Handle symbol defined in IR and referenced in DSO
[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           unsigned int dynamic_ref_after_ir_def;
4936
4937           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4938             {
4939               h = (struct elf_link_hash_entry *) p;
4940               if (h->root.type == bfd_link_hash_warning)
4941                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4942
4943               /* Preserve the maximum alignment and size for common
4944                  symbols even if this dynamic lib isn't on DT_NEEDED
4945                  since it can still be loaded at run time by another
4946                  dynamic lib.  */
4947               if (h->root.type == bfd_link_hash_common)
4948                 {
4949                   size = h->root.u.c.size;
4950                   alignment_power = h->root.u.c.p->alignment_power;
4951                 }
4952               else
4953                 {
4954                   size = 0;
4955                   alignment_power = 0;
4956                 }
4957               /* Preserve dynamic_ref_after_ir_def so that this symbol
4958                  will be exported when the dynamic lib becomes needed
4959                  in the second pass.  */
4960               dynamic_ref_after_ir_def = h->root.dynamic_ref_after_ir_def;
4961               memcpy (p, old_ent, htab->root.table.entsize);
4962               old_ent = (char *) old_ent + htab->root.table.entsize;
4963               h = (struct elf_link_hash_entry *) p;
4964               if (h->root.type == bfd_link_hash_warning)
4965                 {
4966                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4967                   old_ent = (char *) old_ent + htab->root.table.entsize;
4968                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4969                 }
4970               if (h->root.type == bfd_link_hash_common)
4971                 {
4972                   if (size > h->root.u.c.size)
4973                     h->root.u.c.size = size;
4974                   if (alignment_power > h->root.u.c.p->alignment_power)
4975                     h->root.u.c.p->alignment_power = alignment_power;
4976                 }
4977               h->root.dynamic_ref_after_ir_def = dynamic_ref_after_ir_def;
4978             }
4979         }
4980
4981       /* Make a special call to the linker "notice" function to
4982          tell it that symbols added for crefs may need to be removed.  */
4983       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4984         goto error_free_vers;
4985
4986       free (old_tab);
4987       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4988                            alloc_mark);
4989       if (nondeflt_vers != NULL)
4990         free (nondeflt_vers);
4991       return TRUE;
4992     }
4993
4994   if (old_tab != NULL)
4995     {
4996       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4997         goto error_free_vers;
4998       free (old_tab);
4999       old_tab = NULL;
5000     }
5001
5002   /* Now that all the symbols from this input file are created, if
5003      not performing a relocatable link, handle .symver foo, foo@BAR
5004      such that any relocs against foo become foo@BAR.  */
5005   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5006     {
5007       size_t cnt, symidx;
5008
5009       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5010         {
5011           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5012           char *shortname, *p;
5013
5014           p = strchr (h->root.root.string, ELF_VER_CHR);
5015           if (p == NULL
5016               || (h->root.type != bfd_link_hash_defined
5017                   && h->root.type != bfd_link_hash_defweak))
5018             continue;
5019
5020           amt = p - h->root.root.string;
5021           shortname = (char *) bfd_malloc (amt + 1);
5022           if (!shortname)
5023             goto error_free_vers;
5024           memcpy (shortname, h->root.root.string, amt);
5025           shortname[amt] = '\0';
5026
5027           hi = (struct elf_link_hash_entry *)
5028                bfd_link_hash_lookup (&htab->root, shortname,
5029                                      FALSE, FALSE, FALSE);
5030           if (hi != NULL
5031               && hi->root.type == h->root.type
5032               && hi->root.u.def.value == h->root.u.def.value
5033               && hi->root.u.def.section == h->root.u.def.section)
5034             {
5035               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5036               hi->root.type = bfd_link_hash_indirect;
5037               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5038               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5039               sym_hash = elf_sym_hashes (abfd);
5040               if (sym_hash)
5041                 for (symidx = 0; symidx < extsymcount; ++symidx)
5042                   if (sym_hash[symidx] == hi)
5043                     {
5044                       sym_hash[symidx] = h;
5045                       break;
5046                     }
5047             }
5048           free (shortname);
5049         }
5050       free (nondeflt_vers);
5051       nondeflt_vers = NULL;
5052     }
5053
5054   /* Now set the weakdefs field correctly for all the weak defined
5055      symbols we found.  The only way to do this is to search all the
5056      symbols.  Since we only need the information for non functions in
5057      dynamic objects, that's the only time we actually put anything on
5058      the list WEAKS.  We need this information so that if a regular
5059      object refers to a symbol defined weakly in a dynamic object, the
5060      real symbol in the dynamic object is also put in the dynamic
5061      symbols; we also must arrange for both symbols to point to the
5062      same memory location.  We could handle the general case of symbol
5063      aliasing, but a general symbol alias can only be generated in
5064      assembler code, handling it correctly would be very time
5065      consuming, and other ELF linkers don't handle general aliasing
5066      either.  */
5067   if (weaks != NULL)
5068     {
5069       struct elf_link_hash_entry **hpp;
5070       struct elf_link_hash_entry **hppend;
5071       struct elf_link_hash_entry **sorted_sym_hash;
5072       struct elf_link_hash_entry *h;
5073       size_t sym_count;
5074
5075       /* Since we have to search the whole symbol list for each weak
5076          defined symbol, search time for N weak defined symbols will be
5077          O(N^2). Binary search will cut it down to O(NlogN).  */
5078       amt = extsymcount;
5079       amt *= sizeof (struct elf_link_hash_entry *);
5080       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5081       if (sorted_sym_hash == NULL)
5082         goto error_return;
5083       sym_hash = sorted_sym_hash;
5084       hpp = elf_sym_hashes (abfd);
5085       hppend = hpp + extsymcount;
5086       sym_count = 0;
5087       for (; hpp < hppend; hpp++)
5088         {
5089           h = *hpp;
5090           if (h != NULL
5091               && h->root.type == bfd_link_hash_defined
5092               && !bed->is_function_type (h->type))
5093             {
5094               *sym_hash = h;
5095               sym_hash++;
5096               sym_count++;
5097             }
5098         }
5099
5100       qsort (sorted_sym_hash, sym_count,
5101              sizeof (struct elf_link_hash_entry *),
5102              elf_sort_symbol);
5103
5104       while (weaks != NULL)
5105         {
5106           struct elf_link_hash_entry *hlook;
5107           asection *slook;
5108           bfd_vma vlook;
5109           size_t i, j, idx = 0;
5110
5111           hlook = weaks;
5112           weaks = hlook->u.weakdef;
5113           hlook->u.weakdef = NULL;
5114
5115           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5116                       || hlook->root.type == bfd_link_hash_defweak
5117                       || hlook->root.type == bfd_link_hash_common
5118                       || hlook->root.type == bfd_link_hash_indirect);
5119           slook = hlook->root.u.def.section;
5120           vlook = hlook->root.u.def.value;
5121
5122           i = 0;
5123           j = sym_count;
5124           while (i != j)
5125             {
5126               bfd_signed_vma vdiff;
5127               idx = (i + j) / 2;
5128               h = sorted_sym_hash[idx];
5129               vdiff = vlook - h->root.u.def.value;
5130               if (vdiff < 0)
5131                 j = idx;
5132               else if (vdiff > 0)
5133                 i = idx + 1;
5134               else
5135                 {
5136                   int sdiff = slook->id - h->root.u.def.section->id;
5137                   if (sdiff < 0)
5138                     j = idx;
5139                   else if (sdiff > 0)
5140                     i = idx + 1;
5141                   else
5142                     break;
5143                 }
5144             }
5145
5146           /* We didn't find a value/section match.  */
5147           if (i == j)
5148             continue;
5149
5150           /* With multiple aliases, or when the weak symbol is already
5151              strongly defined, we have multiple matching symbols and
5152              the binary search above may land on any of them.  Step
5153              one past the matching symbol(s).  */
5154           while (++idx != j)
5155             {
5156               h = sorted_sym_hash[idx];
5157               if (h->root.u.def.section != slook
5158                   || h->root.u.def.value != vlook)
5159                 break;
5160             }
5161
5162           /* Now look back over the aliases.  Since we sorted by size
5163              as well as value and section, we'll choose the one with
5164              the largest size.  */
5165           while (idx-- != i)
5166             {
5167               h = sorted_sym_hash[idx];
5168
5169               /* Stop if value or section doesn't match.  */
5170               if (h->root.u.def.section != slook
5171                   || h->root.u.def.value != vlook)
5172                 break;
5173               else if (h != hlook)
5174                 {
5175                   hlook->u.weakdef = h;
5176
5177                   /* If the weak definition is in the list of dynamic
5178                      symbols, make sure the real definition is put
5179                      there as well.  */
5180                   if (hlook->dynindx != -1 && h->dynindx == -1)
5181                     {
5182                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5183                         {
5184                         err_free_sym_hash:
5185                           free (sorted_sym_hash);
5186                           goto error_return;
5187                         }
5188                     }
5189
5190                   /* If the real definition is in the list of dynamic
5191                      symbols, make sure the weak definition is put
5192                      there as well.  If we don't do this, then the
5193                      dynamic loader might not merge the entries for the
5194                      real definition and the weak definition.  */
5195                   if (h->dynindx != -1 && hlook->dynindx == -1)
5196                     {
5197                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5198                         goto err_free_sym_hash;
5199                     }
5200                   break;
5201                 }
5202             }
5203         }
5204
5205       free (sorted_sym_hash);
5206     }
5207
5208   if (bed->check_directives
5209       && !(*bed->check_directives) (abfd, info))
5210     return FALSE;
5211
5212   if (!info->check_relocs_after_open_input
5213       && !_bfd_elf_link_check_relocs (abfd, info))
5214     return FALSE;
5215
5216   /* If this is a non-traditional link, try to optimize the handling
5217      of the .stab/.stabstr sections.  */
5218   if (! dynamic
5219       && ! info->traditional_format
5220       && is_elf_hash_table (htab)
5221       && (info->strip != strip_all && info->strip != strip_debugger))
5222     {
5223       asection *stabstr;
5224
5225       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5226       if (stabstr != NULL)
5227         {
5228           bfd_size_type string_offset = 0;
5229           asection *stab;
5230
5231           for (stab = abfd->sections; stab; stab = stab->next)
5232             if (CONST_STRNEQ (stab->name, ".stab")
5233                 && (!stab->name[5] ||
5234                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5235                 && (stab->flags & SEC_MERGE) == 0
5236                 && !bfd_is_abs_section (stab->output_section))
5237               {
5238                 struct bfd_elf_section_data *secdata;
5239
5240                 secdata = elf_section_data (stab);
5241                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5242                                                stabstr, &secdata->sec_info,
5243                                                &string_offset))
5244                   goto error_return;
5245                 if (secdata->sec_info)
5246                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5247             }
5248         }
5249     }
5250
5251   if (is_elf_hash_table (htab) && add_needed)
5252     {
5253       /* Add this bfd to the loaded list.  */
5254       struct elf_link_loaded_list *n;
5255
5256       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5257       if (n == NULL)
5258         goto error_return;
5259       n->abfd = abfd;
5260       n->next = htab->loaded;
5261       htab->loaded = n;
5262     }
5263
5264   return TRUE;
5265
5266  error_free_vers:
5267   if (old_tab != NULL)
5268     free (old_tab);
5269   if (old_strtab != NULL)
5270     free (old_strtab);
5271   if (nondeflt_vers != NULL)
5272     free (nondeflt_vers);
5273   if (extversym != NULL)
5274     free (extversym);
5275  error_free_sym:
5276   if (isymbuf != NULL)
5277     free (isymbuf);
5278  error_return:
5279   return FALSE;
5280 }
5281
5282 /* Return the linker hash table entry of a symbol that might be
5283    satisfied by an archive symbol.  Return -1 on error.  */
5284
5285 struct elf_link_hash_entry *
5286 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5287                                 struct bfd_link_info *info,
5288                                 const char *name)
5289 {
5290   struct elf_link_hash_entry *h;
5291   char *p, *copy;
5292   size_t len, first;
5293
5294   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5295   if (h != NULL)
5296     return h;
5297
5298   /* If this is a default version (the name contains @@), look up the
5299      symbol again with only one `@' as well as without the version.
5300      The effect is that references to the symbol with and without the
5301      version will be matched by the default symbol in the archive.  */
5302
5303   p = strchr (name, ELF_VER_CHR);
5304   if (p == NULL || p[1] != ELF_VER_CHR)
5305     return h;
5306
5307   /* First check with only one `@'.  */
5308   len = strlen (name);
5309   copy = (char *) bfd_alloc (abfd, len);
5310   if (copy == NULL)
5311     return (struct elf_link_hash_entry *) 0 - 1;
5312
5313   first = p - name + 1;
5314   memcpy (copy, name, first);
5315   memcpy (copy + first, name + first + 1, len - first);
5316
5317   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5318   if (h == NULL)
5319     {
5320       /* We also need to check references to the symbol without the
5321          version.  */
5322       copy[first - 1] = '\0';
5323       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5324                                 FALSE, FALSE, TRUE);
5325     }
5326
5327   bfd_release (abfd, copy);
5328   return h;
5329 }
5330
5331 /* Add symbols from an ELF archive file to the linker hash table.  We
5332    don't use _bfd_generic_link_add_archive_symbols because we need to
5333    handle versioned symbols.
5334
5335    Fortunately, ELF archive handling is simpler than that done by
5336    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5337    oddities.  In ELF, if we find a symbol in the archive map, and the
5338    symbol is currently undefined, we know that we must pull in that
5339    object file.
5340
5341    Unfortunately, we do have to make multiple passes over the symbol
5342    table until nothing further is resolved.  */
5343
5344 static bfd_boolean
5345 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5346 {
5347   symindex c;
5348   unsigned char *included = NULL;
5349   carsym *symdefs;
5350   bfd_boolean loop;
5351   bfd_size_type amt;
5352   const struct elf_backend_data *bed;
5353   struct elf_link_hash_entry * (*archive_symbol_lookup)
5354     (bfd *, struct bfd_link_info *, const char *);
5355
5356   if (! bfd_has_map (abfd))
5357     {
5358       /* An empty archive is a special case.  */
5359       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5360         return TRUE;
5361       bfd_set_error (bfd_error_no_armap);
5362       return FALSE;
5363     }
5364
5365   /* Keep track of all symbols we know to be already defined, and all
5366      files we know to be already included.  This is to speed up the
5367      second and subsequent passes.  */
5368   c = bfd_ardata (abfd)->symdef_count;
5369   if (c == 0)
5370     return TRUE;
5371   amt = c;
5372   amt *= sizeof (*included);
5373   included = (unsigned char *) bfd_zmalloc (amt);
5374   if (included == NULL)
5375     return FALSE;
5376
5377   symdefs = bfd_ardata (abfd)->symdefs;
5378   bed = get_elf_backend_data (abfd);
5379   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5380
5381   do
5382     {
5383       file_ptr last;
5384       symindex i;
5385       carsym *symdef;
5386       carsym *symdefend;
5387
5388       loop = FALSE;
5389       last = -1;
5390
5391       symdef = symdefs;
5392       symdefend = symdef + c;
5393       for (i = 0; symdef < symdefend; symdef++, i++)
5394         {
5395           struct elf_link_hash_entry *h;
5396           bfd *element;
5397           struct bfd_link_hash_entry *undefs_tail;
5398           symindex mark;
5399
5400           if (included[i])
5401             continue;
5402           if (symdef->file_offset == last)
5403             {
5404               included[i] = TRUE;
5405               continue;
5406             }
5407
5408           h = archive_symbol_lookup (abfd, info, symdef->name);
5409           if (h == (struct elf_link_hash_entry *) 0 - 1)
5410             goto error_return;
5411
5412           if (h == NULL)
5413             continue;
5414
5415           if (h->root.type == bfd_link_hash_common)
5416             {
5417               /* We currently have a common symbol.  The archive map contains
5418                  a reference to this symbol, so we may want to include it.  We
5419                  only want to include it however, if this archive element
5420                  contains a definition of the symbol, not just another common
5421                  declaration of it.
5422
5423                  Unfortunately some archivers (including GNU ar) will put
5424                  declarations of common symbols into their archive maps, as
5425                  well as real definitions, so we cannot just go by the archive
5426                  map alone.  Instead we must read in the element's symbol
5427                  table and check that to see what kind of symbol definition
5428                  this is.  */
5429               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5430                 continue;
5431             }
5432           else if (h->root.type != bfd_link_hash_undefined)
5433             {
5434               if (h->root.type != bfd_link_hash_undefweak)
5435                 /* Symbol must be defined.  Don't check it again.  */
5436                 included[i] = TRUE;
5437               continue;
5438             }
5439
5440           /* We need to include this archive member.  */
5441           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5442           if (element == NULL)
5443             goto error_return;
5444
5445           if (! bfd_check_format (element, bfd_object))
5446             goto error_return;
5447
5448           undefs_tail = info->hash->undefs_tail;
5449
5450           if (!(*info->callbacks
5451                 ->add_archive_element) (info, element, symdef->name, &element))
5452             continue;
5453           if (!bfd_link_add_symbols (element, info))
5454             goto error_return;
5455
5456           /* If there are any new undefined symbols, we need to make
5457              another pass through the archive in order to see whether
5458              they can be defined.  FIXME: This isn't perfect, because
5459              common symbols wind up on undefs_tail and because an
5460              undefined symbol which is defined later on in this pass
5461              does not require another pass.  This isn't a bug, but it
5462              does make the code less efficient than it could be.  */
5463           if (undefs_tail != info->hash->undefs_tail)
5464             loop = TRUE;
5465
5466           /* Look backward to mark all symbols from this object file
5467              which we have already seen in this pass.  */
5468           mark = i;
5469           do
5470             {
5471               included[mark] = TRUE;
5472               if (mark == 0)
5473                 break;
5474               --mark;
5475             }
5476           while (symdefs[mark].file_offset == symdef->file_offset);
5477
5478           /* We mark subsequent symbols from this object file as we go
5479              on through the loop.  */
5480           last = symdef->file_offset;
5481         }
5482     }
5483   while (loop);
5484
5485   free (included);
5486
5487   return TRUE;
5488
5489  error_return:
5490   if (included != NULL)
5491     free (included);
5492   return FALSE;
5493 }
5494
5495 /* Given an ELF BFD, add symbols to the global hash table as
5496    appropriate.  */
5497
5498 bfd_boolean
5499 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5500 {
5501   switch (bfd_get_format (abfd))
5502     {
5503     case bfd_object:
5504       return elf_link_add_object_symbols (abfd, info);
5505     case bfd_archive:
5506       return elf_link_add_archive_symbols (abfd, info);
5507     default:
5508       bfd_set_error (bfd_error_wrong_format);
5509       return FALSE;
5510     }
5511 }
5512 \f
5513 struct hash_codes_info
5514 {
5515   unsigned long *hashcodes;
5516   bfd_boolean error;
5517 };
5518
5519 /* This function will be called though elf_link_hash_traverse to store
5520    all hash value of the exported symbols in an array.  */
5521
5522 static bfd_boolean
5523 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5524 {
5525   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5526   const char *name;
5527   unsigned long ha;
5528   char *alc = NULL;
5529
5530   /* Ignore indirect symbols.  These are added by the versioning code.  */
5531   if (h->dynindx == -1)
5532     return TRUE;
5533
5534   name = h->root.root.string;
5535   if (h->versioned >= versioned)
5536     {
5537       char *p = strchr (name, ELF_VER_CHR);
5538       if (p != NULL)
5539         {
5540           alc = (char *) bfd_malloc (p - name + 1);
5541           if (alc == NULL)
5542             {
5543               inf->error = TRUE;
5544               return FALSE;
5545             }
5546           memcpy (alc, name, p - name);
5547           alc[p - name] = '\0';
5548           name = alc;
5549         }
5550     }
5551
5552   /* Compute the hash value.  */
5553   ha = bfd_elf_hash (name);
5554
5555   /* Store the found hash value in the array given as the argument.  */
5556   *(inf->hashcodes)++ = ha;
5557
5558   /* And store it in the struct so that we can put it in the hash table
5559      later.  */
5560   h->u.elf_hash_value = ha;
5561
5562   if (alc != NULL)
5563     free (alc);
5564
5565   return TRUE;
5566 }
5567
5568 struct collect_gnu_hash_codes
5569 {
5570   bfd *output_bfd;
5571   const struct elf_backend_data *bed;
5572   unsigned long int nsyms;
5573   unsigned long int maskbits;
5574   unsigned long int *hashcodes;
5575   unsigned long int *hashval;
5576   unsigned long int *indx;
5577   unsigned long int *counts;
5578   bfd_vma *bitmask;
5579   bfd_byte *contents;
5580   long int min_dynindx;
5581   unsigned long int bucketcount;
5582   unsigned long int symindx;
5583   long int local_indx;
5584   long int shift1, shift2;
5585   unsigned long int mask;
5586   bfd_boolean error;
5587 };
5588
5589 /* This function will be called though elf_link_hash_traverse to store
5590    all hash value of the exported symbols in an array.  */
5591
5592 static bfd_boolean
5593 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5594 {
5595   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5596   const char *name;
5597   unsigned long ha;
5598   char *alc = NULL;
5599
5600   /* Ignore indirect symbols.  These are added by the versioning code.  */
5601   if (h->dynindx == -1)
5602     return TRUE;
5603
5604   /* Ignore also local symbols and undefined symbols.  */
5605   if (! (*s->bed->elf_hash_symbol) (h))
5606     return TRUE;
5607
5608   name = h->root.root.string;
5609   if (h->versioned >= versioned)
5610     {
5611       char *p = strchr (name, ELF_VER_CHR);
5612       if (p != NULL)
5613         {
5614           alc = (char *) bfd_malloc (p - name + 1);
5615           if (alc == NULL)
5616             {
5617               s->error = TRUE;
5618               return FALSE;
5619             }
5620           memcpy (alc, name, p - name);
5621           alc[p - name] = '\0';
5622           name = alc;
5623         }
5624     }
5625
5626   /* Compute the hash value.  */
5627   ha = bfd_elf_gnu_hash (name);
5628
5629   /* Store the found hash value in the array for compute_bucket_count,
5630      and also for .dynsym reordering purposes.  */
5631   s->hashcodes[s->nsyms] = ha;
5632   s->hashval[h->dynindx] = ha;
5633   ++s->nsyms;
5634   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5635     s->min_dynindx = h->dynindx;
5636
5637   if (alc != NULL)
5638     free (alc);
5639
5640   return TRUE;
5641 }
5642
5643 /* This function will be called though elf_link_hash_traverse to do
5644    final dynaminc symbol renumbering.  */
5645
5646 static bfd_boolean
5647 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5648 {
5649   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5650   unsigned long int bucket;
5651   unsigned long int val;
5652
5653   /* Ignore indirect symbols.  */
5654   if (h->dynindx == -1)
5655     return TRUE;
5656
5657   /* Ignore also local symbols and undefined symbols.  */
5658   if (! (*s->bed->elf_hash_symbol) (h))
5659     {
5660       if (h->dynindx >= s->min_dynindx)
5661         h->dynindx = s->local_indx++;
5662       return TRUE;
5663     }
5664
5665   bucket = s->hashval[h->dynindx] % s->bucketcount;
5666   val = (s->hashval[h->dynindx] >> s->shift1)
5667         & ((s->maskbits >> s->shift1) - 1);
5668   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5669   s->bitmask[val]
5670     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5671   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5672   if (s->counts[bucket] == 1)
5673     /* Last element terminates the chain.  */
5674     val |= 1;
5675   bfd_put_32 (s->output_bfd, val,
5676               s->contents + (s->indx[bucket] - s->symindx) * 4);
5677   --s->counts[bucket];
5678   h->dynindx = s->indx[bucket]++;
5679   return TRUE;
5680 }
5681
5682 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5683
5684 bfd_boolean
5685 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5686 {
5687   return !(h->forced_local
5688            || h->root.type == bfd_link_hash_undefined
5689            || h->root.type == bfd_link_hash_undefweak
5690            || ((h->root.type == bfd_link_hash_defined
5691                 || h->root.type == bfd_link_hash_defweak)
5692                && h->root.u.def.section->output_section == NULL));
5693 }
5694
5695 /* Array used to determine the number of hash table buckets to use
5696    based on the number of symbols there are.  If there are fewer than
5697    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5698    fewer than 37 we use 17 buckets, and so forth.  We never use more
5699    than 32771 buckets.  */
5700
5701 static const size_t elf_buckets[] =
5702 {
5703   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5704   16411, 32771, 0
5705 };
5706
5707 /* Compute bucket count for hashing table.  We do not use a static set
5708    of possible tables sizes anymore.  Instead we determine for all
5709    possible reasonable sizes of the table the outcome (i.e., the
5710    number of collisions etc) and choose the best solution.  The
5711    weighting functions are not too simple to allow the table to grow
5712    without bounds.  Instead one of the weighting factors is the size.
5713    Therefore the result is always a good payoff between few collisions
5714    (= short chain lengths) and table size.  */
5715 static size_t
5716 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5717                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5718                       unsigned long int nsyms,
5719                       int gnu_hash)
5720 {
5721   size_t best_size = 0;
5722   unsigned long int i;
5723
5724   /* We have a problem here.  The following code to optimize the table
5725      size requires an integer type with more the 32 bits.  If
5726      BFD_HOST_U_64_BIT is set we know about such a type.  */
5727 #ifdef BFD_HOST_U_64_BIT
5728   if (info->optimize)
5729     {
5730       size_t minsize;
5731       size_t maxsize;
5732       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5733       bfd *dynobj = elf_hash_table (info)->dynobj;
5734       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5735       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5736       unsigned long int *counts;
5737       bfd_size_type amt;
5738       unsigned int no_improvement_count = 0;
5739
5740       /* Possible optimization parameters: if we have NSYMS symbols we say
5741          that the hashing table must at least have NSYMS/4 and at most
5742          2*NSYMS buckets.  */
5743       minsize = nsyms / 4;
5744       if (minsize == 0)
5745         minsize = 1;
5746       best_size = maxsize = nsyms * 2;
5747       if (gnu_hash)
5748         {
5749           if (minsize < 2)
5750             minsize = 2;
5751           if ((best_size & 31) == 0)
5752             ++best_size;
5753         }
5754
5755       /* Create array where we count the collisions in.  We must use bfd_malloc
5756          since the size could be large.  */
5757       amt = maxsize;
5758       amt *= sizeof (unsigned long int);
5759       counts = (unsigned long int *) bfd_malloc (amt);
5760       if (counts == NULL)
5761         return 0;
5762
5763       /* Compute the "optimal" size for the hash table.  The criteria is a
5764          minimal chain length.  The minor criteria is (of course) the size
5765          of the table.  */
5766       for (i = minsize; i < maxsize; ++i)
5767         {
5768           /* Walk through the array of hashcodes and count the collisions.  */
5769           BFD_HOST_U_64_BIT max;
5770           unsigned long int j;
5771           unsigned long int fact;
5772
5773           if (gnu_hash && (i & 31) == 0)
5774             continue;
5775
5776           memset (counts, '\0', i * sizeof (unsigned long int));
5777
5778           /* Determine how often each hash bucket is used.  */
5779           for (j = 0; j < nsyms; ++j)
5780             ++counts[hashcodes[j] % i];
5781
5782           /* For the weight function we need some information about the
5783              pagesize on the target.  This is information need not be 100%
5784              accurate.  Since this information is not available (so far) we
5785              define it here to a reasonable default value.  If it is crucial
5786              to have a better value some day simply define this value.  */
5787 # ifndef BFD_TARGET_PAGESIZE
5788 #  define BFD_TARGET_PAGESIZE   (4096)
5789 # endif
5790
5791           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5792              and the chains.  */
5793           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5794
5795 # if 1
5796           /* Variant 1: optimize for short chains.  We add the squares
5797              of all the chain lengths (which favors many small chain
5798              over a few long chains).  */
5799           for (j = 0; j < i; ++j)
5800             max += counts[j] * counts[j];
5801
5802           /* This adds penalties for the overall size of the table.  */
5803           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5804           max *= fact * fact;
5805 # else
5806           /* Variant 2: Optimize a lot more for small table.  Here we
5807              also add squares of the size but we also add penalties for
5808              empty slots (the +1 term).  */
5809           for (j = 0; j < i; ++j)
5810             max += (1 + counts[j]) * (1 + counts[j]);
5811
5812           /* The overall size of the table is considered, but not as
5813              strong as in variant 1, where it is squared.  */
5814           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5815           max *= fact;
5816 # endif
5817
5818           /* Compare with current best results.  */
5819           if (max < best_chlen)
5820             {
5821               best_chlen = max;
5822               best_size = i;
5823               no_improvement_count = 0;
5824             }
5825           /* PR 11843: Avoid futile long searches for the best bucket size
5826              when there are a large number of symbols.  */
5827           else if (++no_improvement_count == 100)
5828             break;
5829         }
5830
5831       free (counts);
5832     }
5833   else
5834 #endif /* defined (BFD_HOST_U_64_BIT) */
5835     {
5836       /* This is the fallback solution if no 64bit type is available or if we
5837          are not supposed to spend much time on optimizations.  We select the
5838          bucket count using a fixed set of numbers.  */
5839       for (i = 0; elf_buckets[i] != 0; i++)
5840         {
5841           best_size = elf_buckets[i];
5842           if (nsyms < elf_buckets[i + 1])
5843             break;
5844         }
5845       if (gnu_hash && best_size < 2)
5846         best_size = 2;
5847     }
5848
5849   return best_size;
5850 }
5851
5852 /* Size any SHT_GROUP section for ld -r.  */
5853
5854 bfd_boolean
5855 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5856 {
5857   bfd *ibfd;
5858
5859   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5860     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5861         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5862       return FALSE;
5863   return TRUE;
5864 }
5865
5866 /* Set a default stack segment size.  The value in INFO wins.  If it
5867    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5868    undefined it is initialized.  */
5869
5870 bfd_boolean
5871 bfd_elf_stack_segment_size (bfd *output_bfd,
5872                             struct bfd_link_info *info,
5873                             const char *legacy_symbol,
5874                             bfd_vma default_size)
5875 {
5876   struct elf_link_hash_entry *h = NULL;
5877
5878   /* Look for legacy symbol.  */
5879   if (legacy_symbol)
5880     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5881                               FALSE, FALSE, FALSE);
5882   if (h && (h->root.type == bfd_link_hash_defined
5883             || h->root.type == bfd_link_hash_defweak)
5884       && h->def_regular
5885       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5886     {
5887       /* The symbol has no type if specified on the command line.  */
5888       h->type = STT_OBJECT;
5889       if (info->stacksize)
5890         /* xgettext:c-format */
5891         _bfd_error_handler (_("%B: stack size specified and %s set"),
5892                             output_bfd, legacy_symbol);
5893       else if (h->root.u.def.section != bfd_abs_section_ptr)
5894         /* xgettext:c-format */
5895         _bfd_error_handler (_("%B: %s not absolute"),
5896                             output_bfd, legacy_symbol);
5897       else
5898         info->stacksize = h->root.u.def.value;
5899     }
5900
5901   if (!info->stacksize)
5902     /* If the user didn't set a size, or explicitly inhibit the
5903        size, set it now.  */
5904     info->stacksize = default_size;
5905
5906   /* Provide the legacy symbol, if it is referenced.  */
5907   if (h && (h->root.type == bfd_link_hash_undefined
5908             || h->root.type == bfd_link_hash_undefweak))
5909     {
5910       struct bfd_link_hash_entry *bh = NULL;
5911
5912       if (!(_bfd_generic_link_add_one_symbol
5913             (info, output_bfd, legacy_symbol,
5914              BSF_GLOBAL, bfd_abs_section_ptr,
5915              info->stacksize >= 0 ? info->stacksize : 0,
5916              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5917         return FALSE;
5918
5919       h = (struct elf_link_hash_entry *) bh;
5920       h->def_regular = 1;
5921       h->type = STT_OBJECT;
5922     }
5923
5924   return TRUE;
5925 }
5926
5927 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
5928
5929 struct elf_gc_sweep_symbol_info
5930 {
5931   struct bfd_link_info *info;
5932   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
5933                        bfd_boolean);
5934 };
5935
5936 static bfd_boolean
5937 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
5938 {
5939   if (!h->mark
5940       && (((h->root.type == bfd_link_hash_defined
5941             || h->root.type == bfd_link_hash_defweak)
5942            && !((h->def_regular || ELF_COMMON_DEF_P (h))
5943                 && h->root.u.def.section->gc_mark))
5944           || h->root.type == bfd_link_hash_undefined
5945           || h->root.type == bfd_link_hash_undefweak))
5946     {
5947       struct elf_gc_sweep_symbol_info *inf;
5948
5949       inf = (struct elf_gc_sweep_symbol_info *) data;
5950       (*inf->hide_symbol) (inf->info, h, TRUE);
5951       h->def_regular = 0;
5952       h->ref_regular = 0;
5953       h->ref_regular_nonweak = 0;
5954     }
5955
5956   return TRUE;
5957 }
5958
5959 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5960    called by the ELF linker emulation before_allocation routine.  We
5961    must set the sizes of the sections before the linker sets the
5962    addresses of the various sections.  */
5963
5964 bfd_boolean
5965 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5966                                const char *soname,
5967                                const char *rpath,
5968                                const char *filter_shlib,
5969                                const char *audit,
5970                                const char *depaudit,
5971                                const char * const *auxiliary_filters,
5972                                struct bfd_link_info *info,
5973                                asection **sinterpptr)
5974 {
5975   bfd *dynobj;
5976   const struct elf_backend_data *bed;
5977
5978   *sinterpptr = NULL;
5979
5980   if (!is_elf_hash_table (info->hash))
5981     return TRUE;
5982
5983   dynobj = elf_hash_table (info)->dynobj;
5984
5985   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5986     {
5987       struct bfd_elf_version_tree *verdefs;
5988       struct elf_info_failed asvinfo;
5989       struct bfd_elf_version_tree *t;
5990       struct bfd_elf_version_expr *d;
5991       struct elf_info_failed eif;
5992       bfd_boolean all_defined;
5993       asection *s;
5994       size_t soname_indx;
5995
5996       eif.info = info;
5997       eif.failed = FALSE;
5998
5999       /* If we are supposed to export all symbols into the dynamic symbol
6000          table (this is not the normal case), then do so.  */
6001       if (info->export_dynamic
6002           || (bfd_link_executable (info) && info->dynamic))
6003         {
6004           elf_link_hash_traverse (elf_hash_table (info),
6005                                   _bfd_elf_export_symbol,
6006                                   &eif);
6007           if (eif.failed)
6008             return FALSE;
6009         }
6010
6011       if (soname != NULL)
6012         {
6013           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6014                                              soname, TRUE);
6015           if (soname_indx == (size_t) -1
6016               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6017             return FALSE;
6018         }
6019       else
6020         soname_indx = (size_t) -1;
6021
6022       /* Make all global versions with definition.  */
6023       for (t = info->version_info; t != NULL; t = t->next)
6024         for (d = t->globals.list; d != NULL; d = d->next)
6025           if (!d->symver && d->literal)
6026             {
6027               const char *verstr, *name;
6028               size_t namelen, verlen, newlen;
6029               char *newname, *p, leading_char;
6030               struct elf_link_hash_entry *newh;
6031
6032               leading_char = bfd_get_symbol_leading_char (output_bfd);
6033               name = d->pattern;
6034               namelen = strlen (name) + (leading_char != '\0');
6035               verstr = t->name;
6036               verlen = strlen (verstr);
6037               newlen = namelen + verlen + 3;
6038
6039               newname = (char *) bfd_malloc (newlen);
6040               if (newname == NULL)
6041                 return FALSE;
6042               newname[0] = leading_char;
6043               memcpy (newname + (leading_char != '\0'), name, namelen);
6044
6045               /* Check the hidden versioned definition.  */
6046               p = newname + namelen;
6047               *p++ = ELF_VER_CHR;
6048               memcpy (p, verstr, verlen + 1);
6049               newh = elf_link_hash_lookup (elf_hash_table (info),
6050                                            newname, FALSE, FALSE,
6051                                            FALSE);
6052               if (newh == NULL
6053                   || (newh->root.type != bfd_link_hash_defined
6054                       && newh->root.type != bfd_link_hash_defweak))
6055                 {
6056                   /* Check the default versioned definition.  */
6057                   *p++ = ELF_VER_CHR;
6058                   memcpy (p, verstr, verlen + 1);
6059                   newh = elf_link_hash_lookup (elf_hash_table (info),
6060                                                newname, FALSE, FALSE,
6061                                                FALSE);
6062                 }
6063               free (newname);
6064
6065               /* Mark this version if there is a definition and it is
6066                  not defined in a shared object.  */
6067               if (newh != NULL
6068                   && !newh->def_dynamic
6069                   && (newh->root.type == bfd_link_hash_defined
6070                       || newh->root.type == bfd_link_hash_defweak))
6071                 d->symver = 1;
6072             }
6073
6074       /* Attach all the symbols to their version information.  */
6075       asvinfo.info = info;
6076       asvinfo.failed = FALSE;
6077
6078       elf_link_hash_traverse (elf_hash_table (info),
6079                               _bfd_elf_link_assign_sym_version,
6080                               &asvinfo);
6081       if (asvinfo.failed)
6082         return FALSE;
6083
6084       if (!info->allow_undefined_version)
6085         {
6086           /* Check if all global versions have a definition.  */
6087           all_defined = TRUE;
6088           for (t = info->version_info; t != NULL; t = t->next)
6089             for (d = t->globals.list; d != NULL; d = d->next)
6090               if (d->literal && !d->symver && !d->script)
6091                 {
6092                   _bfd_error_handler
6093                     (_("%s: undefined version: %s"),
6094                      d->pattern, t->name);
6095                   all_defined = FALSE;
6096                 }
6097
6098           if (!all_defined)
6099             {
6100               bfd_set_error (bfd_error_bad_value);
6101               return FALSE;
6102             }
6103         }
6104
6105       /* Set up the version definition section.  */
6106       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6107       BFD_ASSERT (s != NULL);
6108
6109       /* We may have created additional version definitions if we are
6110          just linking a regular application.  */
6111       verdefs = info->version_info;
6112
6113       /* Skip anonymous version tag.  */
6114       if (verdefs != NULL && verdefs->vernum == 0)
6115         verdefs = verdefs->next;
6116
6117       if (verdefs == NULL && !info->create_default_symver)
6118         s->flags |= SEC_EXCLUDE;
6119       else
6120         {
6121           unsigned int cdefs;
6122           bfd_size_type size;
6123           bfd_byte *p;
6124           Elf_Internal_Verdef def;
6125           Elf_Internal_Verdaux defaux;
6126           struct bfd_link_hash_entry *bh;
6127           struct elf_link_hash_entry *h;
6128           const char *name;
6129
6130           cdefs = 0;
6131           size = 0;
6132
6133           /* Make space for the base version.  */
6134           size += sizeof (Elf_External_Verdef);
6135           size += sizeof (Elf_External_Verdaux);
6136           ++cdefs;
6137
6138           /* Make space for the default version.  */
6139           if (info->create_default_symver)
6140             {
6141               size += sizeof (Elf_External_Verdef);
6142               ++cdefs;
6143             }
6144
6145           for (t = verdefs; t != NULL; t = t->next)
6146             {
6147               struct bfd_elf_version_deps *n;
6148
6149               /* Don't emit base version twice.  */
6150               if (t->vernum == 0)
6151                 continue;
6152
6153               size += sizeof (Elf_External_Verdef);
6154               size += sizeof (Elf_External_Verdaux);
6155               ++cdefs;
6156
6157               for (n = t->deps; n != NULL; n = n->next)
6158                 size += sizeof (Elf_External_Verdaux);
6159             }
6160
6161           s->size = size;
6162           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6163           if (s->contents == NULL && s->size != 0)
6164             return FALSE;
6165
6166           /* Fill in the version definition section.  */
6167
6168           p = s->contents;
6169
6170           def.vd_version = VER_DEF_CURRENT;
6171           def.vd_flags = VER_FLG_BASE;
6172           def.vd_ndx = 1;
6173           def.vd_cnt = 1;
6174           if (info->create_default_symver)
6175             {
6176               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6177               def.vd_next = sizeof (Elf_External_Verdef);
6178             }
6179           else
6180             {
6181               def.vd_aux = sizeof (Elf_External_Verdef);
6182               def.vd_next = (sizeof (Elf_External_Verdef)
6183                              + sizeof (Elf_External_Verdaux));
6184             }
6185
6186           if (soname_indx != (size_t) -1)
6187             {
6188               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6189                                       soname_indx);
6190               def.vd_hash = bfd_elf_hash (soname);
6191               defaux.vda_name = soname_indx;
6192               name = soname;
6193             }
6194           else
6195             {
6196               size_t indx;
6197
6198               name = lbasename (output_bfd->filename);
6199               def.vd_hash = bfd_elf_hash (name);
6200               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6201                                           name, FALSE);
6202               if (indx == (size_t) -1)
6203                 return FALSE;
6204               defaux.vda_name = indx;
6205             }
6206           defaux.vda_next = 0;
6207
6208           _bfd_elf_swap_verdef_out (output_bfd, &def,
6209                                     (Elf_External_Verdef *) p);
6210           p += sizeof (Elf_External_Verdef);
6211           if (info->create_default_symver)
6212             {
6213               /* Add a symbol representing this version.  */
6214               bh = NULL;
6215               if (! (_bfd_generic_link_add_one_symbol
6216                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6217                       0, NULL, FALSE,
6218                       get_elf_backend_data (dynobj)->collect, &bh)))
6219                 return FALSE;
6220               h = (struct elf_link_hash_entry *) bh;
6221               h->non_elf = 0;
6222               h->def_regular = 1;
6223               h->type = STT_OBJECT;
6224               h->verinfo.vertree = NULL;
6225
6226               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6227                 return FALSE;
6228
6229               /* Create a duplicate of the base version with the same
6230                  aux block, but different flags.  */
6231               def.vd_flags = 0;
6232               def.vd_ndx = 2;
6233               def.vd_aux = sizeof (Elf_External_Verdef);
6234               if (verdefs)
6235                 def.vd_next = (sizeof (Elf_External_Verdef)
6236                                + sizeof (Elf_External_Verdaux));
6237               else
6238                 def.vd_next = 0;
6239               _bfd_elf_swap_verdef_out (output_bfd, &def,
6240                                         (Elf_External_Verdef *) p);
6241               p += sizeof (Elf_External_Verdef);
6242             }
6243           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6244                                      (Elf_External_Verdaux *) p);
6245           p += sizeof (Elf_External_Verdaux);
6246
6247           for (t = verdefs; t != NULL; t = t->next)
6248             {
6249               unsigned int cdeps;
6250               struct bfd_elf_version_deps *n;
6251
6252               /* Don't emit the base version twice.  */
6253               if (t->vernum == 0)
6254                 continue;
6255
6256               cdeps = 0;
6257               for (n = t->deps; n != NULL; n = n->next)
6258                 ++cdeps;
6259
6260               /* Add a symbol representing this version.  */
6261               bh = NULL;
6262               if (! (_bfd_generic_link_add_one_symbol
6263                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6264                       0, NULL, FALSE,
6265                       get_elf_backend_data (dynobj)->collect, &bh)))
6266                 return FALSE;
6267               h = (struct elf_link_hash_entry *) bh;
6268               h->non_elf = 0;
6269               h->def_regular = 1;
6270               h->type = STT_OBJECT;
6271               h->verinfo.vertree = t;
6272
6273               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6274                 return FALSE;
6275
6276               def.vd_version = VER_DEF_CURRENT;
6277               def.vd_flags = 0;
6278               if (t->globals.list == NULL
6279                   && t->locals.list == NULL
6280                   && ! t->used)
6281                 def.vd_flags |= VER_FLG_WEAK;
6282               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6283               def.vd_cnt = cdeps + 1;
6284               def.vd_hash = bfd_elf_hash (t->name);
6285               def.vd_aux = sizeof (Elf_External_Verdef);
6286               def.vd_next = 0;
6287
6288               /* If a basever node is next, it *must* be the last node in
6289                  the chain, otherwise Verdef construction breaks.  */
6290               if (t->next != NULL && t->next->vernum == 0)
6291                 BFD_ASSERT (t->next->next == NULL);
6292
6293               if (t->next != NULL && t->next->vernum != 0)
6294                 def.vd_next = (sizeof (Elf_External_Verdef)
6295                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6296
6297               _bfd_elf_swap_verdef_out (output_bfd, &def,
6298                                         (Elf_External_Verdef *) p);
6299               p += sizeof (Elf_External_Verdef);
6300
6301               defaux.vda_name = h->dynstr_index;
6302               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6303                                       h->dynstr_index);
6304               defaux.vda_next = 0;
6305               if (t->deps != NULL)
6306                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6307               t->name_indx = defaux.vda_name;
6308
6309               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6310                                          (Elf_External_Verdaux *) p);
6311               p += sizeof (Elf_External_Verdaux);
6312
6313               for (n = t->deps; n != NULL; n = n->next)
6314                 {
6315                   if (n->version_needed == NULL)
6316                     {
6317                       /* This can happen if there was an error in the
6318                          version script.  */
6319                       defaux.vda_name = 0;
6320                     }
6321                   else
6322                     {
6323                       defaux.vda_name = n->version_needed->name_indx;
6324                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6325                                               defaux.vda_name);
6326                     }
6327                   if (n->next == NULL)
6328                     defaux.vda_next = 0;
6329                   else
6330                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6331
6332                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6333                                              (Elf_External_Verdaux *) p);
6334                   p += sizeof (Elf_External_Verdaux);
6335                 }
6336             }
6337
6338           elf_tdata (output_bfd)->cverdefs = cdefs;
6339         }
6340
6341       /* Work out the size of the version reference section.  */
6342
6343       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6344       BFD_ASSERT (s != NULL);
6345       {
6346         struct elf_find_verdep_info sinfo;
6347
6348         sinfo.info = info;
6349         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6350         if (sinfo.vers == 0)
6351           sinfo.vers = 1;
6352         sinfo.failed = FALSE;
6353
6354         elf_link_hash_traverse (elf_hash_table (info),
6355                                 _bfd_elf_link_find_version_dependencies,
6356                                 &sinfo);
6357         if (sinfo.failed)
6358           return FALSE;
6359
6360         if (elf_tdata (output_bfd)->verref == NULL)
6361           s->flags |= SEC_EXCLUDE;
6362         else
6363           {
6364             Elf_Internal_Verneed *vn;
6365             unsigned int size;
6366             unsigned int crefs;
6367             bfd_byte *p;
6368
6369             /* Build the version dependency section.  */
6370             size = 0;
6371             crefs = 0;
6372             for (vn = elf_tdata (output_bfd)->verref;
6373                  vn != NULL;
6374                  vn = vn->vn_nextref)
6375               {
6376                 Elf_Internal_Vernaux *a;
6377
6378                 size += sizeof (Elf_External_Verneed);
6379                 ++crefs;
6380                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6381                   size += sizeof (Elf_External_Vernaux);
6382               }
6383
6384             s->size = size;
6385             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6386             if (s->contents == NULL)
6387               return FALSE;
6388
6389             p = s->contents;
6390             for (vn = elf_tdata (output_bfd)->verref;
6391                  vn != NULL;
6392                  vn = vn->vn_nextref)
6393               {
6394                 unsigned int caux;
6395                 Elf_Internal_Vernaux *a;
6396                 size_t indx;
6397
6398                 caux = 0;
6399                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6400                   ++caux;
6401
6402                 vn->vn_version = VER_NEED_CURRENT;
6403                 vn->vn_cnt = caux;
6404                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6405                                             elf_dt_name (vn->vn_bfd) != NULL
6406                                             ? elf_dt_name (vn->vn_bfd)
6407                                             : lbasename (vn->vn_bfd->filename),
6408                                             FALSE);
6409                 if (indx == (size_t) -1)
6410                   return FALSE;
6411                 vn->vn_file = indx;
6412                 vn->vn_aux = sizeof (Elf_External_Verneed);
6413                 if (vn->vn_nextref == NULL)
6414                   vn->vn_next = 0;
6415                 else
6416                   vn->vn_next = (sizeof (Elf_External_Verneed)
6417                                 + caux * sizeof (Elf_External_Vernaux));
6418
6419                 _bfd_elf_swap_verneed_out (output_bfd, vn,
6420                                            (Elf_External_Verneed *) p);
6421                 p += sizeof (Elf_External_Verneed);
6422
6423                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6424                   {
6425                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6426                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6427                                                 a->vna_nodename, FALSE);
6428                     if (indx == (size_t) -1)
6429                       return FALSE;
6430                     a->vna_name = indx;
6431                     if (a->vna_nextptr == NULL)
6432                       a->vna_next = 0;
6433                     else
6434                       a->vna_next = sizeof (Elf_External_Vernaux);
6435
6436                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6437                                                (Elf_External_Vernaux *) p);
6438                     p += sizeof (Elf_External_Vernaux);
6439                   }
6440               }
6441
6442             elf_tdata (output_bfd)->cverrefs = crefs;
6443           }
6444       }
6445     }
6446
6447   bed = get_elf_backend_data (output_bfd);
6448
6449   if (info->gc_sections && bed->can_gc_sections)
6450     {
6451       struct elf_gc_sweep_symbol_info sweep_info;
6452       unsigned long section_sym_count;
6453
6454       /* Remove the symbols that were in the swept sections from the
6455          dynamic symbol table.  GCFIXME: Anyone know how to get them
6456          out of the static symbol table as well?  */
6457       sweep_info.info = info;
6458       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6459       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6460                               &sweep_info);
6461
6462       _bfd_elf_link_renumber_dynsyms (output_bfd, info, &section_sym_count);
6463     }
6464
6465   /* Any syms created from now on start with -1 in
6466      got.refcount/offset and plt.refcount/offset.  */
6467   elf_hash_table (info)->init_got_refcount
6468     = elf_hash_table (info)->init_got_offset;
6469   elf_hash_table (info)->init_plt_refcount
6470     = elf_hash_table (info)->init_plt_offset;
6471
6472   if (bfd_link_relocatable (info)
6473       && !_bfd_elf_size_group_sections (info))
6474     return FALSE;
6475
6476   /* The backend may have to create some sections regardless of whether
6477      we're dynamic or not.  */
6478   if (bed->elf_backend_always_size_sections
6479       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6480     return FALSE;
6481
6482   /* Determine any GNU_STACK segment requirements, after the backend
6483      has had a chance to set a default segment size.  */
6484   if (info->execstack)
6485     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6486   else if (info->noexecstack)
6487     elf_stack_flags (output_bfd) = PF_R | PF_W;
6488   else
6489     {
6490       bfd *inputobj;
6491       asection *notesec = NULL;
6492       int exec = 0;
6493
6494       for (inputobj = info->input_bfds;
6495            inputobj;
6496            inputobj = inputobj->link.next)
6497         {
6498           asection *s;
6499
6500           if (inputobj->flags
6501               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6502             continue;
6503           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6504           if (s)
6505             {
6506               if (s->flags & SEC_CODE)
6507                 exec = PF_X;
6508               notesec = s;
6509             }
6510           else if (bed->default_execstack)
6511             exec = PF_X;
6512         }
6513       if (notesec || info->stacksize > 0)
6514         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6515       if (notesec && exec && bfd_link_relocatable (info)
6516           && notesec->output_section != bfd_abs_section_ptr)
6517         notesec->output_section->flags |= SEC_CODE;
6518     }
6519
6520   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6521     {
6522       struct elf_info_failed eif;
6523       struct elf_link_hash_entry *h;
6524       asection *dynstr;
6525       asection *s;
6526
6527       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6528       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6529
6530       if (info->symbolic)
6531         {
6532           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6533             return FALSE;
6534           info->flags |= DF_SYMBOLIC;
6535         }
6536
6537       if (rpath != NULL)
6538         {
6539           size_t indx;
6540           bfd_vma tag;
6541
6542           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6543                                       TRUE);
6544           if (indx == (size_t) -1)
6545             return FALSE;
6546
6547           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6548           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6549             return FALSE;
6550         }
6551
6552       if (filter_shlib != NULL)
6553         {
6554           size_t indx;
6555
6556           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6557                                       filter_shlib, TRUE);
6558           if (indx == (size_t) -1
6559               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6560             return FALSE;
6561         }
6562
6563       if (auxiliary_filters != NULL)
6564         {
6565           const char * const *p;
6566
6567           for (p = auxiliary_filters; *p != NULL; p++)
6568             {
6569               size_t indx;
6570
6571               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6572                                           *p, TRUE);
6573               if (indx == (size_t) -1
6574                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6575                 return FALSE;
6576             }
6577         }
6578
6579       if (audit != NULL)
6580         {
6581           size_t indx;
6582
6583           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6584                                       TRUE);
6585           if (indx == (size_t) -1
6586               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6587             return FALSE;
6588         }
6589
6590       if (depaudit != NULL)
6591         {
6592           size_t indx;
6593
6594           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6595                                       TRUE);
6596           if (indx == (size_t) -1
6597               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6598             return FALSE;
6599         }
6600
6601       eif.info = info;
6602       eif.failed = FALSE;
6603
6604       /* Find all symbols which were defined in a dynamic object and make
6605          the backend pick a reasonable value for them.  */
6606       elf_link_hash_traverse (elf_hash_table (info),
6607                               _bfd_elf_adjust_dynamic_symbol,
6608                               &eif);
6609       if (eif.failed)
6610         return FALSE;
6611
6612       /* Add some entries to the .dynamic section.  We fill in some of the
6613          values later, in bfd_elf_final_link, but we must add the entries
6614          now so that we know the final size of the .dynamic section.  */
6615
6616       /* If there are initialization and/or finalization functions to
6617          call then add the corresponding DT_INIT/DT_FINI entries.  */
6618       h = (info->init_function
6619            ? elf_link_hash_lookup (elf_hash_table (info),
6620                                    info->init_function, FALSE,
6621                                    FALSE, FALSE)
6622            : NULL);
6623       if (h != NULL
6624           && (h->ref_regular
6625               || h->def_regular))
6626         {
6627           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6628             return FALSE;
6629         }
6630       h = (info->fini_function
6631            ? elf_link_hash_lookup (elf_hash_table (info),
6632                                    info->fini_function, FALSE,
6633                                    FALSE, FALSE)
6634            : NULL);
6635       if (h != NULL
6636           && (h->ref_regular
6637               || h->def_regular))
6638         {
6639           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6640             return FALSE;
6641         }
6642
6643       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6644       if (s != NULL && s->linker_has_input)
6645         {
6646           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6647           if (! bfd_link_executable (info))
6648             {
6649               bfd *sub;
6650               asection *o;
6651
6652               for (sub = info->input_bfds; sub != NULL;
6653                    sub = sub->link.next)
6654                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6655                   for (o = sub->sections; o != NULL; o = o->next)
6656                     if (elf_section_data (o)->this_hdr.sh_type
6657                         == SHT_PREINIT_ARRAY)
6658                       {
6659                         _bfd_error_handler
6660                           (_("%B: .preinit_array section is not allowed in DSO"),
6661                            sub);
6662                         break;
6663                       }
6664
6665               bfd_set_error (bfd_error_nonrepresentable_section);
6666               return FALSE;
6667             }
6668
6669           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6670               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6671             return FALSE;
6672         }
6673       s = bfd_get_section_by_name (output_bfd, ".init_array");
6674       if (s != NULL && s->linker_has_input)
6675         {
6676           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6677               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6678             return FALSE;
6679         }
6680       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6681       if (s != NULL && s->linker_has_input)
6682         {
6683           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6684               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6685             return FALSE;
6686         }
6687
6688       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6689       /* If .dynstr is excluded from the link, we don't want any of
6690          these tags.  Strictly, we should be checking each section
6691          individually;  This quick check covers for the case where
6692          someone does a /DISCARD/ : { *(*) }.  */
6693       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6694         {
6695           bfd_size_type strsize;
6696
6697           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6698           if ((info->emit_hash
6699                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6700               || (info->emit_gnu_hash
6701                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6702               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6703               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6704               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6705               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6706                                               bed->s->sizeof_sym))
6707             return FALSE;
6708         }
6709     }
6710
6711   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6712     return FALSE;
6713
6714   /* The backend must work out the sizes of all the other dynamic
6715      sections.  */
6716   if (dynobj != NULL
6717       && bed->elf_backend_size_dynamic_sections != NULL
6718       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6719     return FALSE;
6720
6721   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6722     {
6723       unsigned long section_sym_count;
6724
6725       if (elf_tdata (output_bfd)->cverdefs)
6726         {
6727           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6728
6729           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6730               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6731             return FALSE;
6732         }
6733
6734       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6735         {
6736           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6737             return FALSE;
6738         }
6739       else if (info->flags & DF_BIND_NOW)
6740         {
6741           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6742             return FALSE;
6743         }
6744
6745       if (info->flags_1)
6746         {
6747           if (bfd_link_executable (info))
6748             info->flags_1 &= ~ (DF_1_INITFIRST
6749                                 | DF_1_NODELETE
6750                                 | DF_1_NOOPEN);
6751           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6752             return FALSE;
6753         }
6754
6755       if (elf_tdata (output_bfd)->cverrefs)
6756         {
6757           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6758
6759           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6760               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6761             return FALSE;
6762         }
6763
6764       if ((elf_tdata (output_bfd)->cverrefs == 0
6765            && elf_tdata (output_bfd)->cverdefs == 0)
6766           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6767                                              &section_sym_count) == 0)
6768         {
6769           asection *s;
6770
6771           s = bfd_get_linker_section (dynobj, ".gnu.version");
6772           s->flags |= SEC_EXCLUDE;
6773         }
6774     }
6775   return TRUE;
6776 }
6777
6778 /* Find the first non-excluded output section.  We'll use its
6779    section symbol for some emitted relocs.  */
6780 void
6781 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6782 {
6783   asection *s;
6784
6785   for (s = output_bfd->sections; s != NULL; s = s->next)
6786     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6787         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6788       {
6789         elf_hash_table (info)->text_index_section = s;
6790         break;
6791       }
6792 }
6793
6794 /* Find two non-excluded output sections, one for code, one for data.
6795    We'll use their section symbols for some emitted relocs.  */
6796 void
6797 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6798 {
6799   asection *s;
6800
6801   /* Data first, since setting text_index_section changes
6802      _bfd_elf_link_omit_section_dynsym.  */
6803   for (s = output_bfd->sections; s != NULL; s = s->next)
6804     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6805         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6806       {
6807         elf_hash_table (info)->data_index_section = s;
6808         break;
6809       }
6810
6811   for (s = output_bfd->sections; s != NULL; s = s->next)
6812     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6813          == (SEC_ALLOC | SEC_READONLY))
6814         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6815       {
6816         elf_hash_table (info)->text_index_section = s;
6817         break;
6818       }
6819
6820   if (elf_hash_table (info)->text_index_section == NULL)
6821     elf_hash_table (info)->text_index_section
6822       = elf_hash_table (info)->data_index_section;
6823 }
6824
6825 bfd_boolean
6826 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6827 {
6828   const struct elf_backend_data *bed;
6829
6830   if (!is_elf_hash_table (info->hash))
6831     return TRUE;
6832
6833   bed = get_elf_backend_data (output_bfd);
6834   (*bed->elf_backend_init_index_section) (output_bfd, info);
6835
6836   if (elf_hash_table (info)->dynamic_sections_created)
6837     {
6838       bfd *dynobj;
6839       asection *s;
6840       bfd_size_type dynsymcount;
6841       unsigned long section_sym_count;
6842       unsigned int dtagcount;
6843
6844       dynobj = elf_hash_table (info)->dynobj;
6845
6846       /* Assign dynsym indicies.  In a shared library we generate a
6847          section symbol for each output section, which come first.
6848          Next come all of the back-end allocated local dynamic syms,
6849          followed by the rest of the global symbols.  */
6850
6851       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6852                                                     &section_sym_count);
6853
6854       /* Work out the size of the symbol version section.  */
6855       s = bfd_get_linker_section (dynobj, ".gnu.version");
6856       BFD_ASSERT (s != NULL);
6857       if ((s->flags & SEC_EXCLUDE) == 0)
6858         {
6859           s->size = dynsymcount * sizeof (Elf_External_Versym);
6860           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6861           if (s->contents == NULL)
6862             return FALSE;
6863
6864           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6865             return FALSE;
6866         }
6867
6868       /* Set the size of the .dynsym and .hash sections.  We counted
6869          the number of dynamic symbols in elf_link_add_object_symbols.
6870          We will build the contents of .dynsym and .hash when we build
6871          the final symbol table, because until then we do not know the
6872          correct value to give the symbols.  We built the .dynstr
6873          section as we went along in elf_link_add_object_symbols.  */
6874       s = elf_hash_table (info)->dynsym;
6875       BFD_ASSERT (s != NULL);
6876       s->size = dynsymcount * bed->s->sizeof_sym;
6877
6878       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6879       if (s->contents == NULL)
6880         return FALSE;
6881
6882       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6883          section syms, in case we don't output them all.  */
6884       ++section_sym_count;
6885       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6886
6887       elf_hash_table (info)->bucketcount = 0;
6888
6889       /* Compute the size of the hashing table.  As a side effect this
6890          computes the hash values for all the names we export.  */
6891       if (info->emit_hash)
6892         {
6893           unsigned long int *hashcodes;
6894           struct hash_codes_info hashinf;
6895           bfd_size_type amt;
6896           unsigned long int nsyms;
6897           size_t bucketcount;
6898           size_t hash_entry_size;
6899
6900           /* Compute the hash values for all exported symbols.  At the same
6901              time store the values in an array so that we could use them for
6902              optimizations.  */
6903           amt = dynsymcount * sizeof (unsigned long int);
6904           hashcodes = (unsigned long int *) bfd_malloc (amt);
6905           if (hashcodes == NULL)
6906             return FALSE;
6907           hashinf.hashcodes = hashcodes;
6908           hashinf.error = FALSE;
6909
6910           /* Put all hash values in HASHCODES.  */
6911           elf_link_hash_traverse (elf_hash_table (info),
6912                                   elf_collect_hash_codes, &hashinf);
6913           if (hashinf.error)
6914             {
6915               free (hashcodes);
6916               return FALSE;
6917             }
6918
6919           nsyms = hashinf.hashcodes - hashcodes;
6920           bucketcount
6921             = compute_bucket_count (info, hashcodes, nsyms, 0);
6922           free (hashcodes);
6923
6924           if (bucketcount == 0)
6925             return FALSE;
6926
6927           elf_hash_table (info)->bucketcount = bucketcount;
6928
6929           s = bfd_get_linker_section (dynobj, ".hash");
6930           BFD_ASSERT (s != NULL);
6931           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6932           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6933           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6934           if (s->contents == NULL)
6935             return FALSE;
6936
6937           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6938           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6939                    s->contents + hash_entry_size);
6940         }
6941
6942       if (info->emit_gnu_hash)
6943         {
6944           size_t i, cnt;
6945           unsigned char *contents;
6946           struct collect_gnu_hash_codes cinfo;
6947           bfd_size_type amt;
6948           size_t bucketcount;
6949
6950           memset (&cinfo, 0, sizeof (cinfo));
6951
6952           /* Compute the hash values for all exported symbols.  At the same
6953              time store the values in an array so that we could use them for
6954              optimizations.  */
6955           amt = dynsymcount * 2 * sizeof (unsigned long int);
6956           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6957           if (cinfo.hashcodes == NULL)
6958             return FALSE;
6959
6960           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6961           cinfo.min_dynindx = -1;
6962           cinfo.output_bfd = output_bfd;
6963           cinfo.bed = bed;
6964
6965           /* Put all hash values in HASHCODES.  */
6966           elf_link_hash_traverse (elf_hash_table (info),
6967                                   elf_collect_gnu_hash_codes, &cinfo);
6968           if (cinfo.error)
6969             {
6970               free (cinfo.hashcodes);
6971               return FALSE;
6972             }
6973
6974           bucketcount
6975             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6976
6977           if (bucketcount == 0)
6978             {
6979               free (cinfo.hashcodes);
6980               return FALSE;
6981             }
6982
6983           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6984           BFD_ASSERT (s != NULL);
6985
6986           if (cinfo.nsyms == 0)
6987             {
6988               /* Empty .gnu.hash section is special.  */
6989               BFD_ASSERT (cinfo.min_dynindx == -1);
6990               free (cinfo.hashcodes);
6991               s->size = 5 * 4 + bed->s->arch_size / 8;
6992               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6993               if (contents == NULL)
6994                 return FALSE;
6995               s->contents = contents;
6996               /* 1 empty bucket.  */
6997               bfd_put_32 (output_bfd, 1, contents);
6998               /* SYMIDX above the special symbol 0.  */
6999               bfd_put_32 (output_bfd, 1, contents + 4);
7000               /* Just one word for bitmask.  */
7001               bfd_put_32 (output_bfd, 1, contents + 8);
7002               /* Only hash fn bloom filter.  */
7003               bfd_put_32 (output_bfd, 0, contents + 12);
7004               /* No hashes are valid - empty bitmask.  */
7005               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7006               /* No hashes in the only bucket.  */
7007               bfd_put_32 (output_bfd, 0,
7008                           contents + 16 + bed->s->arch_size / 8);
7009             }
7010           else
7011             {
7012               unsigned long int maskwords, maskbitslog2, x;
7013               BFD_ASSERT (cinfo.min_dynindx != -1);
7014
7015               x = cinfo.nsyms;
7016               maskbitslog2 = 1;
7017               while ((x >>= 1) != 0)
7018                 ++maskbitslog2;
7019               if (maskbitslog2 < 3)
7020                 maskbitslog2 = 5;
7021               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7022                 maskbitslog2 = maskbitslog2 + 3;
7023               else
7024                 maskbitslog2 = maskbitslog2 + 2;
7025               if (bed->s->arch_size == 64)
7026                 {
7027                   if (maskbitslog2 == 5)
7028                     maskbitslog2 = 6;
7029                   cinfo.shift1 = 6;
7030                 }
7031               else
7032                 cinfo.shift1 = 5;
7033               cinfo.mask = (1 << cinfo.shift1) - 1;
7034               cinfo.shift2 = maskbitslog2;
7035               cinfo.maskbits = 1 << maskbitslog2;
7036               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7037               amt = bucketcount * sizeof (unsigned long int) * 2;
7038               amt += maskwords * sizeof (bfd_vma);
7039               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7040               if (cinfo.bitmask == NULL)
7041                 {
7042                   free (cinfo.hashcodes);
7043                   return FALSE;
7044                 }
7045
7046               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7047               cinfo.indx = cinfo.counts + bucketcount;
7048               cinfo.symindx = dynsymcount - cinfo.nsyms;
7049               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7050
7051               /* Determine how often each hash bucket is used.  */
7052               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7053               for (i = 0; i < cinfo.nsyms; ++i)
7054                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7055
7056               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7057                 if (cinfo.counts[i] != 0)
7058                   {
7059                     cinfo.indx[i] = cnt;
7060                     cnt += cinfo.counts[i];
7061                   }
7062               BFD_ASSERT (cnt == dynsymcount);
7063               cinfo.bucketcount = bucketcount;
7064               cinfo.local_indx = cinfo.min_dynindx;
7065
7066               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7067               s->size += cinfo.maskbits / 8;
7068               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7069               if (contents == NULL)
7070                 {
7071                   free (cinfo.bitmask);
7072                   free (cinfo.hashcodes);
7073                   return FALSE;
7074                 }
7075
7076               s->contents = contents;
7077               bfd_put_32 (output_bfd, bucketcount, contents);
7078               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7079               bfd_put_32 (output_bfd, maskwords, contents + 8);
7080               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7081               contents += 16 + cinfo.maskbits / 8;
7082
7083               for (i = 0; i < bucketcount; ++i)
7084                 {
7085                   if (cinfo.counts[i] == 0)
7086                     bfd_put_32 (output_bfd, 0, contents);
7087                   else
7088                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7089                   contents += 4;
7090                 }
7091
7092               cinfo.contents = contents;
7093
7094               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7095               elf_link_hash_traverse (elf_hash_table (info),
7096                                       elf_renumber_gnu_hash_syms, &cinfo);
7097
7098               contents = s->contents + 16;
7099               for (i = 0; i < maskwords; ++i)
7100                 {
7101                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7102                            contents);
7103                   contents += bed->s->arch_size / 8;
7104                 }
7105
7106               free (cinfo.bitmask);
7107               free (cinfo.hashcodes);
7108             }
7109         }
7110
7111       s = bfd_get_linker_section (dynobj, ".dynstr");
7112       BFD_ASSERT (s != NULL);
7113
7114       elf_finalize_dynstr (output_bfd, info);
7115
7116       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7117
7118       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7119         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7120           return FALSE;
7121     }
7122
7123   return TRUE;
7124 }
7125 \f
7126 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7127
7128 static void
7129 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7130                             asection *sec)
7131 {
7132   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7133   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7134 }
7135
7136 /* Finish SHF_MERGE section merging.  */
7137
7138 bfd_boolean
7139 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7140 {
7141   bfd *ibfd;
7142   asection *sec;
7143
7144   if (!is_elf_hash_table (info->hash))
7145     return FALSE;
7146
7147   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7148     if ((ibfd->flags & DYNAMIC) == 0
7149         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7150         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7151             == get_elf_backend_data (obfd)->s->elfclass))
7152       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7153         if ((sec->flags & SEC_MERGE) != 0
7154             && !bfd_is_abs_section (sec->output_section))
7155           {
7156             struct bfd_elf_section_data *secdata;
7157
7158             secdata = elf_section_data (sec);
7159             if (! _bfd_add_merge_section (obfd,
7160                                           &elf_hash_table (info)->merge_info,
7161                                           sec, &secdata->sec_info))
7162               return FALSE;
7163             else if (secdata->sec_info)
7164               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7165           }
7166
7167   if (elf_hash_table (info)->merge_info != NULL)
7168     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7169                          merge_sections_remove_hook);
7170   return TRUE;
7171 }
7172
7173 /* Create an entry in an ELF linker hash table.  */
7174
7175 struct bfd_hash_entry *
7176 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7177                             struct bfd_hash_table *table,
7178                             const char *string)
7179 {
7180   /* Allocate the structure if it has not already been allocated by a
7181      subclass.  */
7182   if (entry == NULL)
7183     {
7184       entry = (struct bfd_hash_entry *)
7185         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7186       if (entry == NULL)
7187         return entry;
7188     }
7189
7190   /* Call the allocation method of the superclass.  */
7191   entry = _bfd_link_hash_newfunc (entry, table, string);
7192   if (entry != NULL)
7193     {
7194       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7195       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7196
7197       /* Set local fields.  */
7198       ret->indx = -1;
7199       ret->dynindx = -1;
7200       ret->got = htab->init_got_refcount;
7201       ret->plt = htab->init_plt_refcount;
7202       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7203                               - offsetof (struct elf_link_hash_entry, size)));
7204       /* Assume that we have been called by a non-ELF symbol reader.
7205          This flag is then reset by the code which reads an ELF input
7206          file.  This ensures that a symbol created by a non-ELF symbol
7207          reader will have the flag set correctly.  */
7208       ret->non_elf = 1;
7209     }
7210
7211   return entry;
7212 }
7213
7214 /* Copy data from an indirect symbol to its direct symbol, hiding the
7215    old indirect symbol.  Also used for copying flags to a weakdef.  */
7216
7217 void
7218 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7219                                   struct elf_link_hash_entry *dir,
7220                                   struct elf_link_hash_entry *ind)
7221 {
7222   struct elf_link_hash_table *htab;
7223
7224   /* Copy down any references that we may have already seen to the
7225      symbol which just became indirect.  */
7226
7227   if (dir->versioned != versioned_hidden)
7228     dir->ref_dynamic |= ind->ref_dynamic;
7229   dir->ref_regular |= ind->ref_regular;
7230   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7231   dir->non_got_ref |= ind->non_got_ref;
7232   dir->needs_plt |= ind->needs_plt;
7233   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7234
7235   if (ind->root.type != bfd_link_hash_indirect)
7236     return;
7237
7238   /* Copy over the global and procedure linkage table refcount entries.
7239      These may have been already set up by a check_relocs routine.  */
7240   htab = elf_hash_table (info);
7241   if (ind->got.refcount > htab->init_got_refcount.refcount)
7242     {
7243       if (dir->got.refcount < 0)
7244         dir->got.refcount = 0;
7245       dir->got.refcount += ind->got.refcount;
7246       ind->got.refcount = htab->init_got_refcount.refcount;
7247     }
7248
7249   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7250     {
7251       if (dir->plt.refcount < 0)
7252         dir->plt.refcount = 0;
7253       dir->plt.refcount += ind->plt.refcount;
7254       ind->plt.refcount = htab->init_plt_refcount.refcount;
7255     }
7256
7257   if (ind->dynindx != -1)
7258     {
7259       if (dir->dynindx != -1)
7260         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7261       dir->dynindx = ind->dynindx;
7262       dir->dynstr_index = ind->dynstr_index;
7263       ind->dynindx = -1;
7264       ind->dynstr_index = 0;
7265     }
7266 }
7267
7268 void
7269 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7270                                 struct elf_link_hash_entry *h,
7271                                 bfd_boolean force_local)
7272 {
7273   /* STT_GNU_IFUNC symbol must go through PLT.  */
7274   if (h->type != STT_GNU_IFUNC)
7275     {
7276       h->plt = elf_hash_table (info)->init_plt_offset;
7277       h->needs_plt = 0;
7278     }
7279   if (force_local)
7280     {
7281       h->forced_local = 1;
7282       if (h->dynindx != -1)
7283         {
7284           h->dynindx = -1;
7285           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7286                                   h->dynstr_index);
7287         }
7288     }
7289 }
7290
7291 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7292    caller.  */
7293
7294 bfd_boolean
7295 _bfd_elf_link_hash_table_init
7296   (struct elf_link_hash_table *table,
7297    bfd *abfd,
7298    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7299                                       struct bfd_hash_table *,
7300                                       const char *),
7301    unsigned int entsize,
7302    enum elf_target_id target_id)
7303 {
7304   bfd_boolean ret;
7305   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7306
7307   table->init_got_refcount.refcount = can_refcount - 1;
7308   table->init_plt_refcount.refcount = can_refcount - 1;
7309   table->init_got_offset.offset = -(bfd_vma) 1;
7310   table->init_plt_offset.offset = -(bfd_vma) 1;
7311   /* The first dynamic symbol is a dummy.  */
7312   table->dynsymcount = 1;
7313
7314   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7315
7316   table->root.type = bfd_link_elf_hash_table;
7317   table->hash_table_id = target_id;
7318
7319   return ret;
7320 }
7321
7322 /* Create an ELF linker hash table.  */
7323
7324 struct bfd_link_hash_table *
7325 _bfd_elf_link_hash_table_create (bfd *abfd)
7326 {
7327   struct elf_link_hash_table *ret;
7328   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7329
7330   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7331   if (ret == NULL)
7332     return NULL;
7333
7334   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7335                                        sizeof (struct elf_link_hash_entry),
7336                                        GENERIC_ELF_DATA))
7337     {
7338       free (ret);
7339       return NULL;
7340     }
7341   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7342
7343   return &ret->root;
7344 }
7345
7346 /* Destroy an ELF linker hash table.  */
7347
7348 void
7349 _bfd_elf_link_hash_table_free (bfd *obfd)
7350 {
7351   struct elf_link_hash_table *htab;
7352
7353   htab = (struct elf_link_hash_table *) obfd->link.hash;
7354   if (htab->dynstr != NULL)
7355     _bfd_elf_strtab_free (htab->dynstr);
7356   _bfd_merge_sections_free (htab->merge_info);
7357   _bfd_generic_link_hash_table_free (obfd);
7358 }
7359
7360 /* This is a hook for the ELF emulation code in the generic linker to
7361    tell the backend linker what file name to use for the DT_NEEDED
7362    entry for a dynamic object.  */
7363
7364 void
7365 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7366 {
7367   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7368       && bfd_get_format (abfd) == bfd_object)
7369     elf_dt_name (abfd) = name;
7370 }
7371
7372 int
7373 bfd_elf_get_dyn_lib_class (bfd *abfd)
7374 {
7375   int lib_class;
7376   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7377       && bfd_get_format (abfd) == bfd_object)
7378     lib_class = elf_dyn_lib_class (abfd);
7379   else
7380     lib_class = 0;
7381   return lib_class;
7382 }
7383
7384 void
7385 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7386 {
7387   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7388       && bfd_get_format (abfd) == bfd_object)
7389     elf_dyn_lib_class (abfd) = lib_class;
7390 }
7391
7392 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7393    the linker ELF emulation code.  */
7394
7395 struct bfd_link_needed_list *
7396 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7397                          struct bfd_link_info *info)
7398 {
7399   if (! is_elf_hash_table (info->hash))
7400     return NULL;
7401   return elf_hash_table (info)->needed;
7402 }
7403
7404 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7405    hook for the linker ELF emulation code.  */
7406
7407 struct bfd_link_needed_list *
7408 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7409                           struct bfd_link_info *info)
7410 {
7411   if (! is_elf_hash_table (info->hash))
7412     return NULL;
7413   return elf_hash_table (info)->runpath;
7414 }
7415
7416 /* Get the name actually used for a dynamic object for a link.  This
7417    is the SONAME entry if there is one.  Otherwise, it is the string
7418    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7419
7420 const char *
7421 bfd_elf_get_dt_soname (bfd *abfd)
7422 {
7423   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7424       && bfd_get_format (abfd) == bfd_object)
7425     return elf_dt_name (abfd);
7426   return NULL;
7427 }
7428
7429 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7430    the ELF linker emulation code.  */
7431
7432 bfd_boolean
7433 bfd_elf_get_bfd_needed_list (bfd *abfd,
7434                              struct bfd_link_needed_list **pneeded)
7435 {
7436   asection *s;
7437   bfd_byte *dynbuf = NULL;
7438   unsigned int elfsec;
7439   unsigned long shlink;
7440   bfd_byte *extdyn, *extdynend;
7441   size_t extdynsize;
7442   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7443
7444   *pneeded = NULL;
7445
7446   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7447       || bfd_get_format (abfd) != bfd_object)
7448     return TRUE;
7449
7450   s = bfd_get_section_by_name (abfd, ".dynamic");
7451   if (s == NULL || s->size == 0)
7452     return TRUE;
7453
7454   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7455     goto error_return;
7456
7457   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7458   if (elfsec == SHN_BAD)
7459     goto error_return;
7460
7461   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7462
7463   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7464   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7465
7466   extdyn = dynbuf;
7467   extdynend = extdyn + s->size;
7468   for (; extdyn < extdynend; extdyn += extdynsize)
7469     {
7470       Elf_Internal_Dyn dyn;
7471
7472       (*swap_dyn_in) (abfd, extdyn, &dyn);
7473
7474       if (dyn.d_tag == DT_NULL)
7475         break;
7476
7477       if (dyn.d_tag == DT_NEEDED)
7478         {
7479           const char *string;
7480           struct bfd_link_needed_list *l;
7481           unsigned int tagv = dyn.d_un.d_val;
7482           bfd_size_type amt;
7483
7484           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7485           if (string == NULL)
7486             goto error_return;
7487
7488           amt = sizeof *l;
7489           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7490           if (l == NULL)
7491             goto error_return;
7492
7493           l->by = abfd;
7494           l->name = string;
7495           l->next = *pneeded;
7496           *pneeded = l;
7497         }
7498     }
7499
7500   free (dynbuf);
7501
7502   return TRUE;
7503
7504  error_return:
7505   if (dynbuf != NULL)
7506     free (dynbuf);
7507   return FALSE;
7508 }
7509
7510 struct elf_symbuf_symbol
7511 {
7512   unsigned long st_name;        /* Symbol name, index in string tbl */
7513   unsigned char st_info;        /* Type and binding attributes */
7514   unsigned char st_other;       /* Visibilty, and target specific */
7515 };
7516
7517 struct elf_symbuf_head
7518 {
7519   struct elf_symbuf_symbol *ssym;
7520   size_t count;
7521   unsigned int st_shndx;
7522 };
7523
7524 struct elf_symbol
7525 {
7526   union
7527     {
7528       Elf_Internal_Sym *isym;
7529       struct elf_symbuf_symbol *ssym;
7530     } u;
7531   const char *name;
7532 };
7533
7534 /* Sort references to symbols by ascending section number.  */
7535
7536 static int
7537 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7538 {
7539   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7540   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7541
7542   return s1->st_shndx - s2->st_shndx;
7543 }
7544
7545 static int
7546 elf_sym_name_compare (const void *arg1, const void *arg2)
7547 {
7548   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7549   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7550   return strcmp (s1->name, s2->name);
7551 }
7552
7553 static struct elf_symbuf_head *
7554 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7555 {
7556   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7557   struct elf_symbuf_symbol *ssym;
7558   struct elf_symbuf_head *ssymbuf, *ssymhead;
7559   size_t i, shndx_count, total_size;
7560
7561   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7562   if (indbuf == NULL)
7563     return NULL;
7564
7565   for (ind = indbuf, i = 0; i < symcount; i++)
7566     if (isymbuf[i].st_shndx != SHN_UNDEF)
7567       *ind++ = &isymbuf[i];
7568   indbufend = ind;
7569
7570   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7571          elf_sort_elf_symbol);
7572
7573   shndx_count = 0;
7574   if (indbufend > indbuf)
7575     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7576       if (ind[0]->st_shndx != ind[1]->st_shndx)
7577         shndx_count++;
7578
7579   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7580                 + (indbufend - indbuf) * sizeof (*ssym));
7581   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7582   if (ssymbuf == NULL)
7583     {
7584       free (indbuf);
7585       return NULL;
7586     }
7587
7588   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7589   ssymbuf->ssym = NULL;
7590   ssymbuf->count = shndx_count;
7591   ssymbuf->st_shndx = 0;
7592   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7593     {
7594       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7595         {
7596           ssymhead++;
7597           ssymhead->ssym = ssym;
7598           ssymhead->count = 0;
7599           ssymhead->st_shndx = (*ind)->st_shndx;
7600         }
7601       ssym->st_name = (*ind)->st_name;
7602       ssym->st_info = (*ind)->st_info;
7603       ssym->st_other = (*ind)->st_other;
7604       ssymhead->count++;
7605     }
7606   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7607               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7608                   == total_size));
7609
7610   free (indbuf);
7611   return ssymbuf;
7612 }
7613
7614 /* Check if 2 sections define the same set of local and global
7615    symbols.  */
7616
7617 static bfd_boolean
7618 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7619                                    struct bfd_link_info *info)
7620 {
7621   bfd *bfd1, *bfd2;
7622   const struct elf_backend_data *bed1, *bed2;
7623   Elf_Internal_Shdr *hdr1, *hdr2;
7624   size_t symcount1, symcount2;
7625   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7626   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7627   Elf_Internal_Sym *isym, *isymend;
7628   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7629   size_t count1, count2, i;
7630   unsigned int shndx1, shndx2;
7631   bfd_boolean result;
7632
7633   bfd1 = sec1->owner;
7634   bfd2 = sec2->owner;
7635
7636   /* Both sections have to be in ELF.  */
7637   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7638       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7639     return FALSE;
7640
7641   if (elf_section_type (sec1) != elf_section_type (sec2))
7642     return FALSE;
7643
7644   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7645   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7646   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7647     return FALSE;
7648
7649   bed1 = get_elf_backend_data (bfd1);
7650   bed2 = get_elf_backend_data (bfd2);
7651   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7652   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7653   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7654   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7655
7656   if (symcount1 == 0 || symcount2 == 0)
7657     return FALSE;
7658
7659   result = FALSE;
7660   isymbuf1 = NULL;
7661   isymbuf2 = NULL;
7662   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7663   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7664
7665   if (ssymbuf1 == NULL)
7666     {
7667       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7668                                        NULL, NULL, NULL);
7669       if (isymbuf1 == NULL)
7670         goto done;
7671
7672       if (!info->reduce_memory_overheads)
7673         elf_tdata (bfd1)->symbuf = ssymbuf1
7674           = elf_create_symbuf (symcount1, isymbuf1);
7675     }
7676
7677   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7678     {
7679       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7680                                        NULL, NULL, NULL);
7681       if (isymbuf2 == NULL)
7682         goto done;
7683
7684       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7685         elf_tdata (bfd2)->symbuf = ssymbuf2
7686           = elf_create_symbuf (symcount2, isymbuf2);
7687     }
7688
7689   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7690     {
7691       /* Optimized faster version.  */
7692       size_t lo, hi, mid;
7693       struct elf_symbol *symp;
7694       struct elf_symbuf_symbol *ssym, *ssymend;
7695
7696       lo = 0;
7697       hi = ssymbuf1->count;
7698       ssymbuf1++;
7699       count1 = 0;
7700       while (lo < hi)
7701         {
7702           mid = (lo + hi) / 2;
7703           if (shndx1 < ssymbuf1[mid].st_shndx)
7704             hi = mid;
7705           else if (shndx1 > ssymbuf1[mid].st_shndx)
7706             lo = mid + 1;
7707           else
7708             {
7709               count1 = ssymbuf1[mid].count;
7710               ssymbuf1 += mid;
7711               break;
7712             }
7713         }
7714
7715       lo = 0;
7716       hi = ssymbuf2->count;
7717       ssymbuf2++;
7718       count2 = 0;
7719       while (lo < hi)
7720         {
7721           mid = (lo + hi) / 2;
7722           if (shndx2 < ssymbuf2[mid].st_shndx)
7723             hi = mid;
7724           else if (shndx2 > ssymbuf2[mid].st_shndx)
7725             lo = mid + 1;
7726           else
7727             {
7728               count2 = ssymbuf2[mid].count;
7729               ssymbuf2 += mid;
7730               break;
7731             }
7732         }
7733
7734       if (count1 == 0 || count2 == 0 || count1 != count2)
7735         goto done;
7736
7737       symtable1
7738         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7739       symtable2
7740         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7741       if (symtable1 == NULL || symtable2 == NULL)
7742         goto done;
7743
7744       symp = symtable1;
7745       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7746            ssym < ssymend; ssym++, symp++)
7747         {
7748           symp->u.ssym = ssym;
7749           symp->name = bfd_elf_string_from_elf_section (bfd1,
7750                                                         hdr1->sh_link,
7751                                                         ssym->st_name);
7752         }
7753
7754       symp = symtable2;
7755       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7756            ssym < ssymend; ssym++, symp++)
7757         {
7758           symp->u.ssym = ssym;
7759           symp->name = bfd_elf_string_from_elf_section (bfd2,
7760                                                         hdr2->sh_link,
7761                                                         ssym->st_name);
7762         }
7763
7764       /* Sort symbol by name.  */
7765       qsort (symtable1, count1, sizeof (struct elf_symbol),
7766              elf_sym_name_compare);
7767       qsort (symtable2, count1, sizeof (struct elf_symbol),
7768              elf_sym_name_compare);
7769
7770       for (i = 0; i < count1; i++)
7771         /* Two symbols must have the same binding, type and name.  */
7772         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7773             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7774             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7775           goto done;
7776
7777       result = TRUE;
7778       goto done;
7779     }
7780
7781   symtable1 = (struct elf_symbol *)
7782       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7783   symtable2 = (struct elf_symbol *)
7784       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7785   if (symtable1 == NULL || symtable2 == NULL)
7786     goto done;
7787
7788   /* Count definitions in the section.  */
7789   count1 = 0;
7790   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7791     if (isym->st_shndx == shndx1)
7792       symtable1[count1++].u.isym = isym;
7793
7794   count2 = 0;
7795   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7796     if (isym->st_shndx == shndx2)
7797       symtable2[count2++].u.isym = isym;
7798
7799   if (count1 == 0 || count2 == 0 || count1 != count2)
7800     goto done;
7801
7802   for (i = 0; i < count1; i++)
7803     symtable1[i].name
7804       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7805                                          symtable1[i].u.isym->st_name);
7806
7807   for (i = 0; i < count2; i++)
7808     symtable2[i].name
7809       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7810                                          symtable2[i].u.isym->st_name);
7811
7812   /* Sort symbol by name.  */
7813   qsort (symtable1, count1, sizeof (struct elf_symbol),
7814          elf_sym_name_compare);
7815   qsort (symtable2, count1, sizeof (struct elf_symbol),
7816          elf_sym_name_compare);
7817
7818   for (i = 0; i < count1; i++)
7819     /* Two symbols must have the same binding, type and name.  */
7820     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7821         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7822         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7823       goto done;
7824
7825   result = TRUE;
7826
7827 done:
7828   if (symtable1)
7829     free (symtable1);
7830   if (symtable2)
7831     free (symtable2);
7832   if (isymbuf1)
7833     free (isymbuf1);
7834   if (isymbuf2)
7835     free (isymbuf2);
7836
7837   return result;
7838 }
7839
7840 /* Return TRUE if 2 section types are compatible.  */
7841
7842 bfd_boolean
7843 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7844                                  bfd *bbfd, const asection *bsec)
7845 {
7846   if (asec == NULL
7847       || bsec == NULL
7848       || abfd->xvec->flavour != bfd_target_elf_flavour
7849       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7850     return TRUE;
7851
7852   return elf_section_type (asec) == elf_section_type (bsec);
7853 }
7854 \f
7855 /* Final phase of ELF linker.  */
7856
7857 /* A structure we use to avoid passing large numbers of arguments.  */
7858
7859 struct elf_final_link_info
7860 {
7861   /* General link information.  */
7862   struct bfd_link_info *info;
7863   /* Output BFD.  */
7864   bfd *output_bfd;
7865   /* Symbol string table.  */
7866   struct elf_strtab_hash *symstrtab;
7867   /* .hash section.  */
7868   asection *hash_sec;
7869   /* symbol version section (.gnu.version).  */
7870   asection *symver_sec;
7871   /* Buffer large enough to hold contents of any section.  */
7872   bfd_byte *contents;
7873   /* Buffer large enough to hold external relocs of any section.  */
7874   void *external_relocs;
7875   /* Buffer large enough to hold internal relocs of any section.  */
7876   Elf_Internal_Rela *internal_relocs;
7877   /* Buffer large enough to hold external local symbols of any input
7878      BFD.  */
7879   bfd_byte *external_syms;
7880   /* And a buffer for symbol section indices.  */
7881   Elf_External_Sym_Shndx *locsym_shndx;
7882   /* Buffer large enough to hold internal local symbols of any input
7883      BFD.  */
7884   Elf_Internal_Sym *internal_syms;
7885   /* Array large enough to hold a symbol index for each local symbol
7886      of any input BFD.  */
7887   long *indices;
7888   /* Array large enough to hold a section pointer for each local
7889      symbol of any input BFD.  */
7890   asection **sections;
7891   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7892   Elf_External_Sym_Shndx *symshndxbuf;
7893   /* Number of STT_FILE syms seen.  */
7894   size_t filesym_count;
7895 };
7896
7897 /* This struct is used to pass information to elf_link_output_extsym.  */
7898
7899 struct elf_outext_info
7900 {
7901   bfd_boolean failed;
7902   bfd_boolean localsyms;
7903   bfd_boolean file_sym_done;
7904   struct elf_final_link_info *flinfo;
7905 };
7906
7907
7908 /* Support for evaluating a complex relocation.
7909
7910    Complex relocations are generalized, self-describing relocations.  The
7911    implementation of them consists of two parts: complex symbols, and the
7912    relocations themselves.
7913
7914    The relocations are use a reserved elf-wide relocation type code (R_RELC
7915    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7916    information (start bit, end bit, word width, etc) into the addend.  This
7917    information is extracted from CGEN-generated operand tables within gas.
7918
7919    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7920    internal) representing prefix-notation expressions, including but not
7921    limited to those sorts of expressions normally encoded as addends in the
7922    addend field.  The symbol mangling format is:
7923
7924    <node> := <literal>
7925           |  <unary-operator> ':' <node>
7926           |  <binary-operator> ':' <node> ':' <node>
7927           ;
7928
7929    <literal> := 's' <digits=N> ':' <N character symbol name>
7930              |  'S' <digits=N> ':' <N character section name>
7931              |  '#' <hexdigits>
7932              ;
7933
7934    <binary-operator> := as in C
7935    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7936
7937 static void
7938 set_symbol_value (bfd *bfd_with_globals,
7939                   Elf_Internal_Sym *isymbuf,
7940                   size_t locsymcount,
7941                   size_t symidx,
7942                   bfd_vma val)
7943 {
7944   struct elf_link_hash_entry **sym_hashes;
7945   struct elf_link_hash_entry *h;
7946   size_t extsymoff = locsymcount;
7947
7948   if (symidx < locsymcount)
7949     {
7950       Elf_Internal_Sym *sym;
7951
7952       sym = isymbuf + symidx;
7953       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7954         {
7955           /* It is a local symbol: move it to the
7956              "absolute" section and give it a value.  */
7957           sym->st_shndx = SHN_ABS;
7958           sym->st_value = val;
7959           return;
7960         }
7961       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7962       extsymoff = 0;
7963     }
7964
7965   /* It is a global symbol: set its link type
7966      to "defined" and give it a value.  */
7967
7968   sym_hashes = elf_sym_hashes (bfd_with_globals);
7969   h = sym_hashes [symidx - extsymoff];
7970   while (h->root.type == bfd_link_hash_indirect
7971          || h->root.type == bfd_link_hash_warning)
7972     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7973   h->root.type = bfd_link_hash_defined;
7974   h->root.u.def.value = val;
7975   h->root.u.def.section = bfd_abs_section_ptr;
7976 }
7977
7978 static bfd_boolean
7979 resolve_symbol (const char *name,
7980                 bfd *input_bfd,
7981                 struct elf_final_link_info *flinfo,
7982                 bfd_vma *result,
7983                 Elf_Internal_Sym *isymbuf,
7984                 size_t locsymcount)
7985 {
7986   Elf_Internal_Sym *sym;
7987   struct bfd_link_hash_entry *global_entry;
7988   const char *candidate = NULL;
7989   Elf_Internal_Shdr *symtab_hdr;
7990   size_t i;
7991
7992   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7993
7994   for (i = 0; i < locsymcount; ++ i)
7995     {
7996       sym = isymbuf + i;
7997
7998       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7999         continue;
8000
8001       candidate = bfd_elf_string_from_elf_section (input_bfd,
8002                                                    symtab_hdr->sh_link,
8003                                                    sym->st_name);
8004 #ifdef DEBUG
8005       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8006               name, candidate, (unsigned long) sym->st_value);
8007 #endif
8008       if (candidate && strcmp (candidate, name) == 0)
8009         {
8010           asection *sec = flinfo->sections [i];
8011
8012           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8013           *result += sec->output_offset + sec->output_section->vma;
8014 #ifdef DEBUG
8015           printf ("Found symbol with value %8.8lx\n",
8016                   (unsigned long) *result);
8017 #endif
8018           return TRUE;
8019         }
8020     }
8021
8022   /* Hmm, haven't found it yet. perhaps it is a global.  */
8023   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8024                                        FALSE, FALSE, TRUE);
8025   if (!global_entry)
8026     return FALSE;
8027
8028   if (global_entry->type == bfd_link_hash_defined
8029       || global_entry->type == bfd_link_hash_defweak)
8030     {
8031       *result = (global_entry->u.def.value
8032                  + global_entry->u.def.section->output_section->vma
8033                  + global_entry->u.def.section->output_offset);
8034 #ifdef DEBUG
8035       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8036               global_entry->root.string, (unsigned long) *result);
8037 #endif
8038       return TRUE;
8039     }
8040
8041   return FALSE;
8042 }
8043
8044 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8045    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8046    names like "foo.end" which is the end address of section "foo".  */
8047    
8048 static bfd_boolean
8049 resolve_section (const char *name,
8050                  asection *sections,
8051                  bfd_vma *result,
8052                  bfd * abfd)
8053 {
8054   asection *curr;
8055   unsigned int len;
8056
8057   for (curr = sections; curr; curr = curr->next)
8058     if (strcmp (curr->name, name) == 0)
8059       {
8060         *result = curr->vma;
8061         return TRUE;
8062       }
8063
8064   /* Hmm. still haven't found it. try pseudo-section names.  */
8065   /* FIXME: This could be coded more efficiently...  */
8066   for (curr = sections; curr; curr = curr->next)
8067     {
8068       len = strlen (curr->name);
8069       if (len > strlen (name))
8070         continue;
8071
8072       if (strncmp (curr->name, name, len) == 0)
8073         {
8074           if (strncmp (".end", name + len, 4) == 0)
8075             {
8076               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8077               return TRUE;
8078             }
8079
8080           /* Insert more pseudo-section names here, if you like.  */
8081         }
8082     }
8083
8084   return FALSE;
8085 }
8086
8087 static void
8088 undefined_reference (const char *reftype, const char *name)
8089 {
8090   /* xgettext:c-format */
8091   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8092                       reftype, name);
8093 }
8094
8095 static bfd_boolean
8096 eval_symbol (bfd_vma *result,
8097              const char **symp,
8098              bfd *input_bfd,
8099              struct elf_final_link_info *flinfo,
8100              bfd_vma dot,
8101              Elf_Internal_Sym *isymbuf,
8102              size_t locsymcount,
8103              int signed_p)
8104 {
8105   size_t len;
8106   size_t symlen;
8107   bfd_vma a;
8108   bfd_vma b;
8109   char symbuf[4096];
8110   const char *sym = *symp;
8111   const char *symend;
8112   bfd_boolean symbol_is_section = FALSE;
8113
8114   len = strlen (sym);
8115   symend = sym + len;
8116
8117   if (len < 1 || len > sizeof (symbuf))
8118     {
8119       bfd_set_error (bfd_error_invalid_operation);
8120       return FALSE;
8121     }
8122
8123   switch (* sym)
8124     {
8125     case '.':
8126       *result = dot;
8127       *symp = sym + 1;
8128       return TRUE;
8129
8130     case '#':
8131       ++sym;
8132       *result = strtoul (sym, (char **) symp, 16);
8133       return TRUE;
8134
8135     case 'S':
8136       symbol_is_section = TRUE;
8137       /* Fall through.  */
8138     case 's':
8139       ++sym;
8140       symlen = strtol (sym, (char **) symp, 10);
8141       sym = *symp + 1; /* Skip the trailing ':'.  */
8142
8143       if (symend < sym || symlen + 1 > sizeof (symbuf))
8144         {
8145           bfd_set_error (bfd_error_invalid_operation);
8146           return FALSE;
8147         }
8148
8149       memcpy (symbuf, sym, symlen);
8150       symbuf[symlen] = '\0';
8151       *symp = sym + symlen;
8152
8153       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8154          the symbol as a section, or vice-versa. so we're pretty liberal in our
8155          interpretation here; section means "try section first", not "must be a
8156          section", and likewise with symbol.  */
8157
8158       if (symbol_is_section)
8159         {
8160           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8161               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8162                                   isymbuf, locsymcount))
8163             {
8164               undefined_reference ("section", symbuf);
8165               return FALSE;
8166             }
8167         }
8168       else
8169         {
8170           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8171                                isymbuf, locsymcount)
8172               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8173                                    result, input_bfd))
8174             {
8175               undefined_reference ("symbol", symbuf);
8176               return FALSE;
8177             }
8178         }
8179
8180       return TRUE;
8181
8182       /* All that remains are operators.  */
8183
8184 #define UNARY_OP(op)                                            \
8185   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8186     {                                                           \
8187       sym += strlen (#op);                                      \
8188       if (*sym == ':')                                          \
8189         ++sym;                                                  \
8190       *symp = sym;                                              \
8191       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8192                         isymbuf, locsymcount, signed_p))        \
8193         return FALSE;                                           \
8194       if (signed_p)                                             \
8195         *result = op ((bfd_signed_vma) a);                      \
8196       else                                                      \
8197         *result = op a;                                         \
8198       return TRUE;                                              \
8199     }
8200
8201 #define BINARY_OP(op)                                           \
8202   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8203     {                                                           \
8204       sym += strlen (#op);                                      \
8205       if (*sym == ':')                                          \
8206         ++sym;                                                  \
8207       *symp = sym;                                              \
8208       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8209                         isymbuf, locsymcount, signed_p))        \
8210         return FALSE;                                           \
8211       ++*symp;                                                  \
8212       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8213                         isymbuf, locsymcount, signed_p))        \
8214         return FALSE;                                           \
8215       if (signed_p)                                             \
8216         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8217       else                                                      \
8218         *result = a op b;                                       \
8219       return TRUE;                                              \
8220     }
8221
8222     default:
8223       UNARY_OP  (0-);
8224       BINARY_OP (<<);
8225       BINARY_OP (>>);
8226       BINARY_OP (==);
8227       BINARY_OP (!=);
8228       BINARY_OP (<=);
8229       BINARY_OP (>=);
8230       BINARY_OP (&&);
8231       BINARY_OP (||);
8232       UNARY_OP  (~);
8233       UNARY_OP  (!);
8234       BINARY_OP (*);
8235       BINARY_OP (/);
8236       BINARY_OP (%);
8237       BINARY_OP (^);
8238       BINARY_OP (|);
8239       BINARY_OP (&);
8240       BINARY_OP (+);
8241       BINARY_OP (-);
8242       BINARY_OP (<);
8243       BINARY_OP (>);
8244 #undef UNARY_OP
8245 #undef BINARY_OP
8246       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8247       bfd_set_error (bfd_error_invalid_operation);
8248       return FALSE;
8249     }
8250 }
8251
8252 static void
8253 put_value (bfd_vma size,
8254            unsigned long chunksz,
8255            bfd *input_bfd,
8256            bfd_vma x,
8257            bfd_byte *location)
8258 {
8259   location += (size - chunksz);
8260
8261   for (; size; size -= chunksz, location -= chunksz)
8262     {
8263       switch (chunksz)
8264         {
8265         case 1:
8266           bfd_put_8 (input_bfd, x, location);
8267           x >>= 8;
8268           break;
8269         case 2:
8270           bfd_put_16 (input_bfd, x, location);
8271           x >>= 16;
8272           break;
8273         case 4:
8274           bfd_put_32 (input_bfd, x, location);
8275           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8276           x >>= 16;
8277           x >>= 16;
8278           break;
8279 #ifdef BFD64
8280         case 8:
8281           bfd_put_64 (input_bfd, x, location);
8282           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8283           x >>= 32;
8284           x >>= 32;
8285           break;
8286 #endif
8287         default:
8288           abort ();
8289           break;
8290         }
8291     }
8292 }
8293
8294 static bfd_vma
8295 get_value (bfd_vma size,
8296            unsigned long chunksz,
8297            bfd *input_bfd,
8298            bfd_byte *location)
8299 {
8300   int shift;
8301   bfd_vma x = 0;
8302
8303   /* Sanity checks.  */
8304   BFD_ASSERT (chunksz <= sizeof (x)
8305               && size >= chunksz
8306               && chunksz != 0
8307               && (size % chunksz) == 0
8308               && input_bfd != NULL
8309               && location != NULL);
8310
8311   if (chunksz == sizeof (x))
8312     {
8313       BFD_ASSERT (size == chunksz);
8314
8315       /* Make sure that we do not perform an undefined shift operation.
8316          We know that size == chunksz so there will only be one iteration
8317          of the loop below.  */
8318       shift = 0;
8319     }
8320   else
8321     shift = 8 * chunksz;
8322
8323   for (; size; size -= chunksz, location += chunksz)
8324     {
8325       switch (chunksz)
8326         {
8327         case 1:
8328           x = (x << shift) | bfd_get_8 (input_bfd, location);
8329           break;
8330         case 2:
8331           x = (x << shift) | bfd_get_16 (input_bfd, location);
8332           break;
8333         case 4:
8334           x = (x << shift) | bfd_get_32 (input_bfd, location);
8335           break;
8336 #ifdef BFD64
8337         case 8:
8338           x = (x << shift) | bfd_get_64 (input_bfd, location);
8339           break;
8340 #endif
8341         default:
8342           abort ();
8343         }
8344     }
8345   return x;
8346 }
8347
8348 static void
8349 decode_complex_addend (unsigned long *start,   /* in bits */
8350                        unsigned long *oplen,   /* in bits */
8351                        unsigned long *len,     /* in bits */
8352                        unsigned long *wordsz,  /* in bytes */
8353                        unsigned long *chunksz, /* in bytes */
8354                        unsigned long *lsb0_p,
8355                        unsigned long *signed_p,
8356                        unsigned long *trunc_p,
8357                        unsigned long encoded)
8358 {
8359   * start     =  encoded        & 0x3F;
8360   * len       = (encoded >>  6) & 0x3F;
8361   * oplen     = (encoded >> 12) & 0x3F;
8362   * wordsz    = (encoded >> 18) & 0xF;
8363   * chunksz   = (encoded >> 22) & 0xF;
8364   * lsb0_p    = (encoded >> 27) & 1;
8365   * signed_p  = (encoded >> 28) & 1;
8366   * trunc_p   = (encoded >> 29) & 1;
8367 }
8368
8369 bfd_reloc_status_type
8370 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8371                                     asection *input_section ATTRIBUTE_UNUSED,
8372                                     bfd_byte *contents,
8373                                     Elf_Internal_Rela *rel,
8374                                     bfd_vma relocation)
8375 {
8376   bfd_vma shift, x, mask;
8377   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8378   bfd_reloc_status_type r;
8379
8380   /*  Perform this reloc, since it is complex.
8381       (this is not to say that it necessarily refers to a complex
8382       symbol; merely that it is a self-describing CGEN based reloc.
8383       i.e. the addend has the complete reloc information (bit start, end,
8384       word size, etc) encoded within it.).  */
8385
8386   decode_complex_addend (&start, &oplen, &len, &wordsz,
8387                          &chunksz, &lsb0_p, &signed_p,
8388                          &trunc_p, rel->r_addend);
8389
8390   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8391
8392   if (lsb0_p)
8393     shift = (start + 1) - len;
8394   else
8395     shift = (8 * wordsz) - (start + len);
8396
8397   x = get_value (wordsz, chunksz, input_bfd,
8398                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8399
8400 #ifdef DEBUG
8401   printf ("Doing complex reloc: "
8402           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8403           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8404           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8405           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8406           oplen, (unsigned long) x, (unsigned long) mask,
8407           (unsigned long) relocation);
8408 #endif
8409
8410   r = bfd_reloc_ok;
8411   if (! trunc_p)
8412     /* Now do an overflow check.  */
8413     r = bfd_check_overflow ((signed_p
8414                              ? complain_overflow_signed
8415                              : complain_overflow_unsigned),
8416                             len, 0, (8 * wordsz),
8417                             relocation);
8418
8419   /* Do the deed.  */
8420   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8421
8422 #ifdef DEBUG
8423   printf ("           relocation: %8.8lx\n"
8424           "         shifted mask: %8.8lx\n"
8425           " shifted/masked reloc: %8.8lx\n"
8426           "               result: %8.8lx\n",
8427           (unsigned long) relocation, (unsigned long) (mask << shift),
8428           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8429 #endif
8430   put_value (wordsz, chunksz, input_bfd, x,
8431              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8432   return r;
8433 }
8434
8435 /* Functions to read r_offset from external (target order) reloc
8436    entry.  Faster than bfd_getl32 et al, because we let the compiler
8437    know the value is aligned.  */
8438
8439 static bfd_vma
8440 ext32l_r_offset (const void *p)
8441 {
8442   union aligned32
8443   {
8444     uint32_t v;
8445     unsigned char c[4];
8446   };
8447   const union aligned32 *a
8448     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8449
8450   uint32_t aval = (  (uint32_t) a->c[0]
8451                    | (uint32_t) a->c[1] << 8
8452                    | (uint32_t) a->c[2] << 16
8453                    | (uint32_t) a->c[3] << 24);
8454   return aval;
8455 }
8456
8457 static bfd_vma
8458 ext32b_r_offset (const void *p)
8459 {
8460   union aligned32
8461   {
8462     uint32_t v;
8463     unsigned char c[4];
8464   };
8465   const union aligned32 *a
8466     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8467
8468   uint32_t aval = (  (uint32_t) a->c[0] << 24
8469                    | (uint32_t) a->c[1] << 16
8470                    | (uint32_t) a->c[2] << 8
8471                    | (uint32_t) a->c[3]);
8472   return aval;
8473 }
8474
8475 #ifdef BFD_HOST_64_BIT
8476 static bfd_vma
8477 ext64l_r_offset (const void *p)
8478 {
8479   union aligned64
8480   {
8481     uint64_t v;
8482     unsigned char c[8];
8483   };
8484   const union aligned64 *a
8485     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8486
8487   uint64_t aval = (  (uint64_t) a->c[0]
8488                    | (uint64_t) a->c[1] << 8
8489                    | (uint64_t) a->c[2] << 16
8490                    | (uint64_t) a->c[3] << 24
8491                    | (uint64_t) a->c[4] << 32
8492                    | (uint64_t) a->c[5] << 40
8493                    | (uint64_t) a->c[6] << 48
8494                    | (uint64_t) a->c[7] << 56);
8495   return aval;
8496 }
8497
8498 static bfd_vma
8499 ext64b_r_offset (const void *p)
8500 {
8501   union aligned64
8502   {
8503     uint64_t v;
8504     unsigned char c[8];
8505   };
8506   const union aligned64 *a
8507     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8508
8509   uint64_t aval = (  (uint64_t) a->c[0] << 56
8510                    | (uint64_t) a->c[1] << 48
8511                    | (uint64_t) a->c[2] << 40
8512                    | (uint64_t) a->c[3] << 32
8513                    | (uint64_t) a->c[4] << 24
8514                    | (uint64_t) a->c[5] << 16
8515                    | (uint64_t) a->c[6] << 8
8516                    | (uint64_t) a->c[7]);
8517   return aval;
8518 }
8519 #endif
8520
8521 /* When performing a relocatable link, the input relocations are
8522    preserved.  But, if they reference global symbols, the indices
8523    referenced must be updated.  Update all the relocations found in
8524    RELDATA.  */
8525
8526 static bfd_boolean
8527 elf_link_adjust_relocs (bfd *abfd,
8528                         asection *sec,
8529                         struct bfd_elf_section_reloc_data *reldata,
8530                         bfd_boolean sort)
8531 {
8532   unsigned int i;
8533   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8534   bfd_byte *erela;
8535   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8536   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8537   bfd_vma r_type_mask;
8538   int r_sym_shift;
8539   unsigned int count = reldata->count;
8540   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8541
8542   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8543     {
8544       swap_in = bed->s->swap_reloc_in;
8545       swap_out = bed->s->swap_reloc_out;
8546     }
8547   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8548     {
8549       swap_in = bed->s->swap_reloca_in;
8550       swap_out = bed->s->swap_reloca_out;
8551     }
8552   else
8553     abort ();
8554
8555   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8556     abort ();
8557
8558   if (bed->s->arch_size == 32)
8559     {
8560       r_type_mask = 0xff;
8561       r_sym_shift = 8;
8562     }
8563   else
8564     {
8565       r_type_mask = 0xffffffff;
8566       r_sym_shift = 32;
8567     }
8568
8569   erela = reldata->hdr->contents;
8570   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8571     {
8572       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8573       unsigned int j;
8574
8575       if (*rel_hash == NULL)
8576         continue;
8577
8578       BFD_ASSERT ((*rel_hash)->indx >= 0);
8579
8580       (*swap_in) (abfd, erela, irela);
8581       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8582         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8583                            | (irela[j].r_info & r_type_mask));
8584       (*swap_out) (abfd, irela, erela);
8585     }
8586
8587   if (bed->elf_backend_update_relocs)
8588     (*bed->elf_backend_update_relocs) (sec, reldata);
8589
8590   if (sort && count != 0)
8591     {
8592       bfd_vma (*ext_r_off) (const void *);
8593       bfd_vma r_off;
8594       size_t elt_size;
8595       bfd_byte *base, *end, *p, *loc;
8596       bfd_byte *buf = NULL;
8597
8598       if (bed->s->arch_size == 32)
8599         {
8600           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8601             ext_r_off = ext32l_r_offset;
8602           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8603             ext_r_off = ext32b_r_offset;
8604           else
8605             abort ();
8606         }
8607       else
8608         {
8609 #ifdef BFD_HOST_64_BIT
8610           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8611             ext_r_off = ext64l_r_offset;
8612           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8613             ext_r_off = ext64b_r_offset;
8614           else
8615 #endif
8616             abort ();
8617         }
8618
8619       /*  Must use a stable sort here.  A modified insertion sort,
8620           since the relocs are mostly sorted already.  */
8621       elt_size = reldata->hdr->sh_entsize;
8622       base = reldata->hdr->contents;
8623       end = base + count * elt_size;
8624       if (elt_size > sizeof (Elf64_External_Rela))
8625         abort ();
8626
8627       /* Ensure the first element is lowest.  This acts as a sentinel,
8628          speeding the main loop below.  */
8629       r_off = (*ext_r_off) (base);
8630       for (p = loc = base; (p += elt_size) < end; )
8631         {
8632           bfd_vma r_off2 = (*ext_r_off) (p);
8633           if (r_off > r_off2)
8634             {
8635               r_off = r_off2;
8636               loc = p;
8637             }
8638         }
8639       if (loc != base)
8640         {
8641           /* Don't just swap *base and *loc as that changes the order
8642              of the original base[0] and base[1] if they happen to
8643              have the same r_offset.  */
8644           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8645           memcpy (onebuf, loc, elt_size);
8646           memmove (base + elt_size, base, loc - base);
8647           memcpy (base, onebuf, elt_size);
8648         }
8649
8650       for (p = base + elt_size; (p += elt_size) < end; )
8651         {
8652           /* base to p is sorted, *p is next to insert.  */
8653           r_off = (*ext_r_off) (p);
8654           /* Search the sorted region for location to insert.  */
8655           loc = p - elt_size;
8656           while (r_off < (*ext_r_off) (loc))
8657             loc -= elt_size;
8658           loc += elt_size;
8659           if (loc != p)
8660             {
8661               /* Chances are there is a run of relocs to insert here,
8662                  from one of more input files.  Files are not always
8663                  linked in order due to the way elf_link_input_bfd is
8664                  called.  See pr17666.  */
8665               size_t sortlen = p - loc;
8666               bfd_vma r_off2 = (*ext_r_off) (loc);
8667               size_t runlen = elt_size;
8668               size_t buf_size = 96 * 1024;
8669               while (p + runlen < end
8670                      && (sortlen <= buf_size
8671                          || runlen + elt_size <= buf_size)
8672                      && r_off2 > (*ext_r_off) (p + runlen))
8673                 runlen += elt_size;
8674               if (buf == NULL)
8675                 {
8676                   buf = bfd_malloc (buf_size);
8677                   if (buf == NULL)
8678                     return FALSE;
8679                 }
8680               if (runlen < sortlen)
8681                 {
8682                   memcpy (buf, p, runlen);
8683                   memmove (loc + runlen, loc, sortlen);
8684                   memcpy (loc, buf, runlen);
8685                 }
8686               else
8687                 {
8688                   memcpy (buf, loc, sortlen);
8689                   memmove (loc, p, runlen);
8690                   memcpy (loc + runlen, buf, sortlen);
8691                 }
8692               p += runlen - elt_size;
8693             }
8694         }
8695       /* Hashes are no longer valid.  */
8696       free (reldata->hashes);
8697       reldata->hashes = NULL;
8698       free (buf);
8699     }
8700   return TRUE;
8701 }
8702
8703 struct elf_link_sort_rela
8704 {
8705   union {
8706     bfd_vma offset;
8707     bfd_vma sym_mask;
8708   } u;
8709   enum elf_reloc_type_class type;
8710   /* We use this as an array of size int_rels_per_ext_rel.  */
8711   Elf_Internal_Rela rela[1];
8712 };
8713
8714 static int
8715 elf_link_sort_cmp1 (const void *A, const void *B)
8716 {
8717   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8718   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8719   int relativea, relativeb;
8720
8721   relativea = a->type == reloc_class_relative;
8722   relativeb = b->type == reloc_class_relative;
8723
8724   if (relativea < relativeb)
8725     return 1;
8726   if (relativea > relativeb)
8727     return -1;
8728   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8729     return -1;
8730   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8731     return 1;
8732   if (a->rela->r_offset < b->rela->r_offset)
8733     return -1;
8734   if (a->rela->r_offset > b->rela->r_offset)
8735     return 1;
8736   return 0;
8737 }
8738
8739 static int
8740 elf_link_sort_cmp2 (const void *A, const void *B)
8741 {
8742   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8743   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8744
8745   if (a->type < b->type)
8746     return -1;
8747   if (a->type > b->type)
8748     return 1;
8749   if (a->u.offset < b->u.offset)
8750     return -1;
8751   if (a->u.offset > b->u.offset)
8752     return 1;
8753   if (a->rela->r_offset < b->rela->r_offset)
8754     return -1;
8755   if (a->rela->r_offset > b->rela->r_offset)
8756     return 1;
8757   return 0;
8758 }
8759
8760 static size_t
8761 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8762 {
8763   asection *dynamic_relocs;
8764   asection *rela_dyn;
8765   asection *rel_dyn;
8766   bfd_size_type count, size;
8767   size_t i, ret, sort_elt, ext_size;
8768   bfd_byte *sort, *s_non_relative, *p;
8769   struct elf_link_sort_rela *sq;
8770   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8771   int i2e = bed->s->int_rels_per_ext_rel;
8772   unsigned int opb = bfd_octets_per_byte (abfd);
8773   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8774   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8775   struct bfd_link_order *lo;
8776   bfd_vma r_sym_mask;
8777   bfd_boolean use_rela;
8778
8779   /* Find a dynamic reloc section.  */
8780   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8781   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8782   if (rela_dyn != NULL && rela_dyn->size > 0
8783       && rel_dyn != NULL && rel_dyn->size > 0)
8784     {
8785       bfd_boolean use_rela_initialised = FALSE;
8786
8787       /* This is just here to stop gcc from complaining.
8788          Its initialization checking code is not perfect.  */
8789       use_rela = TRUE;
8790
8791       /* Both sections are present.  Examine the sizes
8792          of the indirect sections to help us choose.  */
8793       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8794         if (lo->type == bfd_indirect_link_order)
8795           {
8796             asection *o = lo->u.indirect.section;
8797
8798             if ((o->size % bed->s->sizeof_rela) == 0)
8799               {
8800                 if ((o->size % bed->s->sizeof_rel) == 0)
8801                   /* Section size is divisible by both rel and rela sizes.
8802                      It is of no help to us.  */
8803                   ;
8804                 else
8805                   {
8806                     /* Section size is only divisible by rela.  */
8807                     if (use_rela_initialised && (use_rela == FALSE))
8808                       {
8809                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8810                                               "they are in more than one size"),
8811                                             abfd);
8812                         bfd_set_error (bfd_error_invalid_operation);
8813                         return 0;
8814                       }
8815                     else
8816                       {
8817                         use_rela = TRUE;
8818                         use_rela_initialised = TRUE;
8819                       }
8820                   }
8821               }
8822             else if ((o->size % bed->s->sizeof_rel) == 0)
8823               {
8824                 /* Section size is only divisible by rel.  */
8825                 if (use_rela_initialised && (use_rela == TRUE))
8826                   {
8827                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8828                                           "they are in more than one size"),
8829                                         abfd);
8830                     bfd_set_error (bfd_error_invalid_operation);
8831                     return 0;
8832                   }
8833                 else
8834                   {
8835                     use_rela = FALSE;
8836                     use_rela_initialised = TRUE;
8837                   }
8838               }
8839             else
8840               {
8841                 /* The section size is not divisible by either -
8842                    something is wrong.  */
8843                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8844                                       "they are of an unknown size"), abfd);
8845                 bfd_set_error (bfd_error_invalid_operation);
8846                 return 0;
8847               }
8848           }
8849
8850       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8851         if (lo->type == bfd_indirect_link_order)
8852           {
8853             asection *o = lo->u.indirect.section;
8854
8855             if ((o->size % bed->s->sizeof_rela) == 0)
8856               {
8857                 if ((o->size % bed->s->sizeof_rel) == 0)
8858                   /* Section size is divisible by both rel and rela sizes.
8859                      It is of no help to us.  */
8860                   ;
8861                 else
8862                   {
8863                     /* Section size is only divisible by rela.  */
8864                     if (use_rela_initialised && (use_rela == FALSE))
8865                       {
8866                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8867                                               "they are in more than one size"),
8868                                             abfd);
8869                         bfd_set_error (bfd_error_invalid_operation);
8870                         return 0;
8871                       }
8872                     else
8873                       {
8874                         use_rela = TRUE;
8875                         use_rela_initialised = TRUE;
8876                       }
8877                   }
8878               }
8879             else if ((o->size % bed->s->sizeof_rel) == 0)
8880               {
8881                 /* Section size is only divisible by rel.  */
8882                 if (use_rela_initialised && (use_rela == TRUE))
8883                   {
8884                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8885                                           "they are in more than one size"),
8886                                         abfd);
8887                     bfd_set_error (bfd_error_invalid_operation);
8888                     return 0;
8889                   }
8890                 else
8891                   {
8892                     use_rela = FALSE;
8893                     use_rela_initialised = TRUE;
8894                   }
8895               }
8896             else
8897               {
8898                 /* The section size is not divisible by either -
8899                    something is wrong.  */
8900                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8901                                       "they are of an unknown size"), abfd);
8902                 bfd_set_error (bfd_error_invalid_operation);
8903                 return 0;
8904               }
8905           }
8906
8907       if (! use_rela_initialised)
8908         /* Make a guess.  */
8909         use_rela = TRUE;
8910     }
8911   else if (rela_dyn != NULL && rela_dyn->size > 0)
8912     use_rela = TRUE;
8913   else if (rel_dyn != NULL && rel_dyn->size > 0)
8914     use_rela = FALSE;
8915   else
8916     return 0;
8917
8918   if (use_rela)
8919     {
8920       dynamic_relocs = rela_dyn;
8921       ext_size = bed->s->sizeof_rela;
8922       swap_in = bed->s->swap_reloca_in;
8923       swap_out = bed->s->swap_reloca_out;
8924     }
8925   else
8926     {
8927       dynamic_relocs = rel_dyn;
8928       ext_size = bed->s->sizeof_rel;
8929       swap_in = bed->s->swap_reloc_in;
8930       swap_out = bed->s->swap_reloc_out;
8931     }
8932
8933   size = 0;
8934   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8935     if (lo->type == bfd_indirect_link_order)
8936       size += lo->u.indirect.section->size;
8937
8938   if (size != dynamic_relocs->size)
8939     return 0;
8940
8941   sort_elt = (sizeof (struct elf_link_sort_rela)
8942               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8943
8944   count = dynamic_relocs->size / ext_size;
8945   if (count == 0)
8946     return 0;
8947   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8948
8949   if (sort == NULL)
8950     {
8951       (*info->callbacks->warning)
8952         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8953       return 0;
8954     }
8955
8956   if (bed->s->arch_size == 32)
8957     r_sym_mask = ~(bfd_vma) 0xff;
8958   else
8959     r_sym_mask = ~(bfd_vma) 0xffffffff;
8960
8961   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8962     if (lo->type == bfd_indirect_link_order)
8963       {
8964         bfd_byte *erel, *erelend;
8965         asection *o = lo->u.indirect.section;
8966
8967         if (o->contents == NULL && o->size != 0)
8968           {
8969             /* This is a reloc section that is being handled as a normal
8970                section.  See bfd_section_from_shdr.  We can't combine
8971                relocs in this case.  */
8972             free (sort);
8973             return 0;
8974           }
8975         erel = o->contents;
8976         erelend = o->contents + o->size;
8977         p = sort + o->output_offset * opb / ext_size * sort_elt;
8978
8979         while (erel < erelend)
8980           {
8981             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8982
8983             (*swap_in) (abfd, erel, s->rela);
8984             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8985             s->u.sym_mask = r_sym_mask;
8986             p += sort_elt;
8987             erel += ext_size;
8988           }
8989       }
8990
8991   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8992
8993   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8994     {
8995       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8996       if (s->type != reloc_class_relative)
8997         break;
8998     }
8999   ret = i;
9000   s_non_relative = p;
9001
9002   sq = (struct elf_link_sort_rela *) s_non_relative;
9003   for (; i < count; i++, p += sort_elt)
9004     {
9005       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9006       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9007         sq = sp;
9008       sp->u.offset = sq->rela->r_offset;
9009     }
9010
9011   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9012
9013   struct elf_link_hash_table *htab = elf_hash_table (info);
9014   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9015     {
9016       /* We have plt relocs in .rela.dyn.  */
9017       sq = (struct elf_link_sort_rela *) sort;
9018       for (i = 0; i < count; i++)
9019         if (sq[count - i - 1].type != reloc_class_plt)
9020           break;
9021       if (i != 0 && htab->srelplt->size == i * ext_size)
9022         {
9023           struct bfd_link_order **plo;
9024           /* Put srelplt link_order last.  This is so the output_offset
9025              set in the next loop is correct for DT_JMPREL.  */
9026           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9027             if ((*plo)->type == bfd_indirect_link_order
9028                 && (*plo)->u.indirect.section == htab->srelplt)
9029               {
9030                 lo = *plo;
9031                 *plo = lo->next;
9032               }
9033             else
9034               plo = &(*plo)->next;
9035           *plo = lo;
9036           lo->next = NULL;
9037           dynamic_relocs->map_tail.link_order = lo;
9038         }
9039     }
9040
9041   p = sort;
9042   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9043     if (lo->type == bfd_indirect_link_order)
9044       {
9045         bfd_byte *erel, *erelend;
9046         asection *o = lo->u.indirect.section;
9047
9048         erel = o->contents;
9049         erelend = o->contents + o->size;
9050         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9051         while (erel < erelend)
9052           {
9053             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9054             (*swap_out) (abfd, s->rela, erel);
9055             p += sort_elt;
9056             erel += ext_size;
9057           }
9058       }
9059
9060   free (sort);
9061   *psec = dynamic_relocs;
9062   return ret;
9063 }
9064
9065 /* Add a symbol to the output symbol string table.  */
9066
9067 static int
9068 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9069                            const char *name,
9070                            Elf_Internal_Sym *elfsym,
9071                            asection *input_sec,
9072                            struct elf_link_hash_entry *h)
9073 {
9074   int (*output_symbol_hook)
9075     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9076      struct elf_link_hash_entry *);
9077   struct elf_link_hash_table *hash_table;
9078   const struct elf_backend_data *bed;
9079   bfd_size_type strtabsize;
9080
9081   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9082
9083   bed = get_elf_backend_data (flinfo->output_bfd);
9084   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9085   if (output_symbol_hook != NULL)
9086     {
9087       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9088       if (ret != 1)
9089         return ret;
9090     }
9091
9092   if (name == NULL
9093       || *name == '\0'
9094       || (input_sec->flags & SEC_EXCLUDE))
9095     elfsym->st_name = (unsigned long) -1;
9096   else
9097     {
9098       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9099          to get the final offset for st_name.  */
9100       elfsym->st_name
9101         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9102                                                name, FALSE);
9103       if (elfsym->st_name == (unsigned long) -1)
9104         return 0;
9105     }
9106
9107   hash_table = elf_hash_table (flinfo->info);
9108   strtabsize = hash_table->strtabsize;
9109   if (strtabsize <= hash_table->strtabcount)
9110     {
9111       strtabsize += strtabsize;
9112       hash_table->strtabsize = strtabsize;
9113       strtabsize *= sizeof (*hash_table->strtab);
9114       hash_table->strtab
9115         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9116                                                  strtabsize);
9117       if (hash_table->strtab == NULL)
9118         return 0;
9119     }
9120   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9121   hash_table->strtab[hash_table->strtabcount].dest_index
9122     = hash_table->strtabcount;
9123   hash_table->strtab[hash_table->strtabcount].destshndx_index
9124     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9125
9126   bfd_get_symcount (flinfo->output_bfd) += 1;
9127   hash_table->strtabcount += 1;
9128
9129   return 1;
9130 }
9131
9132 /* Swap symbols out to the symbol table and flush the output symbols to
9133    the file.  */
9134
9135 static bfd_boolean
9136 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9137 {
9138   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9139   bfd_size_type amt;
9140   size_t i;
9141   const struct elf_backend_data *bed;
9142   bfd_byte *symbuf;
9143   Elf_Internal_Shdr *hdr;
9144   file_ptr pos;
9145   bfd_boolean ret;
9146
9147   if (!hash_table->strtabcount)
9148     return TRUE;
9149
9150   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9151
9152   bed = get_elf_backend_data (flinfo->output_bfd);
9153
9154   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9155   symbuf = (bfd_byte *) bfd_malloc (amt);
9156   if (symbuf == NULL)
9157     return FALSE;
9158
9159   if (flinfo->symshndxbuf)
9160     {
9161       amt = sizeof (Elf_External_Sym_Shndx);
9162       amt *= bfd_get_symcount (flinfo->output_bfd);
9163       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9164       if (flinfo->symshndxbuf == NULL)
9165         {
9166           free (symbuf);
9167           return FALSE;
9168         }
9169     }
9170
9171   for (i = 0; i < hash_table->strtabcount; i++)
9172     {
9173       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9174       if (elfsym->sym.st_name == (unsigned long) -1)
9175         elfsym->sym.st_name = 0;
9176       else
9177         elfsym->sym.st_name
9178           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9179                                                     elfsym->sym.st_name);
9180       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9181                                ((bfd_byte *) symbuf
9182                                 + (elfsym->dest_index
9183                                    * bed->s->sizeof_sym)),
9184                                (flinfo->symshndxbuf
9185                                 + elfsym->destshndx_index));
9186     }
9187
9188   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9189   pos = hdr->sh_offset + hdr->sh_size;
9190   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9191   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9192       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9193     {
9194       hdr->sh_size += amt;
9195       ret = TRUE;
9196     }
9197   else
9198     ret = FALSE;
9199
9200   free (symbuf);
9201
9202   free (hash_table->strtab);
9203   hash_table->strtab = NULL;
9204
9205   return ret;
9206 }
9207
9208 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9209
9210 static bfd_boolean
9211 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9212 {
9213   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9214       && sym->st_shndx < SHN_LORESERVE)
9215     {
9216       /* The gABI doesn't support dynamic symbols in output sections
9217          beyond 64k.  */
9218       _bfd_error_handler
9219         /* xgettext:c-format */
9220         (_("%B: Too many sections: %d (>= %d)"),
9221          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9222       bfd_set_error (bfd_error_nonrepresentable_section);
9223       return FALSE;
9224     }
9225   return TRUE;
9226 }
9227
9228 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9229    allowing an unsatisfied unversioned symbol in the DSO to match a
9230    versioned symbol that would normally require an explicit version.
9231    We also handle the case that a DSO references a hidden symbol
9232    which may be satisfied by a versioned symbol in another DSO.  */
9233
9234 static bfd_boolean
9235 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9236                                  const struct elf_backend_data *bed,
9237                                  struct elf_link_hash_entry *h)
9238 {
9239   bfd *abfd;
9240   struct elf_link_loaded_list *loaded;
9241
9242   if (!is_elf_hash_table (info->hash))
9243     return FALSE;
9244
9245   /* Check indirect symbol.  */
9246   while (h->root.type == bfd_link_hash_indirect)
9247     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9248
9249   switch (h->root.type)
9250     {
9251     default:
9252       abfd = NULL;
9253       break;
9254
9255     case bfd_link_hash_undefined:
9256     case bfd_link_hash_undefweak:
9257       abfd = h->root.u.undef.abfd;
9258       if (abfd == NULL
9259           || (abfd->flags & DYNAMIC) == 0
9260           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9261         return FALSE;
9262       break;
9263
9264     case bfd_link_hash_defined:
9265     case bfd_link_hash_defweak:
9266       abfd = h->root.u.def.section->owner;
9267       break;
9268
9269     case bfd_link_hash_common:
9270       abfd = h->root.u.c.p->section->owner;
9271       break;
9272     }
9273   BFD_ASSERT (abfd != NULL);
9274
9275   for (loaded = elf_hash_table (info)->loaded;
9276        loaded != NULL;
9277        loaded = loaded->next)
9278     {
9279       bfd *input;
9280       Elf_Internal_Shdr *hdr;
9281       size_t symcount;
9282       size_t extsymcount;
9283       size_t extsymoff;
9284       Elf_Internal_Shdr *versymhdr;
9285       Elf_Internal_Sym *isym;
9286       Elf_Internal_Sym *isymend;
9287       Elf_Internal_Sym *isymbuf;
9288       Elf_External_Versym *ever;
9289       Elf_External_Versym *extversym;
9290
9291       input = loaded->abfd;
9292
9293       /* We check each DSO for a possible hidden versioned definition.  */
9294       if (input == abfd
9295           || (input->flags & DYNAMIC) == 0
9296           || elf_dynversym (input) == 0)
9297         continue;
9298
9299       hdr = &elf_tdata (input)->dynsymtab_hdr;
9300
9301       symcount = hdr->sh_size / bed->s->sizeof_sym;
9302       if (elf_bad_symtab (input))
9303         {
9304           extsymcount = symcount;
9305           extsymoff = 0;
9306         }
9307       else
9308         {
9309           extsymcount = symcount - hdr->sh_info;
9310           extsymoff = hdr->sh_info;
9311         }
9312
9313       if (extsymcount == 0)
9314         continue;
9315
9316       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9317                                       NULL, NULL, NULL);
9318       if (isymbuf == NULL)
9319         return FALSE;
9320
9321       /* Read in any version definitions.  */
9322       versymhdr = &elf_tdata (input)->dynversym_hdr;
9323       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9324       if (extversym == NULL)
9325         goto error_ret;
9326
9327       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9328           || (bfd_bread (extversym, versymhdr->sh_size, input)
9329               != versymhdr->sh_size))
9330         {
9331           free (extversym);
9332         error_ret:
9333           free (isymbuf);
9334           return FALSE;
9335         }
9336
9337       ever = extversym + extsymoff;
9338       isymend = isymbuf + extsymcount;
9339       for (isym = isymbuf; isym < isymend; isym++, ever++)
9340         {
9341           const char *name;
9342           Elf_Internal_Versym iver;
9343           unsigned short version_index;
9344
9345           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9346               || isym->st_shndx == SHN_UNDEF)
9347             continue;
9348
9349           name = bfd_elf_string_from_elf_section (input,
9350                                                   hdr->sh_link,
9351                                                   isym->st_name);
9352           if (strcmp (name, h->root.root.string) != 0)
9353             continue;
9354
9355           _bfd_elf_swap_versym_in (input, ever, &iver);
9356
9357           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9358               && !(h->def_regular
9359                    && h->forced_local))
9360             {
9361               /* If we have a non-hidden versioned sym, then it should
9362                  have provided a definition for the undefined sym unless
9363                  it is defined in a non-shared object and forced local.
9364                */
9365               abort ();
9366             }
9367
9368           version_index = iver.vs_vers & VERSYM_VERSION;
9369           if (version_index == 1 || version_index == 2)
9370             {
9371               /* This is the base or first version.  We can use it.  */
9372               free (extversym);
9373               free (isymbuf);
9374               return TRUE;
9375             }
9376         }
9377
9378       free (extversym);
9379       free (isymbuf);
9380     }
9381
9382   return FALSE;
9383 }
9384
9385 /* Convert ELF common symbol TYPE.  */
9386
9387 static int
9388 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9389 {
9390   /* Commom symbol can only appear in relocatable link.  */
9391   if (!bfd_link_relocatable (info))
9392     abort ();
9393   switch (info->elf_stt_common)
9394     {
9395     case unchanged:
9396       break;
9397     case elf_stt_common:
9398       type = STT_COMMON;
9399       break;
9400     case no_elf_stt_common:
9401       type = STT_OBJECT;
9402       break;
9403     }
9404   return type;
9405 }
9406
9407 /* Add an external symbol to the symbol table.  This is called from
9408    the hash table traversal routine.  When generating a shared object,
9409    we go through the symbol table twice.  The first time we output
9410    anything that might have been forced to local scope in a version
9411    script.  The second time we output the symbols that are still
9412    global symbols.  */
9413
9414 static bfd_boolean
9415 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9416 {
9417   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9418   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9419   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9420   bfd_boolean strip;
9421   Elf_Internal_Sym sym;
9422   asection *input_sec;
9423   const struct elf_backend_data *bed;
9424   long indx;
9425   int ret;
9426   unsigned int type;
9427
9428   if (h->root.type == bfd_link_hash_warning)
9429     {
9430       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9431       if (h->root.type == bfd_link_hash_new)
9432         return TRUE;
9433     }
9434
9435   /* Decide whether to output this symbol in this pass.  */
9436   if (eoinfo->localsyms)
9437     {
9438       if (!h->forced_local)
9439         return TRUE;
9440     }
9441   else
9442     {
9443       if (h->forced_local)
9444         return TRUE;
9445     }
9446
9447   bed = get_elf_backend_data (flinfo->output_bfd);
9448
9449   if (h->root.type == bfd_link_hash_undefined)
9450     {
9451       /* If we have an undefined symbol reference here then it must have
9452          come from a shared library that is being linked in.  (Undefined
9453          references in regular files have already been handled unless
9454          they are in unreferenced sections which are removed by garbage
9455          collection).  */
9456       bfd_boolean ignore_undef = FALSE;
9457
9458       /* Some symbols may be special in that the fact that they're
9459          undefined can be safely ignored - let backend determine that.  */
9460       if (bed->elf_backend_ignore_undef_symbol)
9461         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9462
9463       /* If we are reporting errors for this situation then do so now.  */
9464       if (!ignore_undef
9465           && h->ref_dynamic
9466           && (!h->ref_regular || flinfo->info->gc_sections)
9467           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9468           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9469         (*flinfo->info->callbacks->undefined_symbol)
9470           (flinfo->info, h->root.root.string,
9471            h->ref_regular ? NULL : h->root.u.undef.abfd,
9472            NULL, 0,
9473            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9474
9475       /* Strip a global symbol defined in a discarded section.  */
9476       if (h->indx == -3)
9477         return TRUE;
9478     }
9479
9480   /* We should also warn if a forced local symbol is referenced from
9481      shared libraries.  */
9482   if (bfd_link_executable (flinfo->info)
9483       && h->forced_local
9484       && h->ref_dynamic
9485       && h->def_regular
9486       && !h->dynamic_def
9487       && h->ref_dynamic_nonweak
9488       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9489     {
9490       bfd *def_bfd;
9491       const char *msg;
9492       struct elf_link_hash_entry *hi = h;
9493
9494       /* Check indirect symbol.  */
9495       while (hi->root.type == bfd_link_hash_indirect)
9496         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9497
9498       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9499         /* xgettext:c-format */
9500         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9501       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9502         /* xgettext:c-format */
9503         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9504       else
9505         /* xgettext:c-format */
9506         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9507       def_bfd = flinfo->output_bfd;
9508       if (hi->root.u.def.section != bfd_abs_section_ptr)
9509         def_bfd = hi->root.u.def.section->owner;
9510       _bfd_error_handler (msg, flinfo->output_bfd,
9511                           h->root.root.string, def_bfd);
9512       bfd_set_error (bfd_error_bad_value);
9513       eoinfo->failed = TRUE;
9514       return FALSE;
9515     }
9516
9517   /* We don't want to output symbols that have never been mentioned by
9518      a regular file, or that we have been told to strip.  However, if
9519      h->indx is set to -2, the symbol is used by a reloc and we must
9520      output it.  */
9521   strip = FALSE;
9522   if (h->indx == -2)
9523     ;
9524   else if ((h->def_dynamic
9525             || h->ref_dynamic
9526             || h->root.type == bfd_link_hash_new)
9527            && !h->def_regular
9528            && !h->ref_regular)
9529     strip = TRUE;
9530   else if (flinfo->info->strip == strip_all)
9531     strip = TRUE;
9532   else if (flinfo->info->strip == strip_some
9533            && bfd_hash_lookup (flinfo->info->keep_hash,
9534                                h->root.root.string, FALSE, FALSE) == NULL)
9535     strip = TRUE;
9536   else if ((h->root.type == bfd_link_hash_defined
9537             || h->root.type == bfd_link_hash_defweak)
9538            && ((flinfo->info->strip_discarded
9539                 && discarded_section (h->root.u.def.section))
9540                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9541                    && h->root.u.def.section->owner != NULL
9542                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9543     strip = TRUE;
9544   else if ((h->root.type == bfd_link_hash_undefined
9545             || h->root.type == bfd_link_hash_undefweak)
9546            && h->root.u.undef.abfd != NULL
9547            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9548     strip = TRUE;
9549
9550   type = h->type;
9551
9552   /* If we're stripping it, and it's not a dynamic symbol, there's
9553      nothing else to do.   However, if it is a forced local symbol or
9554      an ifunc symbol we need to give the backend finish_dynamic_symbol
9555      function a chance to make it dynamic.  */
9556   if (strip
9557       && h->dynindx == -1
9558       && type != STT_GNU_IFUNC
9559       && !h->forced_local)
9560     return TRUE;
9561
9562   sym.st_value = 0;
9563   sym.st_size = h->size;
9564   sym.st_other = h->other;
9565   switch (h->root.type)
9566     {
9567     default:
9568     case bfd_link_hash_new:
9569     case bfd_link_hash_warning:
9570       abort ();
9571       return FALSE;
9572
9573     case bfd_link_hash_undefined:
9574     case bfd_link_hash_undefweak:
9575       input_sec = bfd_und_section_ptr;
9576       sym.st_shndx = SHN_UNDEF;
9577       break;
9578
9579     case bfd_link_hash_defined:
9580     case bfd_link_hash_defweak:
9581       {
9582         input_sec = h->root.u.def.section;
9583         if (input_sec->output_section != NULL)
9584           {
9585             sym.st_shndx =
9586               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9587                                                  input_sec->output_section);
9588             if (sym.st_shndx == SHN_BAD)
9589               {
9590                 _bfd_error_handler
9591                   /* xgettext:c-format */
9592                   (_("%B: could not find output section %A for input section %A"),
9593                    flinfo->output_bfd, input_sec->output_section, input_sec);
9594                 bfd_set_error (bfd_error_nonrepresentable_section);
9595                 eoinfo->failed = TRUE;
9596                 return FALSE;
9597               }
9598
9599             /* ELF symbols in relocatable files are section relative,
9600                but in nonrelocatable files they are virtual
9601                addresses.  */
9602             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9603             if (!bfd_link_relocatable (flinfo->info))
9604               {
9605                 sym.st_value += input_sec->output_section->vma;
9606                 if (h->type == STT_TLS)
9607                   {
9608                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9609                     if (tls_sec != NULL)
9610                       sym.st_value -= tls_sec->vma;
9611                   }
9612               }
9613           }
9614         else
9615           {
9616             BFD_ASSERT (input_sec->owner == NULL
9617                         || (input_sec->owner->flags & DYNAMIC) != 0);
9618             sym.st_shndx = SHN_UNDEF;
9619             input_sec = bfd_und_section_ptr;
9620           }
9621       }
9622       break;
9623
9624     case bfd_link_hash_common:
9625       input_sec = h->root.u.c.p->section;
9626       sym.st_shndx = bed->common_section_index (input_sec);
9627       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9628       break;
9629
9630     case bfd_link_hash_indirect:
9631       /* These symbols are created by symbol versioning.  They point
9632          to the decorated version of the name.  For example, if the
9633          symbol foo@@GNU_1.2 is the default, which should be used when
9634          foo is used with no version, then we add an indirect symbol
9635          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9636          since the indirected symbol is already in the hash table.  */
9637       return TRUE;
9638     }
9639
9640   if (type == STT_COMMON || type == STT_OBJECT)
9641     switch (h->root.type)
9642       {
9643       case bfd_link_hash_common:
9644         type = elf_link_convert_common_type (flinfo->info, type);
9645         break;
9646       case bfd_link_hash_defined:
9647       case bfd_link_hash_defweak:
9648         if (bed->common_definition (&sym))
9649           type = elf_link_convert_common_type (flinfo->info, type);
9650         else
9651           type = STT_OBJECT;
9652         break;
9653       case bfd_link_hash_undefined:
9654       case bfd_link_hash_undefweak:
9655         break;
9656       default:
9657         abort ();
9658       }
9659
9660   if (h->forced_local)
9661     {
9662       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9663       /* Turn off visibility on local symbol.  */
9664       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9665     }
9666   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9667   else if (h->unique_global && h->def_regular)
9668     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9669   else if (h->root.type == bfd_link_hash_undefweak
9670            || h->root.type == bfd_link_hash_defweak)
9671     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9672   else
9673     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9674   sym.st_target_internal = h->target_internal;
9675
9676   /* Give the processor backend a chance to tweak the symbol value,
9677      and also to finish up anything that needs to be done for this
9678      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9679      forced local syms when non-shared is due to a historical quirk.
9680      STT_GNU_IFUNC symbol must go through PLT.  */
9681   if ((h->type == STT_GNU_IFUNC
9682        && h->def_regular
9683        && !bfd_link_relocatable (flinfo->info))
9684       || ((h->dynindx != -1
9685            || h->forced_local)
9686           && ((bfd_link_pic (flinfo->info)
9687                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9688                    || h->root.type != bfd_link_hash_undefweak))
9689               || !h->forced_local)
9690           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9691     {
9692       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9693              (flinfo->output_bfd, flinfo->info, h, &sym)))
9694         {
9695           eoinfo->failed = TRUE;
9696           return FALSE;
9697         }
9698     }
9699
9700   /* If we are marking the symbol as undefined, and there are no
9701      non-weak references to this symbol from a regular object, then
9702      mark the symbol as weak undefined; if there are non-weak
9703      references, mark the symbol as strong.  We can't do this earlier,
9704      because it might not be marked as undefined until the
9705      finish_dynamic_symbol routine gets through with it.  */
9706   if (sym.st_shndx == SHN_UNDEF
9707       && h->ref_regular
9708       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9709           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9710     {
9711       int bindtype;
9712       type = ELF_ST_TYPE (sym.st_info);
9713
9714       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9715       if (type == STT_GNU_IFUNC)
9716         type = STT_FUNC;
9717
9718       if (h->ref_regular_nonweak)
9719         bindtype = STB_GLOBAL;
9720       else
9721         bindtype = STB_WEAK;
9722       sym.st_info = ELF_ST_INFO (bindtype, type);
9723     }
9724
9725   /* If this is a symbol defined in a dynamic library, don't use the
9726      symbol size from the dynamic library.  Relinking an executable
9727      against a new library may introduce gratuitous changes in the
9728      executable's symbols if we keep the size.  */
9729   if (sym.st_shndx == SHN_UNDEF
9730       && !h->def_regular
9731       && h->def_dynamic)
9732     sym.st_size = 0;
9733
9734   /* If a non-weak symbol with non-default visibility is not defined
9735      locally, it is a fatal error.  */
9736   if (!bfd_link_relocatable (flinfo->info)
9737       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9738       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9739       && h->root.type == bfd_link_hash_undefined
9740       && !h->def_regular)
9741     {
9742       const char *msg;
9743
9744       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9745         /* xgettext:c-format */
9746         msg = _("%B: protected symbol `%s' isn't defined");
9747       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9748         /* xgettext:c-format */
9749         msg = _("%B: internal symbol `%s' isn't defined");
9750       else
9751         /* xgettext:c-format */
9752         msg = _("%B: hidden symbol `%s' isn't defined");
9753       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9754       bfd_set_error (bfd_error_bad_value);
9755       eoinfo->failed = TRUE;
9756       return FALSE;
9757     }
9758
9759   /* If this symbol should be put in the .dynsym section, then put it
9760      there now.  We already know the symbol index.  We also fill in
9761      the entry in the .hash section.  */
9762   if (elf_hash_table (flinfo->info)->dynsym != NULL
9763       && h->dynindx != -1
9764       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9765     {
9766       bfd_byte *esym;
9767
9768       /* Since there is no version information in the dynamic string,
9769          if there is no version info in symbol version section, we will
9770          have a run-time problem if not linking executable, referenced
9771          by shared library, or not bound locally.  */
9772       if (h->verinfo.verdef == NULL
9773           && (!bfd_link_executable (flinfo->info)
9774               || h->ref_dynamic
9775               || !h->def_regular))
9776         {
9777           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9778
9779           if (p && p [1] != '\0')
9780             {
9781               _bfd_error_handler
9782                 /* xgettext:c-format */
9783                 (_("%B: No symbol version section for versioned symbol `%s'"),
9784                  flinfo->output_bfd, h->root.root.string);
9785               eoinfo->failed = TRUE;
9786               return FALSE;
9787             }
9788         }
9789
9790       sym.st_name = h->dynstr_index;
9791       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9792               + h->dynindx * bed->s->sizeof_sym);
9793       if (!check_dynsym (flinfo->output_bfd, &sym))
9794         {
9795           eoinfo->failed = TRUE;
9796           return FALSE;
9797         }
9798       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9799
9800       if (flinfo->hash_sec != NULL)
9801         {
9802           size_t hash_entry_size;
9803           bfd_byte *bucketpos;
9804           bfd_vma chain;
9805           size_t bucketcount;
9806           size_t bucket;
9807
9808           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9809           bucket = h->u.elf_hash_value % bucketcount;
9810
9811           hash_entry_size
9812             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9813           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9814                        + (bucket + 2) * hash_entry_size);
9815           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9816           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9817                    bucketpos);
9818           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9819                    ((bfd_byte *) flinfo->hash_sec->contents
9820                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9821         }
9822
9823       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9824         {
9825           Elf_Internal_Versym iversym;
9826           Elf_External_Versym *eversym;
9827
9828           if (!h->def_regular)
9829             {
9830               if (h->verinfo.verdef == NULL
9831                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9832                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9833                 iversym.vs_vers = 0;
9834               else
9835                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9836             }
9837           else
9838             {
9839               if (h->verinfo.vertree == NULL)
9840                 iversym.vs_vers = 1;
9841               else
9842                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9843               if (flinfo->info->create_default_symver)
9844                 iversym.vs_vers++;
9845             }
9846
9847           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9848              defined locally.  */
9849           if (h->versioned == versioned_hidden && h->def_regular)
9850             iversym.vs_vers |= VERSYM_HIDDEN;
9851
9852           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9853           eversym += h->dynindx;
9854           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9855         }
9856     }
9857
9858   /* If the symbol is undefined, and we didn't output it to .dynsym,
9859      strip it from .symtab too.  Obviously we can't do this for
9860      relocatable output or when needed for --emit-relocs.  */
9861   else if (input_sec == bfd_und_section_ptr
9862            && h->indx != -2
9863            && !bfd_link_relocatable (flinfo->info))
9864     return TRUE;
9865   /* Also strip others that we couldn't earlier due to dynamic symbol
9866      processing.  */
9867   if (strip)
9868     return TRUE;
9869   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9870     return TRUE;
9871
9872   /* Output a FILE symbol so that following locals are not associated
9873      with the wrong input file.  We need one for forced local symbols
9874      if we've seen more than one FILE symbol or when we have exactly
9875      one FILE symbol but global symbols are present in a file other
9876      than the one with the FILE symbol.  We also need one if linker
9877      defined symbols are present.  In practice these conditions are
9878      always met, so just emit the FILE symbol unconditionally.  */
9879   if (eoinfo->localsyms
9880       && !eoinfo->file_sym_done
9881       && eoinfo->flinfo->filesym_count != 0)
9882     {
9883       Elf_Internal_Sym fsym;
9884
9885       memset (&fsym, 0, sizeof (fsym));
9886       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9887       fsym.st_shndx = SHN_ABS;
9888       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9889                                       bfd_und_section_ptr, NULL))
9890         return FALSE;
9891
9892       eoinfo->file_sym_done = TRUE;
9893     }
9894
9895   indx = bfd_get_symcount (flinfo->output_bfd);
9896   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9897                                    input_sec, h);
9898   if (ret == 0)
9899     {
9900       eoinfo->failed = TRUE;
9901       return FALSE;
9902     }
9903   else if (ret == 1)
9904     h->indx = indx;
9905   else if (h->indx == -2)
9906     abort();
9907
9908   return TRUE;
9909 }
9910
9911 /* Return TRUE if special handling is done for relocs in SEC against
9912    symbols defined in discarded sections.  */
9913
9914 static bfd_boolean
9915 elf_section_ignore_discarded_relocs (asection *sec)
9916 {
9917   const struct elf_backend_data *bed;
9918
9919   switch (sec->sec_info_type)
9920     {
9921     case SEC_INFO_TYPE_STABS:
9922     case SEC_INFO_TYPE_EH_FRAME:
9923     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9924       return TRUE;
9925     default:
9926       break;
9927     }
9928
9929   bed = get_elf_backend_data (sec->owner);
9930   if (bed->elf_backend_ignore_discarded_relocs != NULL
9931       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9932     return TRUE;
9933
9934   return FALSE;
9935 }
9936
9937 /* Return a mask saying how ld should treat relocations in SEC against
9938    symbols defined in discarded sections.  If this function returns
9939    COMPLAIN set, ld will issue a warning message.  If this function
9940    returns PRETEND set, and the discarded section was link-once and the
9941    same size as the kept link-once section, ld will pretend that the
9942    symbol was actually defined in the kept section.  Otherwise ld will
9943    zero the reloc (at least that is the intent, but some cooperation by
9944    the target dependent code is needed, particularly for REL targets).  */
9945
9946 unsigned int
9947 _bfd_elf_default_action_discarded (asection *sec)
9948 {
9949   if (sec->flags & SEC_DEBUGGING)
9950     return PRETEND;
9951
9952   if (strcmp (".eh_frame", sec->name) == 0)
9953     return 0;
9954
9955   if (strcmp (".gcc_except_table", sec->name) == 0)
9956     return 0;
9957
9958   return COMPLAIN | PRETEND;
9959 }
9960
9961 /* Find a match between a section and a member of a section group.  */
9962
9963 static asection *
9964 match_group_member (asection *sec, asection *group,
9965                     struct bfd_link_info *info)
9966 {
9967   asection *first = elf_next_in_group (group);
9968   asection *s = first;
9969
9970   while (s != NULL)
9971     {
9972       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9973         return s;
9974
9975       s = elf_next_in_group (s);
9976       if (s == first)
9977         break;
9978     }
9979
9980   return NULL;
9981 }
9982
9983 /* Check if the kept section of a discarded section SEC can be used
9984    to replace it.  Return the replacement if it is OK.  Otherwise return
9985    NULL.  */
9986
9987 asection *
9988 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9989 {
9990   asection *kept;
9991
9992   kept = sec->kept_section;
9993   if (kept != NULL)
9994     {
9995       if ((kept->flags & SEC_GROUP) != 0)
9996         kept = match_group_member (sec, kept, info);
9997       if (kept != NULL
9998           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9999               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10000         kept = NULL;
10001       sec->kept_section = kept;
10002     }
10003   return kept;
10004 }
10005
10006 /* Link an input file into the linker output file.  This function
10007    handles all the sections and relocations of the input file at once.
10008    This is so that we only have to read the local symbols once, and
10009    don't have to keep them in memory.  */
10010
10011 static bfd_boolean
10012 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10013 {
10014   int (*relocate_section)
10015     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10016      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10017   bfd *output_bfd;
10018   Elf_Internal_Shdr *symtab_hdr;
10019   size_t locsymcount;
10020   size_t extsymoff;
10021   Elf_Internal_Sym *isymbuf;
10022   Elf_Internal_Sym *isym;
10023   Elf_Internal_Sym *isymend;
10024   long *pindex;
10025   asection **ppsection;
10026   asection *o;
10027   const struct elf_backend_data *bed;
10028   struct elf_link_hash_entry **sym_hashes;
10029   bfd_size_type address_size;
10030   bfd_vma r_type_mask;
10031   int r_sym_shift;
10032   bfd_boolean have_file_sym = FALSE;
10033
10034   output_bfd = flinfo->output_bfd;
10035   bed = get_elf_backend_data (output_bfd);
10036   relocate_section = bed->elf_backend_relocate_section;
10037
10038   /* If this is a dynamic object, we don't want to do anything here:
10039      we don't want the local symbols, and we don't want the section
10040      contents.  */
10041   if ((input_bfd->flags & DYNAMIC) != 0)
10042     return TRUE;
10043
10044   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10045   if (elf_bad_symtab (input_bfd))
10046     {
10047       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10048       extsymoff = 0;
10049     }
10050   else
10051     {
10052       locsymcount = symtab_hdr->sh_info;
10053       extsymoff = symtab_hdr->sh_info;
10054     }
10055
10056   /* Read the local symbols.  */
10057   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10058   if (isymbuf == NULL && locsymcount != 0)
10059     {
10060       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10061                                       flinfo->internal_syms,
10062                                       flinfo->external_syms,
10063                                       flinfo->locsym_shndx);
10064       if (isymbuf == NULL)
10065         return FALSE;
10066     }
10067
10068   /* Find local symbol sections and adjust values of symbols in
10069      SEC_MERGE sections.  Write out those local symbols we know are
10070      going into the output file.  */
10071   isymend = isymbuf + locsymcount;
10072   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10073        isym < isymend;
10074        isym++, pindex++, ppsection++)
10075     {
10076       asection *isec;
10077       const char *name;
10078       Elf_Internal_Sym osym;
10079       long indx;
10080       int ret;
10081
10082       *pindex = -1;
10083
10084       if (elf_bad_symtab (input_bfd))
10085         {
10086           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10087             {
10088               *ppsection = NULL;
10089               continue;
10090             }
10091         }
10092
10093       if (isym->st_shndx == SHN_UNDEF)
10094         isec = bfd_und_section_ptr;
10095       else if (isym->st_shndx == SHN_ABS)
10096         isec = bfd_abs_section_ptr;
10097       else if (isym->st_shndx == SHN_COMMON)
10098         isec = bfd_com_section_ptr;
10099       else
10100         {
10101           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10102           if (isec == NULL)
10103             {
10104               /* Don't attempt to output symbols with st_shnx in the
10105                  reserved range other than SHN_ABS and SHN_COMMON.  */
10106               *ppsection = NULL;
10107               continue;
10108             }
10109           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10110                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10111             isym->st_value =
10112               _bfd_merged_section_offset (output_bfd, &isec,
10113                                           elf_section_data (isec)->sec_info,
10114                                           isym->st_value);
10115         }
10116
10117       *ppsection = isec;
10118
10119       /* Don't output the first, undefined, symbol.  In fact, don't
10120          output any undefined local symbol.  */
10121       if (isec == bfd_und_section_ptr)
10122         continue;
10123
10124       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10125         {
10126           /* We never output section symbols.  Instead, we use the
10127              section symbol of the corresponding section in the output
10128              file.  */
10129           continue;
10130         }
10131
10132       /* If we are stripping all symbols, we don't want to output this
10133          one.  */
10134       if (flinfo->info->strip == strip_all)
10135         continue;
10136
10137       /* If we are discarding all local symbols, we don't want to
10138          output this one.  If we are generating a relocatable output
10139          file, then some of the local symbols may be required by
10140          relocs; we output them below as we discover that they are
10141          needed.  */
10142       if (flinfo->info->discard == discard_all)
10143         continue;
10144
10145       /* If this symbol is defined in a section which we are
10146          discarding, we don't need to keep it.  */
10147       if (isym->st_shndx != SHN_UNDEF
10148           && isym->st_shndx < SHN_LORESERVE
10149           && bfd_section_removed_from_list (output_bfd,
10150                                             isec->output_section))
10151         continue;
10152
10153       /* Get the name of the symbol.  */
10154       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10155                                               isym->st_name);
10156       if (name == NULL)
10157         return FALSE;
10158
10159       /* See if we are discarding symbols with this name.  */
10160       if ((flinfo->info->strip == strip_some
10161            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10162                == NULL))
10163           || (((flinfo->info->discard == discard_sec_merge
10164                 && (isec->flags & SEC_MERGE)
10165                 && !bfd_link_relocatable (flinfo->info))
10166                || flinfo->info->discard == discard_l)
10167               && bfd_is_local_label_name (input_bfd, name)))
10168         continue;
10169
10170       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10171         {
10172           if (input_bfd->lto_output)
10173             /* -flto puts a temp file name here.  This means builds
10174                are not reproducible.  Discard the symbol.  */
10175             continue;
10176           have_file_sym = TRUE;
10177           flinfo->filesym_count += 1;
10178         }
10179       if (!have_file_sym)
10180         {
10181           /* In the absence of debug info, bfd_find_nearest_line uses
10182              FILE symbols to determine the source file for local
10183              function symbols.  Provide a FILE symbol here if input
10184              files lack such, so that their symbols won't be
10185              associated with a previous input file.  It's not the
10186              source file, but the best we can do.  */
10187           have_file_sym = TRUE;
10188           flinfo->filesym_count += 1;
10189           memset (&osym, 0, sizeof (osym));
10190           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10191           osym.st_shndx = SHN_ABS;
10192           if (!elf_link_output_symstrtab (flinfo,
10193                                           (input_bfd->lto_output ? NULL
10194                                            : input_bfd->filename),
10195                                           &osym, bfd_abs_section_ptr,
10196                                           NULL))
10197             return FALSE;
10198         }
10199
10200       osym = *isym;
10201
10202       /* Adjust the section index for the output file.  */
10203       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10204                                                          isec->output_section);
10205       if (osym.st_shndx == SHN_BAD)
10206         return FALSE;
10207
10208       /* ELF symbols in relocatable files are section relative, but
10209          in executable files they are virtual addresses.  Note that
10210          this code assumes that all ELF sections have an associated
10211          BFD section with a reasonable value for output_offset; below
10212          we assume that they also have a reasonable value for
10213          output_section.  Any special sections must be set up to meet
10214          these requirements.  */
10215       osym.st_value += isec->output_offset;
10216       if (!bfd_link_relocatable (flinfo->info))
10217         {
10218           osym.st_value += isec->output_section->vma;
10219           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10220             {
10221               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10222               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10223               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10224             }
10225         }
10226
10227       indx = bfd_get_symcount (output_bfd);
10228       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10229       if (ret == 0)
10230         return FALSE;
10231       else if (ret == 1)
10232         *pindex = indx;
10233     }
10234
10235   if (bed->s->arch_size == 32)
10236     {
10237       r_type_mask = 0xff;
10238       r_sym_shift = 8;
10239       address_size = 4;
10240     }
10241   else
10242     {
10243       r_type_mask = 0xffffffff;
10244       r_sym_shift = 32;
10245       address_size = 8;
10246     }
10247
10248   /* Relocate the contents of each section.  */
10249   sym_hashes = elf_sym_hashes (input_bfd);
10250   for (o = input_bfd->sections; o != NULL; o = o->next)
10251     {
10252       bfd_byte *contents;
10253
10254       if (! o->linker_mark)
10255         {
10256           /* This section was omitted from the link.  */
10257           continue;
10258         }
10259
10260       if (bfd_link_relocatable (flinfo->info)
10261           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10262         {
10263           /* Deal with the group signature symbol.  */
10264           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10265           unsigned long symndx = sec_data->this_hdr.sh_info;
10266           asection *osec = o->output_section;
10267
10268           if (symndx >= locsymcount
10269               || (elf_bad_symtab (input_bfd)
10270                   && flinfo->sections[symndx] == NULL))
10271             {
10272               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10273               while (h->root.type == bfd_link_hash_indirect
10274                      || h->root.type == bfd_link_hash_warning)
10275                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10276               /* Arrange for symbol to be output.  */
10277               h->indx = -2;
10278               elf_section_data (osec)->this_hdr.sh_info = -2;
10279             }
10280           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10281             {
10282               /* We'll use the output section target_index.  */
10283               asection *sec = flinfo->sections[symndx]->output_section;
10284               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10285             }
10286           else
10287             {
10288               if (flinfo->indices[symndx] == -1)
10289                 {
10290                   /* Otherwise output the local symbol now.  */
10291                   Elf_Internal_Sym sym = isymbuf[symndx];
10292                   asection *sec = flinfo->sections[symndx]->output_section;
10293                   const char *name;
10294                   long indx;
10295                   int ret;
10296
10297                   name = bfd_elf_string_from_elf_section (input_bfd,
10298                                                           symtab_hdr->sh_link,
10299                                                           sym.st_name);
10300                   if (name == NULL)
10301                     return FALSE;
10302
10303                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10304                                                                     sec);
10305                   if (sym.st_shndx == SHN_BAD)
10306                     return FALSE;
10307
10308                   sym.st_value += o->output_offset;
10309
10310                   indx = bfd_get_symcount (output_bfd);
10311                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10312                                                    NULL);
10313                   if (ret == 0)
10314                     return FALSE;
10315                   else if (ret == 1)
10316                     flinfo->indices[symndx] = indx;
10317                   else
10318                     abort ();
10319                 }
10320               elf_section_data (osec)->this_hdr.sh_info
10321                 = flinfo->indices[symndx];
10322             }
10323         }
10324
10325       if ((o->flags & SEC_HAS_CONTENTS) == 0
10326           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10327         continue;
10328
10329       if ((o->flags & SEC_LINKER_CREATED) != 0)
10330         {
10331           /* Section was created by _bfd_elf_link_create_dynamic_sections
10332              or somesuch.  */
10333           continue;
10334         }
10335
10336       /* Get the contents of the section.  They have been cached by a
10337          relaxation routine.  Note that o is a section in an input
10338          file, so the contents field will not have been set by any of
10339          the routines which work on output files.  */
10340       if (elf_section_data (o)->this_hdr.contents != NULL)
10341         {
10342           contents = elf_section_data (o)->this_hdr.contents;
10343           if (bed->caches_rawsize
10344               && o->rawsize != 0
10345               && o->rawsize < o->size)
10346             {
10347               memcpy (flinfo->contents, contents, o->rawsize);
10348               contents = flinfo->contents;
10349             }
10350         }
10351       else
10352         {
10353           contents = flinfo->contents;
10354           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10355             return FALSE;
10356         }
10357
10358       if ((o->flags & SEC_RELOC) != 0)
10359         {
10360           Elf_Internal_Rela *internal_relocs;
10361           Elf_Internal_Rela *rel, *relend;
10362           int action_discarded;
10363           int ret;
10364
10365           /* Get the swapped relocs.  */
10366           internal_relocs
10367             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10368                                          flinfo->internal_relocs, FALSE);
10369           if (internal_relocs == NULL
10370               && o->reloc_count > 0)
10371             return FALSE;
10372
10373           /* We need to reverse-copy input .ctors/.dtors sections if
10374              they are placed in .init_array/.finit_array for output.  */
10375           if (o->size > address_size
10376               && ((strncmp (o->name, ".ctors", 6) == 0
10377                    && strcmp (o->output_section->name,
10378                               ".init_array") == 0)
10379                   || (strncmp (o->name, ".dtors", 6) == 0
10380                       && strcmp (o->output_section->name,
10381                                  ".fini_array") == 0))
10382               && (o->name[6] == 0 || o->name[6] == '.'))
10383             {
10384               if (o->size != o->reloc_count * address_size)
10385                 {
10386                   _bfd_error_handler
10387                     /* xgettext:c-format */
10388                     (_("error: %B: size of section %A is not "
10389                        "multiple of address size"),
10390                      input_bfd, o);
10391                   bfd_set_error (bfd_error_on_input);
10392                   return FALSE;
10393                 }
10394               o->flags |= SEC_ELF_REVERSE_COPY;
10395             }
10396
10397           action_discarded = -1;
10398           if (!elf_section_ignore_discarded_relocs (o))
10399             action_discarded = (*bed->action_discarded) (o);
10400
10401           /* Run through the relocs evaluating complex reloc symbols and
10402              looking for relocs against symbols from discarded sections
10403              or section symbols from removed link-once sections.
10404              Complain about relocs against discarded sections.  Zero
10405              relocs against removed link-once sections.  */
10406
10407           rel = internal_relocs;
10408           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10409           for ( ; rel < relend; rel++)
10410             {
10411               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10412               unsigned int s_type;
10413               asection **ps, *sec;
10414               struct elf_link_hash_entry *h = NULL;
10415               const char *sym_name;
10416
10417               if (r_symndx == STN_UNDEF)
10418                 continue;
10419
10420               if (r_symndx >= locsymcount
10421                   || (elf_bad_symtab (input_bfd)
10422                       && flinfo->sections[r_symndx] == NULL))
10423                 {
10424                   h = sym_hashes[r_symndx - extsymoff];
10425
10426                   /* Badly formatted input files can contain relocs that
10427                      reference non-existant symbols.  Check here so that
10428                      we do not seg fault.  */
10429                   if (h == NULL)
10430                     {
10431                       char buffer [32];
10432
10433                       sprintf_vma (buffer, rel->r_info);
10434                       _bfd_error_handler
10435                         /* xgettext:c-format */
10436                         (_("error: %B contains a reloc (0x%s) for section %A "
10437                            "that references a non-existent global symbol"),
10438                          input_bfd, buffer, o);
10439                       bfd_set_error (bfd_error_bad_value);
10440                       return FALSE;
10441                     }
10442
10443                   while (h->root.type == bfd_link_hash_indirect
10444                          || h->root.type == bfd_link_hash_warning)
10445                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10446
10447                   s_type = h->type;
10448
10449                   /* If a plugin symbol is referenced from a non-IR file,
10450                      mark the symbol as undefined.  Note that the
10451                      linker may attach linker created dynamic sections
10452                      to the plugin bfd.  Symbols defined in linker
10453                      created sections are not plugin symbols.  */
10454                   if (h->root.non_ir_ref
10455                       && (h->root.type == bfd_link_hash_defined
10456                           || h->root.type == bfd_link_hash_defweak)
10457                       && (h->root.u.def.section->flags
10458                           & SEC_LINKER_CREATED) == 0
10459                       && h->root.u.def.section->owner != NULL
10460                       && (h->root.u.def.section->owner->flags
10461                           & BFD_PLUGIN) != 0)
10462                     {
10463                       h->root.type = bfd_link_hash_undefined;
10464                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10465                     }
10466
10467                   ps = NULL;
10468                   if (h->root.type == bfd_link_hash_defined
10469                       || h->root.type == bfd_link_hash_defweak)
10470                     ps = &h->root.u.def.section;
10471
10472                   sym_name = h->root.root.string;
10473                 }
10474               else
10475                 {
10476                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10477
10478                   s_type = ELF_ST_TYPE (sym->st_info);
10479                   ps = &flinfo->sections[r_symndx];
10480                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10481                                                sym, *ps);
10482                 }
10483
10484               if ((s_type == STT_RELC || s_type == STT_SRELC)
10485                   && !bfd_link_relocatable (flinfo->info))
10486                 {
10487                   bfd_vma val;
10488                   bfd_vma dot = (rel->r_offset
10489                                  + o->output_offset + o->output_section->vma);
10490 #ifdef DEBUG
10491                   printf ("Encountered a complex symbol!");
10492                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10493                           input_bfd->filename, o->name,
10494                           (long) (rel - internal_relocs));
10495                   printf (" symbol: idx  %8.8lx, name %s\n",
10496                           r_symndx, sym_name);
10497                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10498                           (unsigned long) rel->r_info,
10499                           (unsigned long) rel->r_offset);
10500 #endif
10501                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10502                                     isymbuf, locsymcount, s_type == STT_SRELC))
10503                     return FALSE;
10504
10505                   /* Symbol evaluated OK.  Update to absolute value.  */
10506                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10507                                     r_symndx, val);
10508                   continue;
10509                 }
10510
10511               if (action_discarded != -1 && ps != NULL)
10512                 {
10513                   /* Complain if the definition comes from a
10514                      discarded section.  */
10515                   if ((sec = *ps) != NULL && discarded_section (sec))
10516                     {
10517                       BFD_ASSERT (r_symndx != STN_UNDEF);
10518                       if (action_discarded & COMPLAIN)
10519                         (*flinfo->info->callbacks->einfo)
10520                           /* xgettext:c-format */
10521                           (_("%X`%s' referenced in section `%A' of %B: "
10522                              "defined in discarded section `%A' of %B\n"),
10523                            sym_name, o, input_bfd, sec, sec->owner);
10524
10525                       /* Try to do the best we can to support buggy old
10526                          versions of gcc.  Pretend that the symbol is
10527                          really defined in the kept linkonce section.
10528                          FIXME: This is quite broken.  Modifying the
10529                          symbol here means we will be changing all later
10530                          uses of the symbol, not just in this section.  */
10531                       if (action_discarded & PRETEND)
10532                         {
10533                           asection *kept;
10534
10535                           kept = _bfd_elf_check_kept_section (sec,
10536                                                               flinfo->info);
10537                           if (kept != NULL)
10538                             {
10539                               *ps = kept;
10540                               continue;
10541                             }
10542                         }
10543                     }
10544                 }
10545             }
10546
10547           /* Relocate the section by invoking a back end routine.
10548
10549              The back end routine is responsible for adjusting the
10550              section contents as necessary, and (if using Rela relocs
10551              and generating a relocatable output file) adjusting the
10552              reloc addend as necessary.
10553
10554              The back end routine does not have to worry about setting
10555              the reloc address or the reloc symbol index.
10556
10557              The back end routine is given a pointer to the swapped in
10558              internal symbols, and can access the hash table entries
10559              for the external symbols via elf_sym_hashes (input_bfd).
10560
10561              When generating relocatable output, the back end routine
10562              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10563              output symbol is going to be a section symbol
10564              corresponding to the output section, which will require
10565              the addend to be adjusted.  */
10566
10567           ret = (*relocate_section) (output_bfd, flinfo->info,
10568                                      input_bfd, o, contents,
10569                                      internal_relocs,
10570                                      isymbuf,
10571                                      flinfo->sections);
10572           if (!ret)
10573             return FALSE;
10574
10575           if (ret == 2
10576               || bfd_link_relocatable (flinfo->info)
10577               || flinfo->info->emitrelocations)
10578             {
10579               Elf_Internal_Rela *irela;
10580               Elf_Internal_Rela *irelaend, *irelamid;
10581               bfd_vma last_offset;
10582               struct elf_link_hash_entry **rel_hash;
10583               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10584               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10585               unsigned int next_erel;
10586               bfd_boolean rela_normal;
10587               struct bfd_elf_section_data *esdi, *esdo;
10588
10589               esdi = elf_section_data (o);
10590               esdo = elf_section_data (o->output_section);
10591               rela_normal = FALSE;
10592
10593               /* Adjust the reloc addresses and symbol indices.  */
10594
10595               irela = internal_relocs;
10596               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10597               rel_hash = esdo->rel.hashes + esdo->rel.count;
10598               /* We start processing the REL relocs, if any.  When we reach
10599                  IRELAMID in the loop, we switch to the RELA relocs.  */
10600               irelamid = irela;
10601               if (esdi->rel.hdr != NULL)
10602                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10603                              * bed->s->int_rels_per_ext_rel);
10604               rel_hash_list = rel_hash;
10605               rela_hash_list = NULL;
10606               last_offset = o->output_offset;
10607               if (!bfd_link_relocatable (flinfo->info))
10608                 last_offset += o->output_section->vma;
10609               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10610                 {
10611                   unsigned long r_symndx;
10612                   asection *sec;
10613                   Elf_Internal_Sym sym;
10614
10615                   if (next_erel == bed->s->int_rels_per_ext_rel)
10616                     {
10617                       rel_hash++;
10618                       next_erel = 0;
10619                     }
10620
10621                   if (irela == irelamid)
10622                     {
10623                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10624                       rela_hash_list = rel_hash;
10625                       rela_normal = bed->rela_normal;
10626                     }
10627
10628                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10629                                                              flinfo->info, o,
10630                                                              irela->r_offset);
10631                   if (irela->r_offset >= (bfd_vma) -2)
10632                     {
10633                       /* This is a reloc for a deleted entry or somesuch.
10634                          Turn it into an R_*_NONE reloc, at the same
10635                          offset as the last reloc.  elf_eh_frame.c and
10636                          bfd_elf_discard_info rely on reloc offsets
10637                          being ordered.  */
10638                       irela->r_offset = last_offset;
10639                       irela->r_info = 0;
10640                       irela->r_addend = 0;
10641                       continue;
10642                     }
10643
10644                   irela->r_offset += o->output_offset;
10645
10646                   /* Relocs in an executable have to be virtual addresses.  */
10647                   if (!bfd_link_relocatable (flinfo->info))
10648                     irela->r_offset += o->output_section->vma;
10649
10650                   last_offset = irela->r_offset;
10651
10652                   r_symndx = irela->r_info >> r_sym_shift;
10653                   if (r_symndx == STN_UNDEF)
10654                     continue;
10655
10656                   if (r_symndx >= locsymcount
10657                       || (elf_bad_symtab (input_bfd)
10658                           && flinfo->sections[r_symndx] == NULL))
10659                     {
10660                       struct elf_link_hash_entry *rh;
10661                       unsigned long indx;
10662
10663                       /* This is a reloc against a global symbol.  We
10664                          have not yet output all the local symbols, so
10665                          we do not know the symbol index of any global
10666                          symbol.  We set the rel_hash entry for this
10667                          reloc to point to the global hash table entry
10668                          for this symbol.  The symbol index is then
10669                          set at the end of bfd_elf_final_link.  */
10670                       indx = r_symndx - extsymoff;
10671                       rh = elf_sym_hashes (input_bfd)[indx];
10672                       while (rh->root.type == bfd_link_hash_indirect
10673                              || rh->root.type == bfd_link_hash_warning)
10674                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10675
10676                       /* Setting the index to -2 tells
10677                          elf_link_output_extsym that this symbol is
10678                          used by a reloc.  */
10679                       BFD_ASSERT (rh->indx < 0);
10680                       rh->indx = -2;
10681
10682                       *rel_hash = rh;
10683
10684                       continue;
10685                     }
10686
10687                   /* This is a reloc against a local symbol.  */
10688
10689                   *rel_hash = NULL;
10690                   sym = isymbuf[r_symndx];
10691                   sec = flinfo->sections[r_symndx];
10692                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10693                     {
10694                       /* I suppose the backend ought to fill in the
10695                          section of any STT_SECTION symbol against a
10696                          processor specific section.  */
10697                       r_symndx = STN_UNDEF;
10698                       if (bfd_is_abs_section (sec))
10699                         ;
10700                       else if (sec == NULL || sec->owner == NULL)
10701                         {
10702                           bfd_set_error (bfd_error_bad_value);
10703                           return FALSE;
10704                         }
10705                       else
10706                         {
10707                           asection *osec = sec->output_section;
10708
10709                           /* If we have discarded a section, the output
10710                              section will be the absolute section.  In
10711                              case of discarded SEC_MERGE sections, use
10712                              the kept section.  relocate_section should
10713                              have already handled discarded linkonce
10714                              sections.  */
10715                           if (bfd_is_abs_section (osec)
10716                               && sec->kept_section != NULL
10717                               && sec->kept_section->output_section != NULL)
10718                             {
10719                               osec = sec->kept_section->output_section;
10720                               irela->r_addend -= osec->vma;
10721                             }
10722
10723                           if (!bfd_is_abs_section (osec))
10724                             {
10725                               r_symndx = osec->target_index;
10726                               if (r_symndx == STN_UNDEF)
10727                                 {
10728                                   irela->r_addend += osec->vma;
10729                                   osec = _bfd_nearby_section (output_bfd, osec,
10730                                                               osec->vma);
10731                                   irela->r_addend -= osec->vma;
10732                                   r_symndx = osec->target_index;
10733                                 }
10734                             }
10735                         }
10736
10737                       /* Adjust the addend according to where the
10738                          section winds up in the output section.  */
10739                       if (rela_normal)
10740                         irela->r_addend += sec->output_offset;
10741                     }
10742                   else
10743                     {
10744                       if (flinfo->indices[r_symndx] == -1)
10745                         {
10746                           unsigned long shlink;
10747                           const char *name;
10748                           asection *osec;
10749                           long indx;
10750
10751                           if (flinfo->info->strip == strip_all)
10752                             {
10753                               /* You can't do ld -r -s.  */
10754                               bfd_set_error (bfd_error_invalid_operation);
10755                               return FALSE;
10756                             }
10757
10758                           /* This symbol was skipped earlier, but
10759                              since it is needed by a reloc, we
10760                              must output it now.  */
10761                           shlink = symtab_hdr->sh_link;
10762                           name = (bfd_elf_string_from_elf_section
10763                                   (input_bfd, shlink, sym.st_name));
10764                           if (name == NULL)
10765                             return FALSE;
10766
10767                           osec = sec->output_section;
10768                           sym.st_shndx =
10769                             _bfd_elf_section_from_bfd_section (output_bfd,
10770                                                                osec);
10771                           if (sym.st_shndx == SHN_BAD)
10772                             return FALSE;
10773
10774                           sym.st_value += sec->output_offset;
10775                           if (!bfd_link_relocatable (flinfo->info))
10776                             {
10777                               sym.st_value += osec->vma;
10778                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10779                                 {
10780                                   /* STT_TLS symbols are relative to PT_TLS
10781                                      segment base.  */
10782                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10783                                               ->tls_sec != NULL);
10784                                   sym.st_value -= (elf_hash_table (flinfo->info)
10785                                                    ->tls_sec->vma);
10786                                 }
10787                             }
10788
10789                           indx = bfd_get_symcount (output_bfd);
10790                           ret = elf_link_output_symstrtab (flinfo, name,
10791                                                            &sym, sec,
10792                                                            NULL);
10793                           if (ret == 0)
10794                             return FALSE;
10795                           else if (ret == 1)
10796                             flinfo->indices[r_symndx] = indx;
10797                           else
10798                             abort ();
10799                         }
10800
10801                       r_symndx = flinfo->indices[r_symndx];
10802                     }
10803
10804                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10805                                    | (irela->r_info & r_type_mask));
10806                 }
10807
10808               /* Swap out the relocs.  */
10809               input_rel_hdr = esdi->rel.hdr;
10810               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10811                 {
10812                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10813                                                      input_rel_hdr,
10814                                                      internal_relocs,
10815                                                      rel_hash_list))
10816                     return FALSE;
10817                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10818                                       * bed->s->int_rels_per_ext_rel);
10819                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10820                 }
10821
10822               input_rela_hdr = esdi->rela.hdr;
10823               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10824                 {
10825                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10826                                                      input_rela_hdr,
10827                                                      internal_relocs,
10828                                                      rela_hash_list))
10829                     return FALSE;
10830                 }
10831             }
10832         }
10833
10834       /* Write out the modified section contents.  */
10835       if (bed->elf_backend_write_section
10836           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10837                                                 contents))
10838         {
10839           /* Section written out.  */
10840         }
10841       else switch (o->sec_info_type)
10842         {
10843         case SEC_INFO_TYPE_STABS:
10844           if (! (_bfd_write_section_stabs
10845                  (output_bfd,
10846                   &elf_hash_table (flinfo->info)->stab_info,
10847                   o, &elf_section_data (o)->sec_info, contents)))
10848             return FALSE;
10849           break;
10850         case SEC_INFO_TYPE_MERGE:
10851           if (! _bfd_write_merged_section (output_bfd, o,
10852                                            elf_section_data (o)->sec_info))
10853             return FALSE;
10854           break;
10855         case SEC_INFO_TYPE_EH_FRAME:
10856           {
10857             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10858                                                    o, contents))
10859               return FALSE;
10860           }
10861           break;
10862         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10863           {
10864             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10865                                                          flinfo->info,
10866                                                          o, contents))
10867               return FALSE;
10868           }
10869           break;
10870         default:
10871           {
10872             if (! (o->flags & SEC_EXCLUDE))
10873               {
10874                 file_ptr offset = (file_ptr) o->output_offset;
10875                 bfd_size_type todo = o->size;
10876
10877                 offset *= bfd_octets_per_byte (output_bfd);
10878
10879                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10880                   {
10881                     /* Reverse-copy input section to output.  */
10882                     do
10883                       {
10884                         todo -= address_size;
10885                         if (! bfd_set_section_contents (output_bfd,
10886                                                         o->output_section,
10887                                                         contents + todo,
10888                                                         offset,
10889                                                         address_size))
10890                           return FALSE;
10891                         if (todo == 0)
10892                           break;
10893                         offset += address_size;
10894                       }
10895                     while (1);
10896                   }
10897                 else if (! bfd_set_section_contents (output_bfd,
10898                                                      o->output_section,
10899                                                      contents,
10900                                                      offset, todo))
10901                   return FALSE;
10902               }
10903           }
10904           break;
10905         }
10906     }
10907
10908   return TRUE;
10909 }
10910
10911 /* Generate a reloc when linking an ELF file.  This is a reloc
10912    requested by the linker, and does not come from any input file.  This
10913    is used to build constructor and destructor tables when linking
10914    with -Ur.  */
10915
10916 static bfd_boolean
10917 elf_reloc_link_order (bfd *output_bfd,
10918                       struct bfd_link_info *info,
10919                       asection *output_section,
10920                       struct bfd_link_order *link_order)
10921 {
10922   reloc_howto_type *howto;
10923   long indx;
10924   bfd_vma offset;
10925   bfd_vma addend;
10926   struct bfd_elf_section_reloc_data *reldata;
10927   struct elf_link_hash_entry **rel_hash_ptr;
10928   Elf_Internal_Shdr *rel_hdr;
10929   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10930   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10931   bfd_byte *erel;
10932   unsigned int i;
10933   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10934
10935   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10936   if (howto == NULL)
10937     {
10938       bfd_set_error (bfd_error_bad_value);
10939       return FALSE;
10940     }
10941
10942   addend = link_order->u.reloc.p->addend;
10943
10944   if (esdo->rel.hdr)
10945     reldata = &esdo->rel;
10946   else if (esdo->rela.hdr)
10947     reldata = &esdo->rela;
10948   else
10949     {
10950       reldata = NULL;
10951       BFD_ASSERT (0);
10952     }
10953
10954   /* Figure out the symbol index.  */
10955   rel_hash_ptr = reldata->hashes + reldata->count;
10956   if (link_order->type == bfd_section_reloc_link_order)
10957     {
10958       indx = link_order->u.reloc.p->u.section->target_index;
10959       BFD_ASSERT (indx != 0);
10960       *rel_hash_ptr = NULL;
10961     }
10962   else
10963     {
10964       struct elf_link_hash_entry *h;
10965
10966       /* Treat a reloc against a defined symbol as though it were
10967          actually against the section.  */
10968       h = ((struct elf_link_hash_entry *)
10969            bfd_wrapped_link_hash_lookup (output_bfd, info,
10970                                          link_order->u.reloc.p->u.name,
10971                                          FALSE, FALSE, TRUE));
10972       if (h != NULL
10973           && (h->root.type == bfd_link_hash_defined
10974               || h->root.type == bfd_link_hash_defweak))
10975         {
10976           asection *section;
10977
10978           section = h->root.u.def.section;
10979           indx = section->output_section->target_index;
10980           *rel_hash_ptr = NULL;
10981           /* It seems that we ought to add the symbol value to the
10982              addend here, but in practice it has already been added
10983              because it was passed to constructor_callback.  */
10984           addend += section->output_section->vma + section->output_offset;
10985         }
10986       else if (h != NULL)
10987         {
10988           /* Setting the index to -2 tells elf_link_output_extsym that
10989              this symbol is used by a reloc.  */
10990           h->indx = -2;
10991           *rel_hash_ptr = h;
10992           indx = 0;
10993         }
10994       else
10995         {
10996           (*info->callbacks->unattached_reloc)
10997             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
10998           indx = 0;
10999         }
11000     }
11001
11002   /* If this is an inplace reloc, we must write the addend into the
11003      object file.  */
11004   if (howto->partial_inplace && addend != 0)
11005     {
11006       bfd_size_type size;
11007       bfd_reloc_status_type rstat;
11008       bfd_byte *buf;
11009       bfd_boolean ok;
11010       const char *sym_name;
11011
11012       size = (bfd_size_type) bfd_get_reloc_size (howto);
11013       buf = (bfd_byte *) bfd_zmalloc (size);
11014       if (buf == NULL && size != 0)
11015         return FALSE;
11016       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11017       switch (rstat)
11018         {
11019         case bfd_reloc_ok:
11020           break;
11021
11022         default:
11023         case bfd_reloc_outofrange:
11024           abort ();
11025
11026         case bfd_reloc_overflow:
11027           if (link_order->type == bfd_section_reloc_link_order)
11028             sym_name = bfd_section_name (output_bfd,
11029                                          link_order->u.reloc.p->u.section);
11030           else
11031             sym_name = link_order->u.reloc.p->u.name;
11032           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11033                                               howto->name, addend, NULL, NULL,
11034                                               (bfd_vma) 0);
11035           break;
11036         }
11037
11038       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11039                                      link_order->offset
11040                                      * bfd_octets_per_byte (output_bfd),
11041                                      size);
11042       free (buf);
11043       if (! ok)
11044         return FALSE;
11045     }
11046
11047   /* The address of a reloc is relative to the section in a
11048      relocatable file, and is a virtual address in an executable
11049      file.  */
11050   offset = link_order->offset;
11051   if (! bfd_link_relocatable (info))
11052     offset += output_section->vma;
11053
11054   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11055     {
11056       irel[i].r_offset = offset;
11057       irel[i].r_info = 0;
11058       irel[i].r_addend = 0;
11059     }
11060   if (bed->s->arch_size == 32)
11061     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11062   else
11063     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11064
11065   rel_hdr = reldata->hdr;
11066   erel = rel_hdr->contents;
11067   if (rel_hdr->sh_type == SHT_REL)
11068     {
11069       erel += reldata->count * bed->s->sizeof_rel;
11070       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11071     }
11072   else
11073     {
11074       irel[0].r_addend = addend;
11075       erel += reldata->count * bed->s->sizeof_rela;
11076       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11077     }
11078
11079   ++reldata->count;
11080
11081   return TRUE;
11082 }
11083
11084
11085 /* Get the output vma of the section pointed to by the sh_link field.  */
11086
11087 static bfd_vma
11088 elf_get_linked_section_vma (struct bfd_link_order *p)
11089 {
11090   Elf_Internal_Shdr **elf_shdrp;
11091   asection *s;
11092   int elfsec;
11093
11094   s = p->u.indirect.section;
11095   elf_shdrp = elf_elfsections (s->owner);
11096   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11097   elfsec = elf_shdrp[elfsec]->sh_link;
11098   /* PR 290:
11099      The Intel C compiler generates SHT_IA_64_UNWIND with
11100      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11101      sh_info fields.  Hence we could get the situation
11102      where elfsec is 0.  */
11103   if (elfsec == 0)
11104     {
11105       const struct elf_backend_data *bed
11106         = get_elf_backend_data (s->owner);
11107       if (bed->link_order_error_handler)
11108         bed->link_order_error_handler
11109           /* xgettext:c-format */
11110           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11111       return 0;
11112     }
11113   else
11114     {
11115       s = elf_shdrp[elfsec]->bfd_section;
11116       return s->output_section->vma + s->output_offset;
11117     }
11118 }
11119
11120
11121 /* Compare two sections based on the locations of the sections they are
11122    linked to.  Used by elf_fixup_link_order.  */
11123
11124 static int
11125 compare_link_order (const void * a, const void * b)
11126 {
11127   bfd_vma apos;
11128   bfd_vma bpos;
11129
11130   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11131   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11132   if (apos < bpos)
11133     return -1;
11134   return apos > bpos;
11135 }
11136
11137
11138 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11139    order as their linked sections.  Returns false if this could not be done
11140    because an output section includes both ordered and unordered
11141    sections.  Ideally we'd do this in the linker proper.  */
11142
11143 static bfd_boolean
11144 elf_fixup_link_order (bfd *abfd, asection *o)
11145 {
11146   int seen_linkorder;
11147   int seen_other;
11148   int n;
11149   struct bfd_link_order *p;
11150   bfd *sub;
11151   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11152   unsigned elfsec;
11153   struct bfd_link_order **sections;
11154   asection *s, *other_sec, *linkorder_sec;
11155   bfd_vma offset;
11156
11157   other_sec = NULL;
11158   linkorder_sec = NULL;
11159   seen_other = 0;
11160   seen_linkorder = 0;
11161   for (p = o->map_head.link_order; p != NULL; p = p->next)
11162     {
11163       if (p->type == bfd_indirect_link_order)
11164         {
11165           s = p->u.indirect.section;
11166           sub = s->owner;
11167           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11168               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11169               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11170               && elfsec < elf_numsections (sub)
11171               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11172               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11173             {
11174               seen_linkorder++;
11175               linkorder_sec = s;
11176             }
11177           else
11178             {
11179               seen_other++;
11180               other_sec = s;
11181             }
11182         }
11183       else
11184         seen_other++;
11185
11186       if (seen_other && seen_linkorder)
11187         {
11188           if (other_sec && linkorder_sec)
11189             _bfd_error_handler
11190               /* xgettext:c-format */
11191               (_("%A has both ordered [`%A' in %B] "
11192                  "and unordered [`%A' in %B] sections"),
11193                o, linkorder_sec, linkorder_sec->owner,
11194                other_sec, other_sec->owner);
11195           else
11196             _bfd_error_handler
11197               (_("%A has both ordered and unordered sections"), o);
11198           bfd_set_error (bfd_error_bad_value);
11199           return FALSE;
11200         }
11201     }
11202
11203   if (!seen_linkorder)
11204     return TRUE;
11205
11206   sections = (struct bfd_link_order **)
11207     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11208   if (sections == NULL)
11209     return FALSE;
11210   seen_linkorder = 0;
11211
11212   for (p = o->map_head.link_order; p != NULL; p = p->next)
11213     {
11214       sections[seen_linkorder++] = p;
11215     }
11216   /* Sort the input sections in the order of their linked section.  */
11217   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11218          compare_link_order);
11219
11220   /* Change the offsets of the sections.  */
11221   offset = 0;
11222   for (n = 0; n < seen_linkorder; n++)
11223     {
11224       s = sections[n]->u.indirect.section;
11225       offset &= ~(bfd_vma) 0 << s->alignment_power;
11226       s->output_offset = offset / bfd_octets_per_byte (abfd);
11227       sections[n]->offset = offset;
11228       offset += sections[n]->size;
11229     }
11230
11231   free (sections);
11232   return TRUE;
11233 }
11234
11235 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11236    Returns TRUE upon success, FALSE otherwise.  */
11237
11238 static bfd_boolean
11239 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11240 {
11241   bfd_boolean ret = FALSE;
11242   bfd *implib_bfd;
11243   const struct elf_backend_data *bed;
11244   flagword flags;
11245   enum bfd_architecture arch;
11246   unsigned int mach;
11247   asymbol **sympp = NULL;
11248   long symsize;
11249   long symcount;
11250   long src_count;
11251   elf_symbol_type *osymbuf;
11252
11253   implib_bfd = info->out_implib_bfd;
11254   bed = get_elf_backend_data (abfd);
11255
11256   if (!bfd_set_format (implib_bfd, bfd_object))
11257     return FALSE;
11258
11259   flags = bfd_get_file_flags (abfd);
11260   flags &= ~HAS_RELOC;
11261   if (!bfd_set_start_address (implib_bfd, 0)
11262       || !bfd_set_file_flags (implib_bfd, flags))
11263     return FALSE;
11264
11265   /* Copy architecture of output file to import library file.  */
11266   arch = bfd_get_arch (abfd);
11267   mach = bfd_get_mach (abfd);
11268   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11269       && (abfd->target_defaulted
11270           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11271     return FALSE;
11272
11273   /* Get symbol table size.  */
11274   symsize = bfd_get_symtab_upper_bound (abfd);
11275   if (symsize < 0)
11276     return FALSE;
11277
11278   /* Read in the symbol table.  */
11279   sympp = (asymbol **) xmalloc (symsize);
11280   symcount = bfd_canonicalize_symtab (abfd, sympp);
11281   if (symcount < 0)
11282     goto free_sym_buf;
11283
11284   /* Allow the BFD backend to copy any private header data it
11285      understands from the output BFD to the import library BFD.  */
11286   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11287     goto free_sym_buf;
11288
11289   /* Filter symbols to appear in the import library.  */
11290   if (bed->elf_backend_filter_implib_symbols)
11291     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11292                                                        symcount);
11293   else
11294     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11295   if (symcount == 0)
11296     {
11297       bfd_set_error (bfd_error_no_symbols);
11298       _bfd_error_handler (_("%B: no symbol found for import library"),
11299                           implib_bfd);
11300       goto free_sym_buf;
11301     }
11302
11303
11304   /* Make symbols absolute.  */
11305   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11306                                             sizeof (*osymbuf));
11307   for (src_count = 0; src_count < symcount; src_count++)
11308     {
11309       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11310               sizeof (*osymbuf));
11311       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11312       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11313       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11314       osymbuf[src_count].internal_elf_sym.st_value =
11315         osymbuf[src_count].symbol.value;
11316       sympp[src_count] = &osymbuf[src_count].symbol;
11317     }
11318
11319   bfd_set_symtab (implib_bfd, sympp, symcount);
11320
11321   /* Allow the BFD backend to copy any private data it understands
11322      from the output BFD to the import library BFD.  This is done last
11323      to permit the routine to look at the filtered symbol table.  */
11324   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11325     goto free_sym_buf;
11326
11327   if (!bfd_close (implib_bfd))
11328     goto free_sym_buf;
11329
11330   ret = TRUE;
11331
11332 free_sym_buf:
11333   free (sympp);
11334   return ret;
11335 }
11336
11337 static void
11338 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11339 {
11340   asection *o;
11341
11342   if (flinfo->symstrtab != NULL)
11343     _bfd_elf_strtab_free (flinfo->symstrtab);
11344   if (flinfo->contents != NULL)
11345     free (flinfo->contents);
11346   if (flinfo->external_relocs != NULL)
11347     free (flinfo->external_relocs);
11348   if (flinfo->internal_relocs != NULL)
11349     free (flinfo->internal_relocs);
11350   if (flinfo->external_syms != NULL)
11351     free (flinfo->external_syms);
11352   if (flinfo->locsym_shndx != NULL)
11353     free (flinfo->locsym_shndx);
11354   if (flinfo->internal_syms != NULL)
11355     free (flinfo->internal_syms);
11356   if (flinfo->indices != NULL)
11357     free (flinfo->indices);
11358   if (flinfo->sections != NULL)
11359     free (flinfo->sections);
11360   if (flinfo->symshndxbuf != NULL)
11361     free (flinfo->symshndxbuf);
11362   for (o = obfd->sections; o != NULL; o = o->next)
11363     {
11364       struct bfd_elf_section_data *esdo = elf_section_data (o);
11365       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11366         free (esdo->rel.hashes);
11367       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11368         free (esdo->rela.hashes);
11369     }
11370 }
11371
11372 /* Do the final step of an ELF link.  */
11373
11374 bfd_boolean
11375 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11376 {
11377   bfd_boolean dynamic;
11378   bfd_boolean emit_relocs;
11379   bfd *dynobj;
11380   struct elf_final_link_info flinfo;
11381   asection *o;
11382   struct bfd_link_order *p;
11383   bfd *sub;
11384   bfd_size_type max_contents_size;
11385   bfd_size_type max_external_reloc_size;
11386   bfd_size_type max_internal_reloc_count;
11387   bfd_size_type max_sym_count;
11388   bfd_size_type max_sym_shndx_count;
11389   Elf_Internal_Sym elfsym;
11390   unsigned int i;
11391   Elf_Internal_Shdr *symtab_hdr;
11392   Elf_Internal_Shdr *symtab_shndx_hdr;
11393   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11394   struct elf_outext_info eoinfo;
11395   bfd_boolean merged;
11396   size_t relativecount = 0;
11397   asection *reldyn = 0;
11398   bfd_size_type amt;
11399   asection *attr_section = NULL;
11400   bfd_vma attr_size = 0;
11401   const char *std_attrs_section;
11402   struct elf_link_hash_table *htab = elf_hash_table (info);
11403
11404   if (!is_elf_hash_table (htab))
11405     return FALSE;
11406
11407   if (bfd_link_pic (info))
11408     abfd->flags |= DYNAMIC;
11409
11410   dynamic = htab->dynamic_sections_created;
11411   dynobj = htab->dynobj;
11412
11413   emit_relocs = (bfd_link_relocatable (info)
11414                  || info->emitrelocations);
11415
11416   flinfo.info = info;
11417   flinfo.output_bfd = abfd;
11418   flinfo.symstrtab = _bfd_elf_strtab_init ();
11419   if (flinfo.symstrtab == NULL)
11420     return FALSE;
11421
11422   if (! dynamic)
11423     {
11424       flinfo.hash_sec = NULL;
11425       flinfo.symver_sec = NULL;
11426     }
11427   else
11428     {
11429       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11430       /* Note that dynsym_sec can be NULL (on VMS).  */
11431       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11432       /* Note that it is OK if symver_sec is NULL.  */
11433     }
11434
11435   flinfo.contents = NULL;
11436   flinfo.external_relocs = NULL;
11437   flinfo.internal_relocs = NULL;
11438   flinfo.external_syms = NULL;
11439   flinfo.locsym_shndx = NULL;
11440   flinfo.internal_syms = NULL;
11441   flinfo.indices = NULL;
11442   flinfo.sections = NULL;
11443   flinfo.symshndxbuf = NULL;
11444   flinfo.filesym_count = 0;
11445
11446   /* The object attributes have been merged.  Remove the input
11447      sections from the link, and set the contents of the output
11448      secton.  */
11449   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11450   for (o = abfd->sections; o != NULL; o = o->next)
11451     {
11452       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11453           || strcmp (o->name, ".gnu.attributes") == 0)
11454         {
11455           for (p = o->map_head.link_order; p != NULL; p = p->next)
11456             {
11457               asection *input_section;
11458
11459               if (p->type != bfd_indirect_link_order)
11460                 continue;
11461               input_section = p->u.indirect.section;
11462               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11463                  elf_link_input_bfd ignores this section.  */
11464               input_section->flags &= ~SEC_HAS_CONTENTS;
11465             }
11466
11467           attr_size = bfd_elf_obj_attr_size (abfd);
11468           if (attr_size)
11469             {
11470               bfd_set_section_size (abfd, o, attr_size);
11471               attr_section = o;
11472               /* Skip this section later on.  */
11473               o->map_head.link_order = NULL;
11474             }
11475           else
11476             o->flags |= SEC_EXCLUDE;
11477         }
11478     }
11479
11480   /* Count up the number of relocations we will output for each output
11481      section, so that we know the sizes of the reloc sections.  We
11482      also figure out some maximum sizes.  */
11483   max_contents_size = 0;
11484   max_external_reloc_size = 0;
11485   max_internal_reloc_count = 0;
11486   max_sym_count = 0;
11487   max_sym_shndx_count = 0;
11488   merged = FALSE;
11489   for (o = abfd->sections; o != NULL; o = o->next)
11490     {
11491       struct bfd_elf_section_data *esdo = elf_section_data (o);
11492       o->reloc_count = 0;
11493
11494       for (p = o->map_head.link_order; p != NULL; p = p->next)
11495         {
11496           unsigned int reloc_count = 0;
11497           unsigned int additional_reloc_count = 0;
11498           struct bfd_elf_section_data *esdi = NULL;
11499
11500           if (p->type == bfd_section_reloc_link_order
11501               || p->type == bfd_symbol_reloc_link_order)
11502             reloc_count = 1;
11503           else if (p->type == bfd_indirect_link_order)
11504             {
11505               asection *sec;
11506
11507               sec = p->u.indirect.section;
11508
11509               /* Mark all sections which are to be included in the
11510                  link.  This will normally be every section.  We need
11511                  to do this so that we can identify any sections which
11512                  the linker has decided to not include.  */
11513               sec->linker_mark = TRUE;
11514
11515               if (sec->flags & SEC_MERGE)
11516                 merged = TRUE;
11517
11518               if (sec->rawsize > max_contents_size)
11519                 max_contents_size = sec->rawsize;
11520               if (sec->size > max_contents_size)
11521                 max_contents_size = sec->size;
11522
11523               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11524                   && (sec->owner->flags & DYNAMIC) == 0)
11525                 {
11526                   size_t sym_count;
11527
11528                   /* We are interested in just local symbols, not all
11529                      symbols.  */
11530                   if (elf_bad_symtab (sec->owner))
11531                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11532                                  / bed->s->sizeof_sym);
11533                   else
11534                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11535
11536                   if (sym_count > max_sym_count)
11537                     max_sym_count = sym_count;
11538
11539                   if (sym_count > max_sym_shndx_count
11540                       && elf_symtab_shndx_list (sec->owner) != NULL)
11541                     max_sym_shndx_count = sym_count;
11542
11543                   if (esdo->this_hdr.sh_type == SHT_REL
11544                       || esdo->this_hdr.sh_type == SHT_RELA)
11545                     /* Some backends use reloc_count in relocation sections
11546                        to count particular types of relocs.  Of course,
11547                        reloc sections themselves can't have relocations.  */
11548                     ;
11549                   else if (emit_relocs)
11550                     {
11551                       reloc_count = sec->reloc_count;
11552                       if (bed->elf_backend_count_additional_relocs)
11553                         {
11554                           int c;
11555                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11556                           additional_reloc_count += c;
11557                         }
11558                     }
11559                   else if (bed->elf_backend_count_relocs)
11560                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11561
11562                   esdi = elf_section_data (sec);
11563
11564                   if ((sec->flags & SEC_RELOC) != 0)
11565                     {
11566                       size_t ext_size = 0;
11567
11568                       if (esdi->rel.hdr != NULL)
11569                         ext_size = esdi->rel.hdr->sh_size;
11570                       if (esdi->rela.hdr != NULL)
11571                         ext_size += esdi->rela.hdr->sh_size;
11572
11573                       if (ext_size > max_external_reloc_size)
11574                         max_external_reloc_size = ext_size;
11575                       if (sec->reloc_count > max_internal_reloc_count)
11576                         max_internal_reloc_count = sec->reloc_count;
11577                     }
11578                 }
11579             }
11580
11581           if (reloc_count == 0)
11582             continue;
11583
11584           reloc_count += additional_reloc_count;
11585           o->reloc_count += reloc_count;
11586
11587           if (p->type == bfd_indirect_link_order && emit_relocs)
11588             {
11589               if (esdi->rel.hdr)
11590                 {
11591                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11592                   esdo->rel.count += additional_reloc_count;
11593                 }
11594               if (esdi->rela.hdr)
11595                 {
11596                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11597                   esdo->rela.count += additional_reloc_count;
11598                 }
11599             }
11600           else
11601             {
11602               if (o->use_rela_p)
11603                 esdo->rela.count += reloc_count;
11604               else
11605                 esdo->rel.count += reloc_count;
11606             }
11607         }
11608
11609       if (o->reloc_count > 0)
11610         o->flags |= SEC_RELOC;
11611       else
11612         {
11613           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11614              set it (this is probably a bug) and if it is set
11615              assign_section_numbers will create a reloc section.  */
11616           o->flags &=~ SEC_RELOC;
11617         }
11618
11619       /* If the SEC_ALLOC flag is not set, force the section VMA to
11620          zero.  This is done in elf_fake_sections as well, but forcing
11621          the VMA to 0 here will ensure that relocs against these
11622          sections are handled correctly.  */
11623       if ((o->flags & SEC_ALLOC) == 0
11624           && ! o->user_set_vma)
11625         o->vma = 0;
11626     }
11627
11628   if (! bfd_link_relocatable (info) && merged)
11629     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11630
11631   /* Figure out the file positions for everything but the symbol table
11632      and the relocs.  We set symcount to force assign_section_numbers
11633      to create a symbol table.  */
11634   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11635   BFD_ASSERT (! abfd->output_has_begun);
11636   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11637     goto error_return;
11638
11639   /* Set sizes, and assign file positions for reloc sections.  */
11640   for (o = abfd->sections; o != NULL; o = o->next)
11641     {
11642       struct bfd_elf_section_data *esdo = elf_section_data (o);
11643       if ((o->flags & SEC_RELOC) != 0)
11644         {
11645           if (esdo->rel.hdr
11646               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11647             goto error_return;
11648
11649           if (esdo->rela.hdr
11650               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11651             goto error_return;
11652         }
11653
11654       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11655          to count upwards while actually outputting the relocations.  */
11656       esdo->rel.count = 0;
11657       esdo->rela.count = 0;
11658
11659       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11660         {
11661           /* Cache the section contents so that they can be compressed
11662              later.  Use bfd_malloc since it will be freed by
11663              bfd_compress_section_contents.  */
11664           unsigned char *contents = esdo->this_hdr.contents;
11665           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11666             abort ();
11667           contents
11668             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11669           if (contents == NULL)
11670             goto error_return;
11671           esdo->this_hdr.contents = contents;
11672         }
11673     }
11674
11675   /* We have now assigned file positions for all the sections except
11676      .symtab, .strtab, and non-loaded reloc sections.  We start the
11677      .symtab section at the current file position, and write directly
11678      to it.  We build the .strtab section in memory.  */
11679   bfd_get_symcount (abfd) = 0;
11680   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11681   /* sh_name is set in prep_headers.  */
11682   symtab_hdr->sh_type = SHT_SYMTAB;
11683   /* sh_flags, sh_addr and sh_size all start off zero.  */
11684   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11685   /* sh_link is set in assign_section_numbers.  */
11686   /* sh_info is set below.  */
11687   /* sh_offset is set just below.  */
11688   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11689
11690   if (max_sym_count < 20)
11691     max_sym_count = 20;
11692   htab->strtabsize = max_sym_count;
11693   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11694   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11695   if (htab->strtab == NULL)
11696     goto error_return;
11697   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11698   flinfo.symshndxbuf
11699     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11700        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11701
11702   if (info->strip != strip_all || emit_relocs)
11703     {
11704       file_ptr off = elf_next_file_pos (abfd);
11705
11706       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11707
11708       /* Note that at this point elf_next_file_pos (abfd) is
11709          incorrect.  We do not yet know the size of the .symtab section.
11710          We correct next_file_pos below, after we do know the size.  */
11711
11712       /* Start writing out the symbol table.  The first symbol is always a
11713          dummy symbol.  */
11714       elfsym.st_value = 0;
11715       elfsym.st_size = 0;
11716       elfsym.st_info = 0;
11717       elfsym.st_other = 0;
11718       elfsym.st_shndx = SHN_UNDEF;
11719       elfsym.st_target_internal = 0;
11720       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11721                                      bfd_und_section_ptr, NULL) != 1)
11722         goto error_return;
11723
11724       /* Output a symbol for each section.  We output these even if we are
11725          discarding local symbols, since they are used for relocs.  These
11726          symbols have no names.  We store the index of each one in the
11727          index field of the section, so that we can find it again when
11728          outputting relocs.  */
11729
11730       elfsym.st_size = 0;
11731       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11732       elfsym.st_other = 0;
11733       elfsym.st_value = 0;
11734       elfsym.st_target_internal = 0;
11735       for (i = 1; i < elf_numsections (abfd); i++)
11736         {
11737           o = bfd_section_from_elf_index (abfd, i);
11738           if (o != NULL)
11739             {
11740               o->target_index = bfd_get_symcount (abfd);
11741               elfsym.st_shndx = i;
11742               if (!bfd_link_relocatable (info))
11743                 elfsym.st_value = o->vma;
11744               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11745                                              NULL) != 1)
11746                 goto error_return;
11747             }
11748         }
11749     }
11750
11751   /* Allocate some memory to hold information read in from the input
11752      files.  */
11753   if (max_contents_size != 0)
11754     {
11755       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11756       if (flinfo.contents == NULL)
11757         goto error_return;
11758     }
11759
11760   if (max_external_reloc_size != 0)
11761     {
11762       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11763       if (flinfo.external_relocs == NULL)
11764         goto error_return;
11765     }
11766
11767   if (max_internal_reloc_count != 0)
11768     {
11769       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11770       amt *= sizeof (Elf_Internal_Rela);
11771       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11772       if (flinfo.internal_relocs == NULL)
11773         goto error_return;
11774     }
11775
11776   if (max_sym_count != 0)
11777     {
11778       amt = max_sym_count * bed->s->sizeof_sym;
11779       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11780       if (flinfo.external_syms == NULL)
11781         goto error_return;
11782
11783       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11784       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11785       if (flinfo.internal_syms == NULL)
11786         goto error_return;
11787
11788       amt = max_sym_count * sizeof (long);
11789       flinfo.indices = (long int *) bfd_malloc (amt);
11790       if (flinfo.indices == NULL)
11791         goto error_return;
11792
11793       amt = max_sym_count * sizeof (asection *);
11794       flinfo.sections = (asection **) bfd_malloc (amt);
11795       if (flinfo.sections == NULL)
11796         goto error_return;
11797     }
11798
11799   if (max_sym_shndx_count != 0)
11800     {
11801       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11802       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11803       if (flinfo.locsym_shndx == NULL)
11804         goto error_return;
11805     }
11806
11807   if (htab->tls_sec)
11808     {
11809       bfd_vma base, end = 0;
11810       asection *sec;
11811
11812       for (sec = htab->tls_sec;
11813            sec && (sec->flags & SEC_THREAD_LOCAL);
11814            sec = sec->next)
11815         {
11816           bfd_size_type size = sec->size;
11817
11818           if (size == 0
11819               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11820             {
11821               struct bfd_link_order *ord = sec->map_tail.link_order;
11822
11823               if (ord != NULL)
11824                 size = ord->offset + ord->size;
11825             }
11826           end = sec->vma + size;
11827         }
11828       base = htab->tls_sec->vma;
11829       /* Only align end of TLS section if static TLS doesn't have special
11830          alignment requirements.  */
11831       if (bed->static_tls_alignment == 1)
11832         end = align_power (end, htab->tls_sec->alignment_power);
11833       htab->tls_size = end - base;
11834     }
11835
11836   /* Reorder SHF_LINK_ORDER sections.  */
11837   for (o = abfd->sections; o != NULL; o = o->next)
11838     {
11839       if (!elf_fixup_link_order (abfd, o))
11840         return FALSE;
11841     }
11842
11843   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11844     return FALSE;
11845
11846   /* Since ELF permits relocations to be against local symbols, we
11847      must have the local symbols available when we do the relocations.
11848      Since we would rather only read the local symbols once, and we
11849      would rather not keep them in memory, we handle all the
11850      relocations for a single input file at the same time.
11851
11852      Unfortunately, there is no way to know the total number of local
11853      symbols until we have seen all of them, and the local symbol
11854      indices precede the global symbol indices.  This means that when
11855      we are generating relocatable output, and we see a reloc against
11856      a global symbol, we can not know the symbol index until we have
11857      finished examining all the local symbols to see which ones we are
11858      going to output.  To deal with this, we keep the relocations in
11859      memory, and don't output them until the end of the link.  This is
11860      an unfortunate waste of memory, but I don't see a good way around
11861      it.  Fortunately, it only happens when performing a relocatable
11862      link, which is not the common case.  FIXME: If keep_memory is set
11863      we could write the relocs out and then read them again; I don't
11864      know how bad the memory loss will be.  */
11865
11866   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11867     sub->output_has_begun = FALSE;
11868   for (o = abfd->sections; o != NULL; o = o->next)
11869     {
11870       for (p = o->map_head.link_order; p != NULL; p = p->next)
11871         {
11872           if (p->type == bfd_indirect_link_order
11873               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11874                   == bfd_target_elf_flavour)
11875               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11876             {
11877               if (! sub->output_has_begun)
11878                 {
11879                   if (! elf_link_input_bfd (&flinfo, sub))
11880                     goto error_return;
11881                   sub->output_has_begun = TRUE;
11882                 }
11883             }
11884           else if (p->type == bfd_section_reloc_link_order
11885                    || p->type == bfd_symbol_reloc_link_order)
11886             {
11887               if (! elf_reloc_link_order (abfd, info, o, p))
11888                 goto error_return;
11889             }
11890           else
11891             {
11892               if (! _bfd_default_link_order (abfd, info, o, p))
11893                 {
11894                   if (p->type == bfd_indirect_link_order
11895                       && (bfd_get_flavour (sub)
11896                           == bfd_target_elf_flavour)
11897                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11898                           != bed->s->elfclass))
11899                     {
11900                       const char *iclass, *oclass;
11901
11902                       switch (bed->s->elfclass)
11903                         {
11904                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11905                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11906                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11907                         default: abort ();
11908                         }
11909
11910                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11911                         {
11912                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11913                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11914                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11915                         default: abort ();
11916                         }
11917
11918                       bfd_set_error (bfd_error_wrong_format);
11919                       _bfd_error_handler
11920                         /* xgettext:c-format */
11921                         (_("%B: file class %s incompatible with %s"),
11922                          sub, iclass, oclass);
11923                     }
11924
11925                   goto error_return;
11926                 }
11927             }
11928         }
11929     }
11930
11931   /* Free symbol buffer if needed.  */
11932   if (!info->reduce_memory_overheads)
11933     {
11934       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11935         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11936             && elf_tdata (sub)->symbuf)
11937           {
11938             free (elf_tdata (sub)->symbuf);
11939             elf_tdata (sub)->symbuf = NULL;
11940           }
11941     }
11942
11943   /* Output any global symbols that got converted to local in a
11944      version script or due to symbol visibility.  We do this in a
11945      separate step since ELF requires all local symbols to appear
11946      prior to any global symbols.  FIXME: We should only do this if
11947      some global symbols were, in fact, converted to become local.
11948      FIXME: Will this work correctly with the Irix 5 linker?  */
11949   eoinfo.failed = FALSE;
11950   eoinfo.flinfo = &flinfo;
11951   eoinfo.localsyms = TRUE;
11952   eoinfo.file_sym_done = FALSE;
11953   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11954   if (eoinfo.failed)
11955     return FALSE;
11956
11957   /* If backend needs to output some local symbols not present in the hash
11958      table, do it now.  */
11959   if (bed->elf_backend_output_arch_local_syms
11960       && (info->strip != strip_all || emit_relocs))
11961     {
11962       typedef int (*out_sym_func)
11963         (void *, const char *, Elf_Internal_Sym *, asection *,
11964          struct elf_link_hash_entry *);
11965
11966       if (! ((*bed->elf_backend_output_arch_local_syms)
11967              (abfd, info, &flinfo,
11968               (out_sym_func) elf_link_output_symstrtab)))
11969         return FALSE;
11970     }
11971
11972   /* That wrote out all the local symbols.  Finish up the symbol table
11973      with the global symbols. Even if we want to strip everything we
11974      can, we still need to deal with those global symbols that got
11975      converted to local in a version script.  */
11976
11977   /* The sh_info field records the index of the first non local symbol.  */
11978   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11979
11980   if (dynamic
11981       && htab->dynsym != NULL
11982       && htab->dynsym->output_section != bfd_abs_section_ptr)
11983     {
11984       Elf_Internal_Sym sym;
11985       bfd_byte *dynsym = htab->dynsym->contents;
11986
11987       o = htab->dynsym->output_section;
11988       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
11989
11990       /* Write out the section symbols for the output sections.  */
11991       if (bfd_link_pic (info)
11992           || htab->is_relocatable_executable)
11993         {
11994           asection *s;
11995
11996           sym.st_size = 0;
11997           sym.st_name = 0;
11998           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11999           sym.st_other = 0;
12000           sym.st_target_internal = 0;
12001
12002           for (s = abfd->sections; s != NULL; s = s->next)
12003             {
12004               int indx;
12005               bfd_byte *dest;
12006               long dynindx;
12007
12008               dynindx = elf_section_data (s)->dynindx;
12009               if (dynindx <= 0)
12010                 continue;
12011               indx = elf_section_data (s)->this_idx;
12012               BFD_ASSERT (indx > 0);
12013               sym.st_shndx = indx;
12014               if (! check_dynsym (abfd, &sym))
12015                 return FALSE;
12016               sym.st_value = s->vma;
12017               dest = dynsym + dynindx * bed->s->sizeof_sym;
12018               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12019             }
12020         }
12021
12022       /* Write out the local dynsyms.  */
12023       if (htab->dynlocal)
12024         {
12025           struct elf_link_local_dynamic_entry *e;
12026           for (e = htab->dynlocal; e ; e = e->next)
12027             {
12028               asection *s;
12029               bfd_byte *dest;
12030
12031               /* Copy the internal symbol and turn off visibility.
12032                  Note that we saved a word of storage and overwrote
12033                  the original st_name with the dynstr_index.  */
12034               sym = e->isym;
12035               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12036
12037               s = bfd_section_from_elf_index (e->input_bfd,
12038                                               e->isym.st_shndx);
12039               if (s != NULL)
12040                 {
12041                   sym.st_shndx =
12042                     elf_section_data (s->output_section)->this_idx;
12043                   if (! check_dynsym (abfd, &sym))
12044                     return FALSE;
12045                   sym.st_value = (s->output_section->vma
12046                                   + s->output_offset
12047                                   + e->isym.st_value);
12048                 }
12049
12050               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12051               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12052             }
12053         }
12054     }
12055
12056   /* We get the global symbols from the hash table.  */
12057   eoinfo.failed = FALSE;
12058   eoinfo.localsyms = FALSE;
12059   eoinfo.flinfo = &flinfo;
12060   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12061   if (eoinfo.failed)
12062     return FALSE;
12063
12064   /* If backend needs to output some symbols not present in the hash
12065      table, do it now.  */
12066   if (bed->elf_backend_output_arch_syms
12067       && (info->strip != strip_all || emit_relocs))
12068     {
12069       typedef int (*out_sym_func)
12070         (void *, const char *, Elf_Internal_Sym *, asection *,
12071          struct elf_link_hash_entry *);
12072
12073       if (! ((*bed->elf_backend_output_arch_syms)
12074              (abfd, info, &flinfo,
12075               (out_sym_func) elf_link_output_symstrtab)))
12076         return FALSE;
12077     }
12078
12079   /* Finalize the .strtab section.  */
12080   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12081
12082   /* Swap out the .strtab section. */
12083   if (!elf_link_swap_symbols_out (&flinfo))
12084     return FALSE;
12085
12086   /* Now we know the size of the symtab section.  */
12087   if (bfd_get_symcount (abfd) > 0)
12088     {
12089       /* Finish up and write out the symbol string table (.strtab)
12090          section.  */
12091       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12092       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12093
12094       if (elf_symtab_shndx_list (abfd))
12095         {
12096           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12097
12098           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12099             {
12100               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12101               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12102               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12103               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12104               symtab_shndx_hdr->sh_size = amt;
12105
12106               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12107                                                                off, TRUE);
12108
12109               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12110                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12111                 return FALSE;
12112             }
12113         }
12114
12115       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12116       /* sh_name was set in prep_headers.  */
12117       symstrtab_hdr->sh_type = SHT_STRTAB;
12118       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12119       symstrtab_hdr->sh_addr = 0;
12120       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12121       symstrtab_hdr->sh_entsize = 0;
12122       symstrtab_hdr->sh_link = 0;
12123       symstrtab_hdr->sh_info = 0;
12124       /* sh_offset is set just below.  */
12125       symstrtab_hdr->sh_addralign = 1;
12126
12127       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12128                                                        off, TRUE);
12129       elf_next_file_pos (abfd) = off;
12130
12131       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12132           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12133         return FALSE;
12134     }
12135
12136   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12137     {
12138       _bfd_error_handler (_("%B: failed to generate import library"),
12139                           info->out_implib_bfd);
12140       return FALSE;
12141     }
12142
12143   /* Adjust the relocs to have the correct symbol indices.  */
12144   for (o = abfd->sections; o != NULL; o = o->next)
12145     {
12146       struct bfd_elf_section_data *esdo = elf_section_data (o);
12147       bfd_boolean sort;
12148       if ((o->flags & SEC_RELOC) == 0)
12149         continue;
12150
12151       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12152       if (esdo->rel.hdr != NULL
12153           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort))
12154         return FALSE;
12155       if (esdo->rela.hdr != NULL
12156           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort))
12157         return FALSE;
12158
12159       /* Set the reloc_count field to 0 to prevent write_relocs from
12160          trying to swap the relocs out itself.  */
12161       o->reloc_count = 0;
12162     }
12163
12164   if (dynamic && info->combreloc && dynobj != NULL)
12165     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12166
12167   /* If we are linking against a dynamic object, or generating a
12168      shared library, finish up the dynamic linking information.  */
12169   if (dynamic)
12170     {
12171       bfd_byte *dyncon, *dynconend;
12172
12173       /* Fix up .dynamic entries.  */
12174       o = bfd_get_linker_section (dynobj, ".dynamic");
12175       BFD_ASSERT (o != NULL);
12176
12177       dyncon = o->contents;
12178       dynconend = o->contents + o->size;
12179       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12180         {
12181           Elf_Internal_Dyn dyn;
12182           const char *name;
12183           unsigned int type;
12184           bfd_size_type sh_size;
12185           bfd_vma sh_addr;
12186
12187           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12188
12189           switch (dyn.d_tag)
12190             {
12191             default:
12192               continue;
12193             case DT_NULL:
12194               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12195                 {
12196                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12197                     {
12198                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12199                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12200                     default: continue;
12201                     }
12202                   dyn.d_un.d_val = relativecount;
12203                   relativecount = 0;
12204                   break;
12205                 }
12206               continue;
12207
12208             case DT_INIT:
12209               name = info->init_function;
12210               goto get_sym;
12211             case DT_FINI:
12212               name = info->fini_function;
12213             get_sym:
12214               {
12215                 struct elf_link_hash_entry *h;
12216
12217                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12218                 if (h != NULL
12219                     && (h->root.type == bfd_link_hash_defined
12220                         || h->root.type == bfd_link_hash_defweak))
12221                   {
12222                     dyn.d_un.d_ptr = h->root.u.def.value;
12223                     o = h->root.u.def.section;
12224                     if (o->output_section != NULL)
12225                       dyn.d_un.d_ptr += (o->output_section->vma
12226                                          + o->output_offset);
12227                     else
12228                       {
12229                         /* The symbol is imported from another shared
12230                            library and does not apply to this one.  */
12231                         dyn.d_un.d_ptr = 0;
12232                       }
12233                     break;
12234                   }
12235               }
12236               continue;
12237
12238             case DT_PREINIT_ARRAYSZ:
12239               name = ".preinit_array";
12240               goto get_out_size;
12241             case DT_INIT_ARRAYSZ:
12242               name = ".init_array";
12243               goto get_out_size;
12244             case DT_FINI_ARRAYSZ:
12245               name = ".fini_array";
12246             get_out_size:
12247               o = bfd_get_section_by_name (abfd, name);
12248               if (o == NULL)
12249                 {
12250                   _bfd_error_handler
12251                     (_("could not find section %s"), name);
12252                   goto error_return;
12253                 }
12254               if (o->size == 0)
12255                 _bfd_error_handler
12256                   (_("warning: %s section has zero size"), name);
12257               dyn.d_un.d_val = o->size;
12258               break;
12259
12260             case DT_PREINIT_ARRAY:
12261               name = ".preinit_array";
12262               goto get_out_vma;
12263             case DT_INIT_ARRAY:
12264               name = ".init_array";
12265               goto get_out_vma;
12266             case DT_FINI_ARRAY:
12267               name = ".fini_array";
12268             get_out_vma:
12269               o = bfd_get_section_by_name (abfd, name);
12270               goto do_vma;
12271
12272             case DT_HASH:
12273               name = ".hash";
12274               goto get_vma;
12275             case DT_GNU_HASH:
12276               name = ".gnu.hash";
12277               goto get_vma;
12278             case DT_STRTAB:
12279               name = ".dynstr";
12280               goto get_vma;
12281             case DT_SYMTAB:
12282               name = ".dynsym";
12283               goto get_vma;
12284             case DT_VERDEF:
12285               name = ".gnu.version_d";
12286               goto get_vma;
12287             case DT_VERNEED:
12288               name = ".gnu.version_r";
12289               goto get_vma;
12290             case DT_VERSYM:
12291               name = ".gnu.version";
12292             get_vma:
12293               o = bfd_get_linker_section (dynobj, name);
12294             do_vma:
12295               if (o == NULL)
12296                 {
12297                   _bfd_error_handler
12298                     (_("could not find section %s"), name);
12299                   goto error_return;
12300                 }
12301               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12302                 {
12303                   _bfd_error_handler
12304                     (_("warning: section '%s' is being made into a note"), name);
12305                   bfd_set_error (bfd_error_nonrepresentable_section);
12306                   goto error_return;
12307                 }
12308               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12309               break;
12310
12311             case DT_REL:
12312             case DT_RELA:
12313             case DT_RELSZ:
12314             case DT_RELASZ:
12315               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12316                 type = SHT_REL;
12317               else
12318                 type = SHT_RELA;
12319               sh_size = 0;
12320               sh_addr = 0;
12321               for (i = 1; i < elf_numsections (abfd); i++)
12322                 {
12323                   Elf_Internal_Shdr *hdr;
12324
12325                   hdr = elf_elfsections (abfd)[i];
12326                   if (hdr->sh_type == type
12327                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12328                     {
12329                       sh_size += hdr->sh_size;
12330                       if (sh_addr == 0
12331                           || sh_addr > hdr->sh_addr)
12332                         sh_addr = hdr->sh_addr;
12333                     }
12334                 }
12335
12336               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12337                 {
12338                   /* Don't count procedure linkage table relocs in the
12339                      overall reloc count.  */
12340                   sh_size -= htab->srelplt->size;
12341                   if (sh_size == 0)
12342                     /* If the size is zero, make the address zero too.
12343                        This is to avoid a glibc bug.  If the backend
12344                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12345                        zero, then we'll put DT_RELA at the end of
12346                        DT_JMPREL.  glibc will interpret the end of
12347                        DT_RELA matching the end of DT_JMPREL as the
12348                        case where DT_RELA includes DT_JMPREL, and for
12349                        LD_BIND_NOW will decide that processing DT_RELA
12350                        will process the PLT relocs too.  Net result:
12351                        No PLT relocs applied.  */
12352                     sh_addr = 0;
12353
12354                   /* If .rela.plt is the first .rela section, exclude
12355                      it from DT_RELA.  */
12356                   else if (sh_addr == (htab->srelplt->output_section->vma
12357                                        + htab->srelplt->output_offset))
12358                     sh_addr += htab->srelplt->size;
12359                 }
12360
12361               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12362                 dyn.d_un.d_val = sh_size;
12363               else
12364                 dyn.d_un.d_ptr = sh_addr;
12365               break;
12366             }
12367           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12368         }
12369     }
12370
12371   /* If we have created any dynamic sections, then output them.  */
12372   if (dynobj != NULL)
12373     {
12374       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12375         goto error_return;
12376
12377       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12378       if (((info->warn_shared_textrel && bfd_link_pic (info))
12379            || info->error_textrel)
12380           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12381         {
12382           bfd_byte *dyncon, *dynconend;
12383
12384           dyncon = o->contents;
12385           dynconend = o->contents + o->size;
12386           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12387             {
12388               Elf_Internal_Dyn dyn;
12389
12390               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12391
12392               if (dyn.d_tag == DT_TEXTREL)
12393                 {
12394                   if (info->error_textrel)
12395                     info->callbacks->einfo
12396                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12397                   else
12398                     info->callbacks->einfo
12399                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12400                   break;
12401                 }
12402             }
12403         }
12404
12405       for (o = dynobj->sections; o != NULL; o = o->next)
12406         {
12407           if ((o->flags & SEC_HAS_CONTENTS) == 0
12408               || o->size == 0
12409               || o->output_section == bfd_abs_section_ptr)
12410             continue;
12411           if ((o->flags & SEC_LINKER_CREATED) == 0)
12412             {
12413               /* At this point, we are only interested in sections
12414                  created by _bfd_elf_link_create_dynamic_sections.  */
12415               continue;
12416             }
12417           if (htab->stab_info.stabstr == o)
12418             continue;
12419           if (htab->eh_info.hdr_sec == o)
12420             continue;
12421           if (strcmp (o->name, ".dynstr") != 0)
12422             {
12423               if (! bfd_set_section_contents (abfd, o->output_section,
12424                                               o->contents,
12425                                               (file_ptr) o->output_offset
12426                                               * bfd_octets_per_byte (abfd),
12427                                               o->size))
12428                 goto error_return;
12429             }
12430           else
12431             {
12432               /* The contents of the .dynstr section are actually in a
12433                  stringtab.  */
12434               file_ptr off;
12435
12436               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12437               if (bfd_seek (abfd, off, SEEK_SET) != 0
12438                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12439                 goto error_return;
12440             }
12441         }
12442     }
12443
12444   if (bfd_link_relocatable (info))
12445     {
12446       bfd_boolean failed = FALSE;
12447
12448       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12449       if (failed)
12450         goto error_return;
12451     }
12452
12453   /* If we have optimized stabs strings, output them.  */
12454   if (htab->stab_info.stabstr != NULL)
12455     {
12456       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12457         goto error_return;
12458     }
12459
12460   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12461     goto error_return;
12462
12463   elf_final_link_free (abfd, &flinfo);
12464
12465   elf_linker (abfd) = TRUE;
12466
12467   if (attr_section)
12468     {
12469       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12470       if (contents == NULL)
12471         return FALSE;   /* Bail out and fail.  */
12472       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12473       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12474       free (contents);
12475     }
12476
12477   return TRUE;
12478
12479  error_return:
12480   elf_final_link_free (abfd, &flinfo);
12481   return FALSE;
12482 }
12483 \f
12484 /* Initialize COOKIE for input bfd ABFD.  */
12485
12486 static bfd_boolean
12487 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12488                    struct bfd_link_info *info, bfd *abfd)
12489 {
12490   Elf_Internal_Shdr *symtab_hdr;
12491   const struct elf_backend_data *bed;
12492
12493   bed = get_elf_backend_data (abfd);
12494   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12495
12496   cookie->abfd = abfd;
12497   cookie->sym_hashes = elf_sym_hashes (abfd);
12498   cookie->bad_symtab = elf_bad_symtab (abfd);
12499   if (cookie->bad_symtab)
12500     {
12501       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12502       cookie->extsymoff = 0;
12503     }
12504   else
12505     {
12506       cookie->locsymcount = symtab_hdr->sh_info;
12507       cookie->extsymoff = symtab_hdr->sh_info;
12508     }
12509
12510   if (bed->s->arch_size == 32)
12511     cookie->r_sym_shift = 8;
12512   else
12513     cookie->r_sym_shift = 32;
12514
12515   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12516   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12517     {
12518       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12519                                               cookie->locsymcount, 0,
12520                                               NULL, NULL, NULL);
12521       if (cookie->locsyms == NULL)
12522         {
12523           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12524           return FALSE;
12525         }
12526       if (info->keep_memory)
12527         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12528     }
12529   return TRUE;
12530 }
12531
12532 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12533
12534 static void
12535 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12536 {
12537   Elf_Internal_Shdr *symtab_hdr;
12538
12539   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12540   if (cookie->locsyms != NULL
12541       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12542     free (cookie->locsyms);
12543 }
12544
12545 /* Initialize the relocation information in COOKIE for input section SEC
12546    of input bfd ABFD.  */
12547
12548 static bfd_boolean
12549 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12550                         struct bfd_link_info *info, bfd *abfd,
12551                         asection *sec)
12552 {
12553   const struct elf_backend_data *bed;
12554
12555   if (sec->reloc_count == 0)
12556     {
12557       cookie->rels = NULL;
12558       cookie->relend = NULL;
12559     }
12560   else
12561     {
12562       bed = get_elf_backend_data (abfd);
12563
12564       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12565                                                 info->keep_memory);
12566       if (cookie->rels == NULL)
12567         return FALSE;
12568       cookie->rel = cookie->rels;
12569       cookie->relend = (cookie->rels
12570                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12571     }
12572   cookie->rel = cookie->rels;
12573   return TRUE;
12574 }
12575
12576 /* Free the memory allocated by init_reloc_cookie_rels,
12577    if appropriate.  */
12578
12579 static void
12580 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12581                         asection *sec)
12582 {
12583   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12584     free (cookie->rels);
12585 }
12586
12587 /* Initialize the whole of COOKIE for input section SEC.  */
12588
12589 static bfd_boolean
12590 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12591                                struct bfd_link_info *info,
12592                                asection *sec)
12593 {
12594   if (!init_reloc_cookie (cookie, info, sec->owner))
12595     goto error1;
12596   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12597     goto error2;
12598   return TRUE;
12599
12600  error2:
12601   fini_reloc_cookie (cookie, sec->owner);
12602  error1:
12603   return FALSE;
12604 }
12605
12606 /* Free the memory allocated by init_reloc_cookie_for_section,
12607    if appropriate.  */
12608
12609 static void
12610 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12611                                asection *sec)
12612 {
12613   fini_reloc_cookie_rels (cookie, sec);
12614   fini_reloc_cookie (cookie, sec->owner);
12615 }
12616 \f
12617 /* Garbage collect unused sections.  */
12618
12619 /* Default gc_mark_hook.  */
12620
12621 asection *
12622 _bfd_elf_gc_mark_hook (asection *sec,
12623                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12624                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12625                        struct elf_link_hash_entry *h,
12626                        Elf_Internal_Sym *sym)
12627 {
12628   if (h != NULL)
12629     {
12630       switch (h->root.type)
12631         {
12632         case bfd_link_hash_defined:
12633         case bfd_link_hash_defweak:
12634           return h->root.u.def.section;
12635
12636         case bfd_link_hash_common:
12637           return h->root.u.c.p->section;
12638
12639         default:
12640           break;
12641         }
12642     }
12643   else
12644     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12645
12646   return NULL;
12647 }
12648
12649 /* For undefined __start_<name> and __stop_<name> symbols, return the
12650    first input section matching <name>.  Return NULL otherwise.  */
12651
12652 asection *
12653 _bfd_elf_is_start_stop (const struct bfd_link_info *info,
12654                         struct elf_link_hash_entry *h)
12655 {
12656   asection *s;
12657   const char *sec_name;
12658
12659   if (h->root.type != bfd_link_hash_undefined
12660       && h->root.type != bfd_link_hash_undefweak)
12661     return NULL;
12662
12663   s = h->root.u.undef.section;
12664   if (s != NULL)
12665     {
12666       if (s == (asection *) 0 - 1)
12667         return NULL;
12668       return s;
12669     }
12670
12671   sec_name = NULL;
12672   if (strncmp (h->root.root.string, "__start_", 8) == 0)
12673     sec_name = h->root.root.string + 8;
12674   else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12675     sec_name = h->root.root.string + 7;
12676
12677   if (sec_name != NULL && *sec_name != '\0')
12678     {
12679       bfd *i;
12680
12681       for (i = info->input_bfds; i != NULL; i = i->link.next)
12682         {
12683           s = bfd_get_section_by_name (i, sec_name);
12684           if (s != NULL)
12685             {
12686               h->root.u.undef.section = s;
12687               break;
12688             }
12689         }
12690     }
12691
12692   if (s == NULL)
12693     h->root.u.undef.section = (asection *) 0 - 1;
12694
12695   return s;
12696 }
12697
12698 /* COOKIE->rel describes a relocation against section SEC, which is
12699    a section we've decided to keep.  Return the section that contains
12700    the relocation symbol, or NULL if no section contains it.  */
12701
12702 asection *
12703 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12704                        elf_gc_mark_hook_fn gc_mark_hook,
12705                        struct elf_reloc_cookie *cookie,
12706                        bfd_boolean *start_stop)
12707 {
12708   unsigned long r_symndx;
12709   struct elf_link_hash_entry *h;
12710
12711   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12712   if (r_symndx == STN_UNDEF)
12713     return NULL;
12714
12715   if (r_symndx >= cookie->locsymcount
12716       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12717     {
12718       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12719       if (h == NULL)
12720         {
12721           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12722                                   sec->owner);
12723           return NULL;
12724         }
12725       while (h->root.type == bfd_link_hash_indirect
12726              || h->root.type == bfd_link_hash_warning)
12727         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12728       h->mark = 1;
12729       /* If this symbol is weak and there is a non-weak definition, we
12730          keep the non-weak definition because many backends put
12731          dynamic reloc info on the non-weak definition for code
12732          handling copy relocs.  */
12733       if (h->u.weakdef != NULL)
12734         h->u.weakdef->mark = 1;
12735
12736       if (start_stop != NULL)
12737         {
12738           /* To work around a glibc bug, mark all XXX input sections
12739              when there is an as yet undefined reference to __start_XXX
12740              or __stop_XXX symbols.  The linker will later define such
12741              symbols for orphan input sections that have a name
12742              representable as a C identifier.  */
12743           asection *s = _bfd_elf_is_start_stop (info, h);
12744
12745           if (s != NULL)
12746             {
12747               *start_stop = !s->gc_mark;
12748               return s;
12749             }
12750         }
12751
12752       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12753     }
12754
12755   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12756                           &cookie->locsyms[r_symndx]);
12757 }
12758
12759 /* COOKIE->rel describes a relocation against section SEC, which is
12760    a section we've decided to keep.  Mark the section that contains
12761    the relocation symbol.  */
12762
12763 bfd_boolean
12764 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12765                         asection *sec,
12766                         elf_gc_mark_hook_fn gc_mark_hook,
12767                         struct elf_reloc_cookie *cookie)
12768 {
12769   asection *rsec;
12770   bfd_boolean start_stop = FALSE;
12771
12772   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12773   while (rsec != NULL)
12774     {
12775       if (!rsec->gc_mark)
12776         {
12777           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12778               || (rsec->owner->flags & DYNAMIC) != 0)
12779             rsec->gc_mark = 1;
12780           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12781             return FALSE;
12782         }
12783       if (!start_stop)
12784         break;
12785       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12786     }
12787   return TRUE;
12788 }
12789
12790 /* The mark phase of garbage collection.  For a given section, mark
12791    it and any sections in this section's group, and all the sections
12792    which define symbols to which it refers.  */
12793
12794 bfd_boolean
12795 _bfd_elf_gc_mark (struct bfd_link_info *info,
12796                   asection *sec,
12797                   elf_gc_mark_hook_fn gc_mark_hook)
12798 {
12799   bfd_boolean ret;
12800   asection *group_sec, *eh_frame;
12801
12802   sec->gc_mark = 1;
12803
12804   /* Mark all the sections in the group.  */
12805   group_sec = elf_section_data (sec)->next_in_group;
12806   if (group_sec && !group_sec->gc_mark)
12807     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12808       return FALSE;
12809
12810   /* Look through the section relocs.  */
12811   ret = TRUE;
12812   eh_frame = elf_eh_frame_section (sec->owner);
12813   if ((sec->flags & SEC_RELOC) != 0
12814       && sec->reloc_count > 0
12815       && sec != eh_frame)
12816     {
12817       struct elf_reloc_cookie cookie;
12818
12819       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12820         ret = FALSE;
12821       else
12822         {
12823           for (; cookie.rel < cookie.relend; cookie.rel++)
12824             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12825               {
12826                 ret = FALSE;
12827                 break;
12828               }
12829           fini_reloc_cookie_for_section (&cookie, sec);
12830         }
12831     }
12832
12833   if (ret && eh_frame && elf_fde_list (sec))
12834     {
12835       struct elf_reloc_cookie cookie;
12836
12837       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12838         ret = FALSE;
12839       else
12840         {
12841           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12842                                       gc_mark_hook, &cookie))
12843             ret = FALSE;
12844           fini_reloc_cookie_for_section (&cookie, eh_frame);
12845         }
12846     }
12847
12848   eh_frame = elf_section_eh_frame_entry (sec);
12849   if (ret && eh_frame && !eh_frame->gc_mark)
12850     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12851       ret = FALSE;
12852
12853   return ret;
12854 }
12855
12856 /* Scan and mark sections in a special or debug section group.  */
12857
12858 static void
12859 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12860 {
12861   /* Point to first section of section group.  */
12862   asection *ssec;
12863   /* Used to iterate the section group.  */
12864   asection *msec;
12865
12866   bfd_boolean is_special_grp = TRUE;
12867   bfd_boolean is_debug_grp = TRUE;
12868
12869   /* First scan to see if group contains any section other than debug
12870      and special section.  */
12871   ssec = msec = elf_next_in_group (grp);
12872   do
12873     {
12874       if ((msec->flags & SEC_DEBUGGING) == 0)
12875         is_debug_grp = FALSE;
12876
12877       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12878         is_special_grp = FALSE;
12879
12880       msec = elf_next_in_group (msec);
12881     }
12882   while (msec != ssec);
12883
12884   /* If this is a pure debug section group or pure special section group,
12885      keep all sections in this group.  */
12886   if (is_debug_grp || is_special_grp)
12887     {
12888       do
12889         {
12890           msec->gc_mark = 1;
12891           msec = elf_next_in_group (msec);
12892         }
12893       while (msec != ssec);
12894     }
12895 }
12896
12897 /* Keep debug and special sections.  */
12898
12899 bfd_boolean
12900 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12901                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12902 {
12903   bfd *ibfd;
12904
12905   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12906     {
12907       asection *isec;
12908       bfd_boolean some_kept;
12909       bfd_boolean debug_frag_seen;
12910
12911       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12912         continue;
12913
12914       /* Ensure all linker created sections are kept,
12915          see if any other section is already marked,
12916          and note if we have any fragmented debug sections.  */
12917       debug_frag_seen = some_kept = FALSE;
12918       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12919         {
12920           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12921             isec->gc_mark = 1;
12922           else if (isec->gc_mark)
12923             some_kept = TRUE;
12924
12925           if (debug_frag_seen == FALSE
12926               && (isec->flags & SEC_DEBUGGING)
12927               && CONST_STRNEQ (isec->name, ".debug_line."))
12928             debug_frag_seen = TRUE;
12929         }
12930
12931       /* If no section in this file will be kept, then we can
12932          toss out the debug and special sections.  */
12933       if (!some_kept)
12934         continue;
12935
12936       /* Keep debug and special sections like .comment when they are
12937          not part of a group.  Also keep section groups that contain
12938          just debug sections or special sections.  */
12939       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12940         {
12941           if ((isec->flags & SEC_GROUP) != 0)
12942             _bfd_elf_gc_mark_debug_special_section_group (isec);
12943           else if (((isec->flags & SEC_DEBUGGING) != 0
12944                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12945                    && elf_next_in_group (isec) == NULL)
12946             isec->gc_mark = 1;
12947         }
12948
12949       if (! debug_frag_seen)
12950         continue;
12951
12952       /* Look for CODE sections which are going to be discarded,
12953          and find and discard any fragmented debug sections which
12954          are associated with that code section.  */
12955       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12956         if ((isec->flags & SEC_CODE) != 0
12957             && isec->gc_mark == 0)
12958           {
12959             unsigned int ilen;
12960             asection *dsec;
12961
12962             ilen = strlen (isec->name);
12963
12964             /* Association is determined by the name of the debug section
12965                containing the name of the code section as a suffix.  For
12966                example .debug_line.text.foo is a debug section associated
12967                with .text.foo.  */
12968             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12969               {
12970                 unsigned int dlen;
12971
12972                 if (dsec->gc_mark == 0
12973                     || (dsec->flags & SEC_DEBUGGING) == 0)
12974                   continue;
12975
12976                 dlen = strlen (dsec->name);
12977
12978                 if (dlen > ilen
12979                     && strncmp (dsec->name + (dlen - ilen),
12980                                 isec->name, ilen) == 0)
12981                   {
12982                     dsec->gc_mark = 0;
12983                   }
12984               }
12985           }
12986     }
12987   return TRUE;
12988 }
12989
12990 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12991
12992 typedef bfd_boolean (*gc_sweep_hook_fn)
12993   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12994
12995 static bfd_boolean
12996 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12997 {
12998   bfd *sub;
12999   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13000   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
13001
13002   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13003     {
13004       asection *o;
13005
13006       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13007           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13008         continue;
13009
13010       for (o = sub->sections; o != NULL; o = o->next)
13011         {
13012           /* When any section in a section group is kept, we keep all
13013              sections in the section group.  If the first member of
13014              the section group is excluded, we will also exclude the
13015              group section.  */
13016           if (o->flags & SEC_GROUP)
13017             {
13018               asection *first = elf_next_in_group (o);
13019               o->gc_mark = first->gc_mark;
13020             }
13021
13022           if (o->gc_mark)
13023             continue;
13024
13025           /* Skip sweeping sections already excluded.  */
13026           if (o->flags & SEC_EXCLUDE)
13027             continue;
13028
13029           /* Since this is early in the link process, it is simple
13030              to remove a section from the output.  */
13031           o->flags |= SEC_EXCLUDE;
13032
13033           if (info->print_gc_sections && o->size != 0)
13034             /* xgettext:c-format */
13035             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13036                                 o, sub);
13037
13038           /* But we also have to update some of the relocation
13039              info we collected before.  */
13040           if (gc_sweep_hook
13041               && (o->flags & SEC_RELOC) != 0
13042               && o->reloc_count != 0
13043               && !((info->strip == strip_all || info->strip == strip_debugger)
13044                    && (o->flags & SEC_DEBUGGING) != 0)
13045               && !bfd_is_abs_section (o->output_section))
13046             {
13047               Elf_Internal_Rela *internal_relocs;
13048               bfd_boolean r;
13049
13050               internal_relocs
13051                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
13052                                              info->keep_memory);
13053               if (internal_relocs == NULL)
13054                 return FALSE;
13055
13056               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
13057
13058               if (elf_section_data (o)->relocs != internal_relocs)
13059                 free (internal_relocs);
13060
13061               if (!r)
13062                 return FALSE;
13063             }
13064         }
13065     }
13066
13067   return TRUE;
13068 }
13069
13070 /* Propagate collected vtable information.  This is called through
13071    elf_link_hash_traverse.  */
13072
13073 static bfd_boolean
13074 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13075 {
13076   /* Those that are not vtables.  */
13077   if (h->vtable == NULL || h->vtable->parent == NULL)
13078     return TRUE;
13079
13080   /* Those vtables that do not have parents, we cannot merge.  */
13081   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
13082     return TRUE;
13083
13084   /* If we've already been done, exit.  */
13085   if (h->vtable->used && h->vtable->used[-1])
13086     return TRUE;
13087
13088   /* Make sure the parent's table is up to date.  */
13089   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
13090
13091   if (h->vtable->used == NULL)
13092     {
13093       /* None of this table's entries were referenced.  Re-use the
13094          parent's table.  */
13095       h->vtable->used = h->vtable->parent->vtable->used;
13096       h->vtable->size = h->vtable->parent->vtable->size;
13097     }
13098   else
13099     {
13100       size_t n;
13101       bfd_boolean *cu, *pu;
13102
13103       /* Or the parent's entries into ours.  */
13104       cu = h->vtable->used;
13105       cu[-1] = TRUE;
13106       pu = h->vtable->parent->vtable->used;
13107       if (pu != NULL)
13108         {
13109           const struct elf_backend_data *bed;
13110           unsigned int log_file_align;
13111
13112           bed = get_elf_backend_data (h->root.u.def.section->owner);
13113           log_file_align = bed->s->log_file_align;
13114           n = h->vtable->parent->vtable->size >> log_file_align;
13115           while (n--)
13116             {
13117               if (*pu)
13118                 *cu = TRUE;
13119               pu++;
13120               cu++;
13121             }
13122         }
13123     }
13124
13125   return TRUE;
13126 }
13127
13128 static bfd_boolean
13129 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13130 {
13131   asection *sec;
13132   bfd_vma hstart, hend;
13133   Elf_Internal_Rela *relstart, *relend, *rel;
13134   const struct elf_backend_data *bed;
13135   unsigned int log_file_align;
13136
13137   /* Take care of both those symbols that do not describe vtables as
13138      well as those that are not loaded.  */
13139   if (h->vtable == NULL || h->vtable->parent == NULL)
13140     return TRUE;
13141
13142   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13143               || h->root.type == bfd_link_hash_defweak);
13144
13145   sec = h->root.u.def.section;
13146   hstart = h->root.u.def.value;
13147   hend = hstart + h->size;
13148
13149   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13150   if (!relstart)
13151     return *(bfd_boolean *) okp = FALSE;
13152   bed = get_elf_backend_data (sec->owner);
13153   log_file_align = bed->s->log_file_align;
13154
13155   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
13156
13157   for (rel = relstart; rel < relend; ++rel)
13158     if (rel->r_offset >= hstart && rel->r_offset < hend)
13159       {
13160         /* If the entry is in use, do nothing.  */
13161         if (h->vtable->used
13162             && (rel->r_offset - hstart) < h->vtable->size)
13163           {
13164             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13165             if (h->vtable->used[entry])
13166               continue;
13167           }
13168         /* Otherwise, kill it.  */
13169         rel->r_offset = rel->r_info = rel->r_addend = 0;
13170       }
13171
13172   return TRUE;
13173 }
13174
13175 /* Mark sections containing dynamically referenced symbols.  When
13176    building shared libraries, we must assume that any visible symbol is
13177    referenced.  */
13178
13179 bfd_boolean
13180 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13181 {
13182   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13183   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13184
13185   if ((h->root.type == bfd_link_hash_defined
13186        || h->root.type == bfd_link_hash_defweak)
13187       && (h->ref_dynamic
13188           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13189               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13190               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13191               && (!bfd_link_executable (info)
13192                   || info->gc_keep_exported
13193                   || info->export_dynamic
13194                   || (h->dynamic
13195                       && d != NULL
13196                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13197               && (h->versioned >= versioned
13198                   || !bfd_hide_sym_by_version (info->version_info,
13199                                                h->root.root.string)))))
13200     h->root.u.def.section->flags |= SEC_KEEP;
13201
13202   return TRUE;
13203 }
13204
13205 /* Keep all sections containing symbols undefined on the command-line,
13206    and the section containing the entry symbol.  */
13207
13208 void
13209 _bfd_elf_gc_keep (struct bfd_link_info *info)
13210 {
13211   struct bfd_sym_chain *sym;
13212
13213   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13214     {
13215       struct elf_link_hash_entry *h;
13216
13217       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13218                                 FALSE, FALSE, FALSE);
13219
13220       if (h != NULL
13221           && (h->root.type == bfd_link_hash_defined
13222               || h->root.type == bfd_link_hash_defweak)
13223           && !bfd_is_abs_section (h->root.u.def.section)
13224           && !bfd_is_und_section (h->root.u.def.section))
13225         h->root.u.def.section->flags |= SEC_KEEP;
13226     }
13227 }
13228
13229 bfd_boolean
13230 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13231                                 struct bfd_link_info *info)
13232 {
13233   bfd *ibfd = info->input_bfds;
13234
13235   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13236     {
13237       asection *sec;
13238       struct elf_reloc_cookie cookie;
13239
13240       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13241         continue;
13242
13243       if (!init_reloc_cookie (&cookie, info, ibfd))
13244         return FALSE;
13245
13246       for (sec = ibfd->sections; sec; sec = sec->next)
13247         {
13248           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13249               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13250             {
13251               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13252               fini_reloc_cookie_rels (&cookie, sec);
13253             }
13254         }
13255     }
13256   return TRUE;
13257 }
13258
13259 /* Do mark and sweep of unused sections.  */
13260
13261 bfd_boolean
13262 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13263 {
13264   bfd_boolean ok = TRUE;
13265   bfd *sub;
13266   elf_gc_mark_hook_fn gc_mark_hook;
13267   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13268   struct elf_link_hash_table *htab;
13269
13270   if (!bed->can_gc_sections
13271       || !is_elf_hash_table (info->hash))
13272     {
13273       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13274       return TRUE;
13275     }
13276
13277   bed->gc_keep (info);
13278   htab = elf_hash_table (info);
13279
13280   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13281      at the .eh_frame section if we can mark the FDEs individually.  */
13282   for (sub = info->input_bfds;
13283        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13284        sub = sub->link.next)
13285     {
13286       asection *sec;
13287       struct elf_reloc_cookie cookie;
13288
13289       sec = bfd_get_section_by_name (sub, ".eh_frame");
13290       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13291         {
13292           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13293           if (elf_section_data (sec)->sec_info
13294               && (sec->flags & SEC_LINKER_CREATED) == 0)
13295             elf_eh_frame_section (sub) = sec;
13296           fini_reloc_cookie_for_section (&cookie, sec);
13297           sec = bfd_get_next_section_by_name (NULL, sec);
13298         }
13299     }
13300
13301   /* Apply transitive closure to the vtable entry usage info.  */
13302   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13303   if (!ok)
13304     return FALSE;
13305
13306   /* Kill the vtable relocations that were not used.  */
13307   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13308   if (!ok)
13309     return FALSE;
13310
13311   /* Mark dynamically referenced symbols.  */
13312   if (htab->dynamic_sections_created || info->gc_keep_exported)
13313     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13314
13315   /* Grovel through relocs to find out who stays ...  */
13316   gc_mark_hook = bed->gc_mark_hook;
13317   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13318     {
13319       asection *o;
13320
13321       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13322           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13323         continue;
13324
13325       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13326          Also treat note sections as a root, if the section is not part
13327          of a group.  */
13328       for (o = sub->sections; o != NULL; o = o->next)
13329         if (!o->gc_mark
13330             && (o->flags & SEC_EXCLUDE) == 0
13331             && ((o->flags & SEC_KEEP) != 0
13332                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13333                     && elf_next_in_group (o) == NULL )))
13334           {
13335             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13336               return FALSE;
13337           }
13338     }
13339
13340   /* Allow the backend to mark additional target specific sections.  */
13341   bed->gc_mark_extra_sections (info, gc_mark_hook);
13342
13343   /* ... and mark SEC_EXCLUDE for those that go.  */
13344   return elf_gc_sweep (abfd, info);
13345 }
13346 \f
13347 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13348
13349 bfd_boolean
13350 bfd_elf_gc_record_vtinherit (bfd *abfd,
13351                              asection *sec,
13352                              struct elf_link_hash_entry *h,
13353                              bfd_vma offset)
13354 {
13355   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13356   struct elf_link_hash_entry **search, *child;
13357   size_t extsymcount;
13358   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13359
13360   /* The sh_info field of the symtab header tells us where the
13361      external symbols start.  We don't care about the local symbols at
13362      this point.  */
13363   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13364   if (!elf_bad_symtab (abfd))
13365     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13366
13367   sym_hashes = elf_sym_hashes (abfd);
13368   sym_hashes_end = sym_hashes + extsymcount;
13369
13370   /* Hunt down the child symbol, which is in this section at the same
13371      offset as the relocation.  */
13372   for (search = sym_hashes; search != sym_hashes_end; ++search)
13373     {
13374       if ((child = *search) != NULL
13375           && (child->root.type == bfd_link_hash_defined
13376               || child->root.type == bfd_link_hash_defweak)
13377           && child->root.u.def.section == sec
13378           && child->root.u.def.value == offset)
13379         goto win;
13380     }
13381
13382   /* xgettext:c-format */
13383   _bfd_error_handler (_("%B: %A+%lu: No symbol found for INHERIT"),
13384                       abfd, sec, (unsigned long) offset);
13385   bfd_set_error (bfd_error_invalid_operation);
13386   return FALSE;
13387
13388  win:
13389   if (!child->vtable)
13390     {
13391       child->vtable = ((struct elf_link_virtual_table_entry *)
13392                        bfd_zalloc (abfd, sizeof (*child->vtable)));
13393       if (!child->vtable)
13394         return FALSE;
13395     }
13396   if (!h)
13397     {
13398       /* This *should* only be the absolute section.  It could potentially
13399          be that someone has defined a non-global vtable though, which
13400          would be bad.  It isn't worth paging in the local symbols to be
13401          sure though; that case should simply be handled by the assembler.  */
13402
13403       child->vtable->parent = (struct elf_link_hash_entry *) -1;
13404     }
13405   else
13406     child->vtable->parent = h;
13407
13408   return TRUE;
13409 }
13410
13411 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13412
13413 bfd_boolean
13414 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13415                            asection *sec ATTRIBUTE_UNUSED,
13416                            struct elf_link_hash_entry *h,
13417                            bfd_vma addend)
13418 {
13419   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13420   unsigned int log_file_align = bed->s->log_file_align;
13421
13422   if (!h->vtable)
13423     {
13424       h->vtable = ((struct elf_link_virtual_table_entry *)
13425                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13426       if (!h->vtable)
13427         return FALSE;
13428     }
13429
13430   if (addend >= h->vtable->size)
13431     {
13432       size_t size, bytes, file_align;
13433       bfd_boolean *ptr = h->vtable->used;
13434
13435       /* While the symbol is undefined, we have to be prepared to handle
13436          a zero size.  */
13437       file_align = 1 << log_file_align;
13438       if (h->root.type == bfd_link_hash_undefined)
13439         size = addend + file_align;
13440       else
13441         {
13442           size = h->size;
13443           if (addend >= size)
13444             {
13445               /* Oops!  We've got a reference past the defined end of
13446                  the table.  This is probably a bug -- shall we warn?  */
13447               size = addend + file_align;
13448             }
13449         }
13450       size = (size + file_align - 1) & -file_align;
13451
13452       /* Allocate one extra entry for use as a "done" flag for the
13453          consolidation pass.  */
13454       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13455
13456       if (ptr)
13457         {
13458           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13459
13460           if (ptr != NULL)
13461             {
13462               size_t oldbytes;
13463
13464               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13465                           * sizeof (bfd_boolean));
13466               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13467             }
13468         }
13469       else
13470         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13471
13472       if (ptr == NULL)
13473         return FALSE;
13474
13475       /* And arrange for that done flag to be at index -1.  */
13476       h->vtable->used = ptr + 1;
13477       h->vtable->size = size;
13478     }
13479
13480   h->vtable->used[addend >> log_file_align] = TRUE;
13481
13482   return TRUE;
13483 }
13484
13485 /* Map an ELF section header flag to its corresponding string.  */
13486 typedef struct
13487 {
13488   char *flag_name;
13489   flagword flag_value;
13490 } elf_flags_to_name_table;
13491
13492 static elf_flags_to_name_table elf_flags_to_names [] =
13493 {
13494   { "SHF_WRITE", SHF_WRITE },
13495   { "SHF_ALLOC", SHF_ALLOC },
13496   { "SHF_EXECINSTR", SHF_EXECINSTR },
13497   { "SHF_MERGE", SHF_MERGE },
13498   { "SHF_STRINGS", SHF_STRINGS },
13499   { "SHF_INFO_LINK", SHF_INFO_LINK},
13500   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13501   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13502   { "SHF_GROUP", SHF_GROUP },
13503   { "SHF_TLS", SHF_TLS },
13504   { "SHF_MASKOS", SHF_MASKOS },
13505   { "SHF_EXCLUDE", SHF_EXCLUDE },
13506 };
13507
13508 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13509 bfd_boolean
13510 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13511                               struct flag_info *flaginfo,
13512                               asection *section)
13513 {
13514   const bfd_vma sh_flags = elf_section_flags (section);
13515
13516   if (!flaginfo->flags_initialized)
13517     {
13518       bfd *obfd = info->output_bfd;
13519       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13520       struct flag_info_list *tf = flaginfo->flag_list;
13521       int with_hex = 0;
13522       int without_hex = 0;
13523
13524       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13525         {
13526           unsigned i;
13527           flagword (*lookup) (char *);
13528
13529           lookup = bed->elf_backend_lookup_section_flags_hook;
13530           if (lookup != NULL)
13531             {
13532               flagword hexval = (*lookup) ((char *) tf->name);
13533
13534               if (hexval != 0)
13535                 {
13536                   if (tf->with == with_flags)
13537                     with_hex |= hexval;
13538                   else if (tf->with == without_flags)
13539                     without_hex |= hexval;
13540                   tf->valid = TRUE;
13541                   continue;
13542                 }
13543             }
13544           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13545             {
13546               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13547                 {
13548                   if (tf->with == with_flags)
13549                     with_hex |= elf_flags_to_names[i].flag_value;
13550                   else if (tf->with == without_flags)
13551                     without_hex |= elf_flags_to_names[i].flag_value;
13552                   tf->valid = TRUE;
13553                   break;
13554                 }
13555             }
13556           if (!tf->valid)
13557             {
13558               info->callbacks->einfo
13559                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13560               return FALSE;
13561             }
13562         }
13563       flaginfo->flags_initialized = TRUE;
13564       flaginfo->only_with_flags |= with_hex;
13565       flaginfo->not_with_flags |= without_hex;
13566     }
13567
13568   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13569     return FALSE;
13570
13571   if ((flaginfo->not_with_flags & sh_flags) != 0)
13572     return FALSE;
13573
13574   return TRUE;
13575 }
13576
13577 struct alloc_got_off_arg {
13578   bfd_vma gotoff;
13579   struct bfd_link_info *info;
13580 };
13581
13582 /* We need a special top-level link routine to convert got reference counts
13583    to real got offsets.  */
13584
13585 static bfd_boolean
13586 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13587 {
13588   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13589   bfd *obfd = gofarg->info->output_bfd;
13590   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13591
13592   if (h->got.refcount > 0)
13593     {
13594       h->got.offset = gofarg->gotoff;
13595       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13596     }
13597   else
13598     h->got.offset = (bfd_vma) -1;
13599
13600   return TRUE;
13601 }
13602
13603 /* And an accompanying bit to work out final got entry offsets once
13604    we're done.  Should be called from final_link.  */
13605
13606 bfd_boolean
13607 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13608                                         struct bfd_link_info *info)
13609 {
13610   bfd *i;
13611   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13612   bfd_vma gotoff;
13613   struct alloc_got_off_arg gofarg;
13614
13615   BFD_ASSERT (abfd == info->output_bfd);
13616
13617   if (! is_elf_hash_table (info->hash))
13618     return FALSE;
13619
13620   /* The GOT offset is relative to the .got section, but the GOT header is
13621      put into the .got.plt section, if the backend uses it.  */
13622   if (bed->want_got_plt)
13623     gotoff = 0;
13624   else
13625     gotoff = bed->got_header_size;
13626
13627   /* Do the local .got entries first.  */
13628   for (i = info->input_bfds; i; i = i->link.next)
13629     {
13630       bfd_signed_vma *local_got;
13631       size_t j, locsymcount;
13632       Elf_Internal_Shdr *symtab_hdr;
13633
13634       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13635         continue;
13636
13637       local_got = elf_local_got_refcounts (i);
13638       if (!local_got)
13639         continue;
13640
13641       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13642       if (elf_bad_symtab (i))
13643         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13644       else
13645         locsymcount = symtab_hdr->sh_info;
13646
13647       for (j = 0; j < locsymcount; ++j)
13648         {
13649           if (local_got[j] > 0)
13650             {
13651               local_got[j] = gotoff;
13652               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13653             }
13654           else
13655             local_got[j] = (bfd_vma) -1;
13656         }
13657     }
13658
13659   /* Then the global .got entries.  .plt refcounts are handled by
13660      adjust_dynamic_symbol  */
13661   gofarg.gotoff = gotoff;
13662   gofarg.info = info;
13663   elf_link_hash_traverse (elf_hash_table (info),
13664                           elf_gc_allocate_got_offsets,
13665                           &gofarg);
13666   return TRUE;
13667 }
13668
13669 /* Many folk need no more in the way of final link than this, once
13670    got entry reference counting is enabled.  */
13671
13672 bfd_boolean
13673 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13674 {
13675   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13676     return FALSE;
13677
13678   /* Invoke the regular ELF backend linker to do all the work.  */
13679   return bfd_elf_final_link (abfd, info);
13680 }
13681
13682 bfd_boolean
13683 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13684 {
13685   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13686
13687   if (rcookie->bad_symtab)
13688     rcookie->rel = rcookie->rels;
13689
13690   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13691     {
13692       unsigned long r_symndx;
13693
13694       if (! rcookie->bad_symtab)
13695         if (rcookie->rel->r_offset > offset)
13696           return FALSE;
13697       if (rcookie->rel->r_offset != offset)
13698         continue;
13699
13700       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13701       if (r_symndx == STN_UNDEF)
13702         return TRUE;
13703
13704       if (r_symndx >= rcookie->locsymcount
13705           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13706         {
13707           struct elf_link_hash_entry *h;
13708
13709           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13710
13711           while (h->root.type == bfd_link_hash_indirect
13712                  || h->root.type == bfd_link_hash_warning)
13713             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13714
13715           if ((h->root.type == bfd_link_hash_defined
13716                || h->root.type == bfd_link_hash_defweak)
13717               && (h->root.u.def.section->owner != rcookie->abfd
13718                   || h->root.u.def.section->kept_section != NULL
13719                   || discarded_section (h->root.u.def.section)))
13720             return TRUE;
13721         }
13722       else
13723         {
13724           /* It's not a relocation against a global symbol,
13725              but it could be a relocation against a local
13726              symbol for a discarded section.  */
13727           asection *isec;
13728           Elf_Internal_Sym *isym;
13729
13730           /* Need to: get the symbol; get the section.  */
13731           isym = &rcookie->locsyms[r_symndx];
13732           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13733           if (isec != NULL
13734               && (isec->kept_section != NULL
13735                   || discarded_section (isec)))
13736             return TRUE;
13737         }
13738       return FALSE;
13739     }
13740   return FALSE;
13741 }
13742
13743 /* Discard unneeded references to discarded sections.
13744    Returns -1 on error, 1 if any section's size was changed, 0 if
13745    nothing changed.  This function assumes that the relocations are in
13746    sorted order, which is true for all known assemblers.  */
13747
13748 int
13749 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13750 {
13751   struct elf_reloc_cookie cookie;
13752   asection *o;
13753   bfd *abfd;
13754   int changed = 0;
13755
13756   if (info->traditional_format
13757       || !is_elf_hash_table (info->hash))
13758     return 0;
13759
13760   o = bfd_get_section_by_name (output_bfd, ".stab");
13761   if (o != NULL)
13762     {
13763       asection *i;
13764
13765       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13766         {
13767           if (i->size == 0
13768               || i->reloc_count == 0
13769               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13770             continue;
13771
13772           abfd = i->owner;
13773           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13774             continue;
13775
13776           if (!init_reloc_cookie_for_section (&cookie, info, i))
13777             return -1;
13778
13779           if (_bfd_discard_section_stabs (abfd, i,
13780                                           elf_section_data (i)->sec_info,
13781                                           bfd_elf_reloc_symbol_deleted_p,
13782                                           &cookie))
13783             changed = 1;
13784
13785           fini_reloc_cookie_for_section (&cookie, i);
13786         }
13787     }
13788
13789   o = NULL;
13790   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13791     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13792   if (o != NULL)
13793     {
13794       asection *i;
13795
13796       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13797         {
13798           if (i->size == 0)
13799             continue;
13800
13801           abfd = i->owner;
13802           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13803             continue;
13804
13805           if (!init_reloc_cookie_for_section (&cookie, info, i))
13806             return -1;
13807
13808           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13809           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13810                                                  bfd_elf_reloc_symbol_deleted_p,
13811                                                  &cookie))
13812             changed = 1;
13813
13814           fini_reloc_cookie_for_section (&cookie, i);
13815         }
13816     }
13817
13818   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13819     {
13820       const struct elf_backend_data *bed;
13821
13822       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13823         continue;
13824
13825       bed = get_elf_backend_data (abfd);
13826
13827       if (bed->elf_backend_discard_info != NULL)
13828         {
13829           if (!init_reloc_cookie (&cookie, info, abfd))
13830             return -1;
13831
13832           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13833             changed = 1;
13834
13835           fini_reloc_cookie (&cookie, abfd);
13836         }
13837     }
13838
13839   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13840     _bfd_elf_end_eh_frame_parsing (info);
13841
13842   if (info->eh_frame_hdr_type
13843       && !bfd_link_relocatable (info)
13844       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13845     changed = 1;
13846
13847   return changed;
13848 }
13849
13850 bfd_boolean
13851 _bfd_elf_section_already_linked (bfd *abfd,
13852                                  asection *sec,
13853                                  struct bfd_link_info *info)
13854 {
13855   flagword flags;
13856   const char *name, *key;
13857   struct bfd_section_already_linked *l;
13858   struct bfd_section_already_linked_hash_entry *already_linked_list;
13859
13860   if (sec->output_section == bfd_abs_section_ptr)
13861     return FALSE;
13862
13863   flags = sec->flags;
13864
13865   /* Return if it isn't a linkonce section.  A comdat group section
13866      also has SEC_LINK_ONCE set.  */
13867   if ((flags & SEC_LINK_ONCE) == 0)
13868     return FALSE;
13869
13870   /* Don't put group member sections on our list of already linked
13871      sections.  They are handled as a group via their group section.  */
13872   if (elf_sec_group (sec) != NULL)
13873     return FALSE;
13874
13875   /* For a SHT_GROUP section, use the group signature as the key.  */
13876   name = sec->name;
13877   if ((flags & SEC_GROUP) != 0
13878       && elf_next_in_group (sec) != NULL
13879       && elf_group_name (elf_next_in_group (sec)) != NULL)
13880     key = elf_group_name (elf_next_in_group (sec));
13881   else
13882     {
13883       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13884       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13885           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13886         key++;
13887       else
13888         /* Must be a user linkonce section that doesn't follow gcc's
13889            naming convention.  In this case we won't be matching
13890            single member groups.  */
13891         key = name;
13892     }
13893
13894   already_linked_list = bfd_section_already_linked_table_lookup (key);
13895
13896   for (l = already_linked_list->entry; l != NULL; l = l->next)
13897     {
13898       /* We may have 2 different types of sections on the list: group
13899          sections with a signature of <key> (<key> is some string),
13900          and linkonce sections named .gnu.linkonce.<type>.<key>.
13901          Match like sections.  LTO plugin sections are an exception.
13902          They are always named .gnu.linkonce.t.<key> and match either
13903          type of section.  */
13904       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13905            && ((flags & SEC_GROUP) != 0
13906                || strcmp (name, l->sec->name) == 0))
13907           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13908         {
13909           /* The section has already been linked.  See if we should
13910              issue a warning.  */
13911           if (!_bfd_handle_already_linked (sec, l, info))
13912             return FALSE;
13913
13914           if (flags & SEC_GROUP)
13915             {
13916               asection *first = elf_next_in_group (sec);
13917               asection *s = first;
13918
13919               while (s != NULL)
13920                 {
13921                   s->output_section = bfd_abs_section_ptr;
13922                   /* Record which group discards it.  */
13923                   s->kept_section = l->sec;
13924                   s = elf_next_in_group (s);
13925                   /* These lists are circular.  */
13926                   if (s == first)
13927                     break;
13928                 }
13929             }
13930
13931           return TRUE;
13932         }
13933     }
13934
13935   /* A single member comdat group section may be discarded by a
13936      linkonce section and vice versa.  */
13937   if ((flags & SEC_GROUP) != 0)
13938     {
13939       asection *first = elf_next_in_group (sec);
13940
13941       if (first != NULL && elf_next_in_group (first) == first)
13942         /* Check this single member group against linkonce sections.  */
13943         for (l = already_linked_list->entry; l != NULL; l = l->next)
13944           if ((l->sec->flags & SEC_GROUP) == 0
13945               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13946             {
13947               first->output_section = bfd_abs_section_ptr;
13948               first->kept_section = l->sec;
13949               sec->output_section = bfd_abs_section_ptr;
13950               break;
13951             }
13952     }
13953   else
13954     /* Check this linkonce section against single member groups.  */
13955     for (l = already_linked_list->entry; l != NULL; l = l->next)
13956       if (l->sec->flags & SEC_GROUP)
13957         {
13958           asection *first = elf_next_in_group (l->sec);
13959
13960           if (first != NULL
13961               && elf_next_in_group (first) == first
13962               && bfd_elf_match_symbols_in_sections (first, sec, info))
13963             {
13964               sec->output_section = bfd_abs_section_ptr;
13965               sec->kept_section = first;
13966               break;
13967             }
13968         }
13969
13970   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13971      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13972      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13973      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13974      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13975      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13976      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13977      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13978      The reverse order cannot happen as there is never a bfd with only the
13979      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13980      matter as here were are looking only for cross-bfd sections.  */
13981
13982   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13983     for (l = already_linked_list->entry; l != NULL; l = l->next)
13984       if ((l->sec->flags & SEC_GROUP) == 0
13985           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13986         {
13987           if (abfd != l->sec->owner)
13988             sec->output_section = bfd_abs_section_ptr;
13989           break;
13990         }
13991
13992   /* This is the first section with this name.  Record it.  */
13993   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13994     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13995   return sec->output_section == bfd_abs_section_ptr;
13996 }
13997
13998 bfd_boolean
13999 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14000 {
14001   return sym->st_shndx == SHN_COMMON;
14002 }
14003
14004 unsigned int
14005 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14006 {
14007   return SHN_COMMON;
14008 }
14009
14010 asection *
14011 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14012 {
14013   return bfd_com_section_ptr;
14014 }
14015
14016 bfd_vma
14017 _bfd_elf_default_got_elt_size (bfd *abfd,
14018                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14019                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14020                                bfd *ibfd ATTRIBUTE_UNUSED,
14021                                unsigned long symndx ATTRIBUTE_UNUSED)
14022 {
14023   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14024   return bed->s->arch_size / 8;
14025 }
14026
14027 /* Routines to support the creation of dynamic relocs.  */
14028
14029 /* Returns the name of the dynamic reloc section associated with SEC.  */
14030
14031 static const char *
14032 get_dynamic_reloc_section_name (bfd *       abfd,
14033                                 asection *  sec,
14034                                 bfd_boolean is_rela)
14035 {
14036   char *name;
14037   const char *old_name = bfd_get_section_name (NULL, sec);
14038   const char *prefix = is_rela ? ".rela" : ".rel";
14039
14040   if (old_name == NULL)
14041     return NULL;
14042
14043   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14044   sprintf (name, "%s%s", prefix, old_name);
14045
14046   return name;
14047 }
14048
14049 /* Returns the dynamic reloc section associated with SEC.
14050    If necessary compute the name of the dynamic reloc section based
14051    on SEC's name (looked up in ABFD's string table) and the setting
14052    of IS_RELA.  */
14053
14054 asection *
14055 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14056                                     asection *  sec,
14057                                     bfd_boolean is_rela)
14058 {
14059   asection * reloc_sec = elf_section_data (sec)->sreloc;
14060
14061   if (reloc_sec == NULL)
14062     {
14063       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14064
14065       if (name != NULL)
14066         {
14067           reloc_sec = bfd_get_linker_section (abfd, name);
14068
14069           if (reloc_sec != NULL)
14070             elf_section_data (sec)->sreloc = reloc_sec;
14071         }
14072     }
14073
14074   return reloc_sec;
14075 }
14076
14077 /* Returns the dynamic reloc section associated with SEC.  If the
14078    section does not exist it is created and attached to the DYNOBJ
14079    bfd and stored in the SRELOC field of SEC's elf_section_data
14080    structure.
14081
14082    ALIGNMENT is the alignment for the newly created section and
14083    IS_RELA defines whether the name should be .rela.<SEC's name>
14084    or .rel.<SEC's name>.  The section name is looked up in the
14085    string table associated with ABFD.  */
14086
14087 asection *
14088 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14089                                      bfd *dynobj,
14090                                      unsigned int alignment,
14091                                      bfd *abfd,
14092                                      bfd_boolean is_rela)
14093 {
14094   asection * reloc_sec = elf_section_data (sec)->sreloc;
14095
14096   if (reloc_sec == NULL)
14097     {
14098       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14099
14100       if (name == NULL)
14101         return NULL;
14102
14103       reloc_sec = bfd_get_linker_section (dynobj, name);
14104
14105       if (reloc_sec == NULL)
14106         {
14107           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14108                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14109           if ((sec->flags & SEC_ALLOC) != 0)
14110             flags |= SEC_ALLOC | SEC_LOAD;
14111
14112           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14113           if (reloc_sec != NULL)
14114             {
14115               /* _bfd_elf_get_sec_type_attr chooses a section type by
14116                  name.  Override as it may be wrong, eg. for a user
14117                  section named "auto" we'll get ".relauto" which is
14118                  seen to be a .rela section.  */
14119               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14120               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14121                 reloc_sec = NULL;
14122             }
14123         }
14124
14125       elf_section_data (sec)->sreloc = reloc_sec;
14126     }
14127
14128   return reloc_sec;
14129 }
14130
14131 /* Copy the ELF symbol type and other attributes for a linker script
14132    assignment from HSRC to HDEST.  Generally this should be treated as
14133    if we found a strong non-dynamic definition for HDEST (except that
14134    ld ignores multiple definition errors).  */
14135 void
14136 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14137                                      struct bfd_link_hash_entry *hdest,
14138                                      struct bfd_link_hash_entry *hsrc)
14139 {
14140   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14141   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14142   Elf_Internal_Sym isym;
14143
14144   ehdest->type = ehsrc->type;
14145   ehdest->target_internal = ehsrc->target_internal;
14146
14147   isym.st_other = ehsrc->other;
14148   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14149 }
14150
14151 /* Append a RELA relocation REL to section S in BFD.  */
14152
14153 void
14154 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14155 {
14156   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14157   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14158   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14159   bed->s->swap_reloca_out (abfd, rel, loc);
14160 }
14161
14162 /* Append a REL relocation REL to section S in BFD.  */
14163
14164 void
14165 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14166 {
14167   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14168   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14169   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14170   bed->s->swap_reloc_out (abfd, rel, loc);
14171 }