Properly implement STT_COMMON
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2016 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
32 /* This struct is used to pass information to routines called via
33    elf_link_hash_traverse which must return failure.  */
34
35 struct elf_info_failed
36 {
37   struct bfd_link_info *info;
38   bfd_boolean failed;
39 };
40
41 /* This structure is used to pass information to
42    _bfd_elf_link_find_version_dependencies.  */
43
44 struct elf_find_verdep_info
45 {
46   /* General link information.  */
47   struct bfd_link_info *info;
48   /* The number of dependencies.  */
49   unsigned int vers;
50   /* Whether we had a failure.  */
51   bfd_boolean failed;
52 };
53
54 static bfd_boolean _bfd_elf_fix_symbol_flags
55   (struct elf_link_hash_entry *, struct elf_info_failed *);
56
57 asection *
58 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
59                              unsigned long r_symndx,
60                              bfd_boolean discard)
61 {
62   if (r_symndx >= cookie->locsymcount
63       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
64     {
65       struct elf_link_hash_entry *h;
66
67       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
68
69       while (h->root.type == bfd_link_hash_indirect
70              || h->root.type == bfd_link_hash_warning)
71         h = (struct elf_link_hash_entry *) h->root.u.i.link;
72
73       if ((h->root.type == bfd_link_hash_defined
74            || h->root.type == bfd_link_hash_defweak)
75            && discarded_section (h->root.u.def.section))
76         return h->root.u.def.section;
77       else
78         return NULL;
79     }
80   else
81     {
82       /* It's not a relocation against a global symbol,
83          but it could be a relocation against a local
84          symbol for a discarded section.  */
85       asection *isec;
86       Elf_Internal_Sym *isym;
87
88       /* Need to: get the symbol; get the section.  */
89       isym = &cookie->locsyms[r_symndx];
90       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
91       if (isec != NULL
92           && discard ? discarded_section (isec) : 1)
93         return isec;
94      }
95   return NULL;
96 }
97
98 /* Define a symbol in a dynamic linkage section.  */
99
100 struct elf_link_hash_entry *
101 _bfd_elf_define_linkage_sym (bfd *abfd,
102                              struct bfd_link_info *info,
103                              asection *sec,
104                              const char *name)
105 {
106   struct elf_link_hash_entry *h;
107   struct bfd_link_hash_entry *bh;
108   const struct elf_backend_data *bed;
109
110   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
111   if (h != NULL)
112     {
113       /* Zap symbol defined in an as-needed lib that wasn't linked.
114          This is a symptom of a larger problem:  Absolute symbols
115          defined in shared libraries can't be overridden, because we
116          lose the link to the bfd which is via the symbol section.  */
117       h->root.type = bfd_link_hash_new;
118     }
119
120   bh = &h->root;
121   bed = get_elf_backend_data (abfd);
122   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
123                                          sec, 0, NULL, FALSE, bed->collect,
124                                          &bh))
125     return NULL;
126   h = (struct elf_link_hash_entry *) bh;
127   h->def_regular = 1;
128   h->non_elf = 0;
129   h->root.linker_def = 1;
130   h->type = STT_OBJECT;
131   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
132     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
133
134   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
135   return h;
136 }
137
138 bfd_boolean
139 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
140 {
141   flagword flags;
142   asection *s;
143   struct elf_link_hash_entry *h;
144   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
145   struct elf_link_hash_table *htab = elf_hash_table (info);
146
147   /* This function may be called more than once.  */
148   s = bfd_get_linker_section (abfd, ".got");
149   if (s != NULL)
150     return TRUE;
151
152   flags = bed->dynamic_sec_flags;
153
154   s = bfd_make_section_anyway_with_flags (abfd,
155                                           (bed->rela_plts_and_copies_p
156                                            ? ".rela.got" : ".rel.got"),
157                                           (bed->dynamic_sec_flags
158                                            | SEC_READONLY));
159   if (s == NULL
160       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
161     return FALSE;
162   htab->srelgot = s;
163
164   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
165   if (s == NULL
166       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->sgot = s;
169
170   if (bed->want_got_plt)
171     {
172       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
173       if (s == NULL
174           || !bfd_set_section_alignment (abfd, s,
175                                          bed->s->log_file_align))
176         return FALSE;
177       htab->sgotplt = s;
178     }
179
180   /* The first bit of the global offset table is the header.  */
181   s->size += bed->got_header_size;
182
183   if (bed->want_got_sym)
184     {
185       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
186          (or .got.plt) section.  We don't do this in the linker script
187          because we don't want to define the symbol if we are not creating
188          a global offset table.  */
189       h = _bfd_elf_define_linkage_sym (abfd, info, s,
190                                        "_GLOBAL_OFFSET_TABLE_");
191       elf_hash_table (info)->hgot = h;
192       if (h == NULL)
193         return FALSE;
194     }
195
196   return TRUE;
197 }
198 \f
199 /* Create a strtab to hold the dynamic symbol names.  */
200 static bfd_boolean
201 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
202 {
203   struct elf_link_hash_table *hash_table;
204
205   hash_table = elf_hash_table (info);
206   if (hash_table->dynobj == NULL)
207     hash_table->dynobj = abfd;
208
209   if (hash_table->dynstr == NULL)
210     {
211       hash_table->dynstr = _bfd_elf_strtab_init ();
212       if (hash_table->dynstr == NULL)
213         return FALSE;
214     }
215   return TRUE;
216 }
217
218 /* Create some sections which will be filled in with dynamic linking
219    information.  ABFD is an input file which requires dynamic sections
220    to be created.  The dynamic sections take up virtual memory space
221    when the final executable is run, so we need to create them before
222    addresses are assigned to the output sections.  We work out the
223    actual contents and size of these sections later.  */
224
225 bfd_boolean
226 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
227 {
228   flagword flags;
229   asection *s;
230   const struct elf_backend_data *bed;
231   struct elf_link_hash_entry *h;
232
233   if (! is_elf_hash_table (info->hash))
234     return FALSE;
235
236   if (elf_hash_table (info)->dynamic_sections_created)
237     return TRUE;
238
239   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
240     return FALSE;
241
242   abfd = elf_hash_table (info)->dynobj;
243   bed = get_elf_backend_data (abfd);
244
245   flags = bed->dynamic_sec_flags;
246
247   /* A dynamically linked executable has a .interp section, but a
248      shared library does not.  */
249   if (bfd_link_executable (info) && !info->nointerp)
250     {
251       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
252                                               flags | SEC_READONLY);
253       if (s == NULL)
254         return FALSE;
255     }
256
257   /* Create sections to hold version informations.  These are removed
258      if they are not needed.  */
259   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
260                                           flags | SEC_READONLY);
261   if (s == NULL
262       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
263     return FALSE;
264
265   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
266                                           flags | SEC_READONLY);
267   if (s == NULL
268       || ! bfd_set_section_alignment (abfd, s, 1))
269     return FALSE;
270
271   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
272                                           flags | SEC_READONLY);
273   if (s == NULL
274       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
275     return FALSE;
276
277   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
278                                           flags | SEC_READONLY);
279   if (s == NULL
280       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
281     return FALSE;
282   elf_hash_table (info)->dynsym = s;
283
284   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
285                                           flags | SEC_READONLY);
286   if (s == NULL)
287     return FALSE;
288
289   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
290   if (s == NULL
291       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
292     return FALSE;
293
294   /* The special symbol _DYNAMIC is always set to the start of the
295      .dynamic section.  We could set _DYNAMIC in a linker script, but we
296      only want to define it if we are, in fact, creating a .dynamic
297      section.  We don't want to define it if there is no .dynamic
298      section, since on some ELF platforms the start up code examines it
299      to decide how to initialize the process.  */
300   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
301   elf_hash_table (info)->hdynamic = h;
302   if (h == NULL)
303     return FALSE;
304
305   if (info->emit_hash)
306     {
307       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
308                                               flags | SEC_READONLY);
309       if (s == NULL
310           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
311         return FALSE;
312       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
313     }
314
315   if (info->emit_gnu_hash)
316     {
317       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
318                                               flags | SEC_READONLY);
319       if (s == NULL
320           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
321         return FALSE;
322       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
323          4 32-bit words followed by variable count of 64-bit words, then
324          variable count of 32-bit words.  */
325       if (bed->s->arch_size == 64)
326         elf_section_data (s)->this_hdr.sh_entsize = 0;
327       else
328         elf_section_data (s)->this_hdr.sh_entsize = 4;
329     }
330
331   /* Let the backend create the rest of the sections.  This lets the
332      backend set the right flags.  The backend will normally create
333      the .got and .plt sections.  */
334   if (bed->elf_backend_create_dynamic_sections == NULL
335       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
336     return FALSE;
337
338   elf_hash_table (info)->dynamic_sections_created = TRUE;
339
340   return TRUE;
341 }
342
343 /* Create dynamic sections when linking against a dynamic object.  */
344
345 bfd_boolean
346 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
347 {
348   flagword flags, pltflags;
349   struct elf_link_hash_entry *h;
350   asection *s;
351   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
352   struct elf_link_hash_table *htab = elf_hash_table (info);
353
354   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
355      .rel[a].bss sections.  */
356   flags = bed->dynamic_sec_flags;
357
358   pltflags = flags;
359   if (bed->plt_not_loaded)
360     /* We do not clear SEC_ALLOC here because we still want the OS to
361        allocate space for the section; it's just that there's nothing
362        to read in from the object file.  */
363     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
364   else
365     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
366   if (bed->plt_readonly)
367     pltflags |= SEC_READONLY;
368
369   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
370   if (s == NULL
371       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
372     return FALSE;
373   htab->splt = s;
374
375   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
376      .plt section.  */
377   if (bed->want_plt_sym)
378     {
379       h = _bfd_elf_define_linkage_sym (abfd, info, s,
380                                        "_PROCEDURE_LINKAGE_TABLE_");
381       elf_hash_table (info)->hplt = h;
382       if (h == NULL)
383         return FALSE;
384     }
385
386   s = bfd_make_section_anyway_with_flags (abfd,
387                                           (bed->rela_plts_and_copies_p
388                                            ? ".rela.plt" : ".rel.plt"),
389                                           flags | SEC_READONLY);
390   if (s == NULL
391       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
392     return FALSE;
393   htab->srelplt = s;
394
395   if (! _bfd_elf_create_got_section (abfd, info))
396     return FALSE;
397
398   if (bed->want_dynbss)
399     {
400       /* The .dynbss section is a place to put symbols which are defined
401          by dynamic objects, are referenced by regular objects, and are
402          not functions.  We must allocate space for them in the process
403          image and use a R_*_COPY reloc to tell the dynamic linker to
404          initialize them at run time.  The linker script puts the .dynbss
405          section into the .bss section of the final image.  */
406       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
407                                               (SEC_ALLOC | SEC_LINKER_CREATED));
408       if (s == NULL)
409         return FALSE;
410
411       /* The .rel[a].bss section holds copy relocs.  This section is not
412          normally needed.  We need to create it here, though, so that the
413          linker will map it to an output section.  We can't just create it
414          only if we need it, because we will not know whether we need it
415          until we have seen all the input files, and the first time the
416          main linker code calls BFD after examining all the input files
417          (size_dynamic_sections) the input sections have already been
418          mapped to the output sections.  If the section turns out not to
419          be needed, we can discard it later.  We will never need this
420          section when generating a shared object, since they do not use
421          copy relocs.  */
422       if (! bfd_link_pic (info))
423         {
424           s = bfd_make_section_anyway_with_flags (abfd,
425                                                   (bed->rela_plts_and_copies_p
426                                                    ? ".rela.bss" : ".rel.bss"),
427                                                   flags | SEC_READONLY);
428           if (s == NULL
429               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
430             return FALSE;
431         }
432     }
433
434   return TRUE;
435 }
436 \f
437 /* Record a new dynamic symbol.  We record the dynamic symbols as we
438    read the input files, since we need to have a list of all of them
439    before we can determine the final sizes of the output sections.
440    Note that we may actually call this function even though we are not
441    going to output any dynamic symbols; in some cases we know that a
442    symbol should be in the dynamic symbol table, but only if there is
443    one.  */
444
445 bfd_boolean
446 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
447                                     struct elf_link_hash_entry *h)
448 {
449   if (h->dynindx == -1)
450     {
451       struct elf_strtab_hash *dynstr;
452       char *p;
453       const char *name;
454       bfd_size_type indx;
455
456       /* XXX: The ABI draft says the linker must turn hidden and
457          internal symbols into STB_LOCAL symbols when producing the
458          DSO. However, if ld.so honors st_other in the dynamic table,
459          this would not be necessary.  */
460       switch (ELF_ST_VISIBILITY (h->other))
461         {
462         case STV_INTERNAL:
463         case STV_HIDDEN:
464           if (h->root.type != bfd_link_hash_undefined
465               && h->root.type != bfd_link_hash_undefweak)
466             {
467               h->forced_local = 1;
468               if (!elf_hash_table (info)->is_relocatable_executable)
469                 return TRUE;
470             }
471
472         default:
473           break;
474         }
475
476       h->dynindx = elf_hash_table (info)->dynsymcount;
477       ++elf_hash_table (info)->dynsymcount;
478
479       dynstr = elf_hash_table (info)->dynstr;
480       if (dynstr == NULL)
481         {
482           /* Create a strtab to hold the dynamic symbol names.  */
483           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
484           if (dynstr == NULL)
485             return FALSE;
486         }
487
488       /* We don't put any version information in the dynamic string
489          table.  */
490       name = h->root.root.string;
491       p = strchr (name, ELF_VER_CHR);
492       if (p != NULL)
493         /* We know that the p points into writable memory.  In fact,
494            there are only a few symbols that have read-only names, being
495            those like _GLOBAL_OFFSET_TABLE_ that are created specially
496            by the backends.  Most symbols will have names pointing into
497            an ELF string table read from a file, or to objalloc memory.  */
498         *p = 0;
499
500       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
501
502       if (p != NULL)
503         *p = ELF_VER_CHR;
504
505       if (indx == (bfd_size_type) -1)
506         return FALSE;
507       h->dynstr_index = indx;
508     }
509
510   return TRUE;
511 }
512 \f
513 /* Mark a symbol dynamic.  */
514
515 static void
516 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
517                                   struct elf_link_hash_entry *h,
518                                   Elf_Internal_Sym *sym)
519 {
520   struct bfd_elf_dynamic_list *d = info->dynamic_list;
521
522   /* It may be called more than once on the same H.  */
523   if(h->dynamic || bfd_link_relocatable (info))
524     return;
525
526   if ((info->dynamic_data
527        && (h->type == STT_OBJECT
528            || h->type == STT_COMMON
529            || (sym != NULL
530                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
531                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
532       || (d != NULL
533           && h->root.type == bfd_link_hash_new
534           && (*d->match) (&d->head, NULL, h->root.root.string)))
535     h->dynamic = 1;
536 }
537
538 /* Record an assignment to a symbol made by a linker script.  We need
539    this in case some dynamic object refers to this symbol.  */
540
541 bfd_boolean
542 bfd_elf_record_link_assignment (bfd *output_bfd,
543                                 struct bfd_link_info *info,
544                                 const char *name,
545                                 bfd_boolean provide,
546                                 bfd_boolean hidden)
547 {
548   struct elf_link_hash_entry *h, *hv;
549   struct elf_link_hash_table *htab;
550   const struct elf_backend_data *bed;
551
552   if (!is_elf_hash_table (info->hash))
553     return TRUE;
554
555   htab = elf_hash_table (info);
556   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
557   if (h == NULL)
558     return provide;
559
560   if (h->versioned == unknown)
561     {
562       /* Set versioned if symbol version is unknown.  */
563       char *version = strrchr (name, ELF_VER_CHR);
564       if (version)
565         {
566           if (version > name && version[-1] != ELF_VER_CHR)
567             h->versioned = versioned_hidden;
568           else
569             h->versioned = versioned;
570         }
571     }
572
573   switch (h->root.type)
574     {
575     case bfd_link_hash_defined:
576     case bfd_link_hash_defweak:
577     case bfd_link_hash_common:
578       break;
579     case bfd_link_hash_undefweak:
580     case bfd_link_hash_undefined:
581       /* Since we're defining the symbol, don't let it seem to have not
582          been defined.  record_dynamic_symbol and size_dynamic_sections
583          may depend on this.  */
584       h->root.type = bfd_link_hash_new;
585       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
586         bfd_link_repair_undef_list (&htab->root);
587       break;
588     case bfd_link_hash_new:
589       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
590       h->non_elf = 0;
591       break;
592     case bfd_link_hash_indirect:
593       /* We had a versioned symbol in a dynamic library.  We make the
594          the versioned symbol point to this one.  */
595       bed = get_elf_backend_data (output_bfd);
596       hv = h;
597       while (hv->root.type == bfd_link_hash_indirect
598              || hv->root.type == bfd_link_hash_warning)
599         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
600       /* We don't need to update h->root.u since linker will set them
601          later.  */
602       h->root.type = bfd_link_hash_undefined;
603       hv->root.type = bfd_link_hash_indirect;
604       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
605       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
606       break;
607     case bfd_link_hash_warning:
608       abort ();
609       break;
610     }
611
612   /* If this symbol is being provided by the linker script, and it is
613      currently defined by a dynamic object, but not by a regular
614      object, then mark it as undefined so that the generic linker will
615      force the correct value.  */
616   if (provide
617       && h->def_dynamic
618       && !h->def_regular)
619     h->root.type = bfd_link_hash_undefined;
620
621   /* If this symbol is not being provided by the linker script, and it is
622      currently defined by a dynamic object, but not by a regular object,
623      then clear out any version information because the symbol will not be
624      associated with the dynamic object any more.  */
625   if (!provide
626       && h->def_dynamic
627       && !h->def_regular)
628     h->verinfo.verdef = NULL;
629
630   h->def_regular = 1;
631
632   if (hidden)
633     {
634       bed = get_elf_backend_data (output_bfd);
635       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
636         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
637       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
638     }
639
640   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
641      and executables.  */
642   if (!bfd_link_relocatable (info)
643       && h->dynindx != -1
644       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
645           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
646     h->forced_local = 1;
647
648   if ((h->def_dynamic
649        || h->ref_dynamic
650        || bfd_link_dll (info)
651        || elf_hash_table (info)->is_relocatable_executable)
652       && h->dynindx == -1)
653     {
654       if (! bfd_elf_link_record_dynamic_symbol (info, h))
655         return FALSE;
656
657       /* If this is a weak defined symbol, and we know a corresponding
658          real symbol from the same dynamic object, make sure the real
659          symbol is also made into a dynamic symbol.  */
660       if (h->u.weakdef != NULL
661           && h->u.weakdef->dynindx == -1)
662         {
663           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
664             return FALSE;
665         }
666     }
667
668   return TRUE;
669 }
670
671 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
672    success, and 2 on a failure caused by attempting to record a symbol
673    in a discarded section, eg. a discarded link-once section symbol.  */
674
675 int
676 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
677                                           bfd *input_bfd,
678                                           long input_indx)
679 {
680   bfd_size_type amt;
681   struct elf_link_local_dynamic_entry *entry;
682   struct elf_link_hash_table *eht;
683   struct elf_strtab_hash *dynstr;
684   unsigned long dynstr_index;
685   char *name;
686   Elf_External_Sym_Shndx eshndx;
687   char esym[sizeof (Elf64_External_Sym)];
688
689   if (! is_elf_hash_table (info->hash))
690     return 0;
691
692   /* See if the entry exists already.  */
693   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
694     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
695       return 1;
696
697   amt = sizeof (*entry);
698   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
699   if (entry == NULL)
700     return 0;
701
702   /* Go find the symbol, so that we can find it's name.  */
703   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
704                              1, input_indx, &entry->isym, esym, &eshndx))
705     {
706       bfd_release (input_bfd, entry);
707       return 0;
708     }
709
710   if (entry->isym.st_shndx != SHN_UNDEF
711       && entry->isym.st_shndx < SHN_LORESERVE)
712     {
713       asection *s;
714
715       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
716       if (s == NULL || bfd_is_abs_section (s->output_section))
717         {
718           /* We can still bfd_release here as nothing has done another
719              bfd_alloc.  We can't do this later in this function.  */
720           bfd_release (input_bfd, entry);
721           return 2;
722         }
723     }
724
725   name = (bfd_elf_string_from_elf_section
726           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
727            entry->isym.st_name));
728
729   dynstr = elf_hash_table (info)->dynstr;
730   if (dynstr == NULL)
731     {
732       /* Create a strtab to hold the dynamic symbol names.  */
733       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
734       if (dynstr == NULL)
735         return 0;
736     }
737
738   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
739   if (dynstr_index == (unsigned long) -1)
740     return 0;
741   entry->isym.st_name = dynstr_index;
742
743   eht = elf_hash_table (info);
744
745   entry->next = eht->dynlocal;
746   eht->dynlocal = entry;
747   entry->input_bfd = input_bfd;
748   entry->input_indx = input_indx;
749   eht->dynsymcount++;
750
751   /* Whatever binding the symbol had before, it's now local.  */
752   entry->isym.st_info
753     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
754
755   /* The dynindx will be set at the end of size_dynamic_sections.  */
756
757   return 1;
758 }
759
760 /* Return the dynindex of a local dynamic symbol.  */
761
762 long
763 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
764                                     bfd *input_bfd,
765                                     long input_indx)
766 {
767   struct elf_link_local_dynamic_entry *e;
768
769   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
770     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
771       return e->dynindx;
772   return -1;
773 }
774
775 /* This function is used to renumber the dynamic symbols, if some of
776    them are removed because they are marked as local.  This is called
777    via elf_link_hash_traverse.  */
778
779 static bfd_boolean
780 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
781                                       void *data)
782 {
783   size_t *count = (size_t *) data;
784
785   if (h->forced_local)
786     return TRUE;
787
788   if (h->dynindx != -1)
789     h->dynindx = ++(*count);
790
791   return TRUE;
792 }
793
794
795 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
796    STB_LOCAL binding.  */
797
798 static bfd_boolean
799 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
800                                             void *data)
801 {
802   size_t *count = (size_t *) data;
803
804   if (!h->forced_local)
805     return TRUE;
806
807   if (h->dynindx != -1)
808     h->dynindx = ++(*count);
809
810   return TRUE;
811 }
812
813 /* Return true if the dynamic symbol for a given section should be
814    omitted when creating a shared library.  */
815 bfd_boolean
816 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
817                                    struct bfd_link_info *info,
818                                    asection *p)
819 {
820   struct elf_link_hash_table *htab;
821   asection *ip;
822
823   switch (elf_section_data (p)->this_hdr.sh_type)
824     {
825     case SHT_PROGBITS:
826     case SHT_NOBITS:
827       /* If sh_type is yet undecided, assume it could be
828          SHT_PROGBITS/SHT_NOBITS.  */
829     case SHT_NULL:
830       htab = elf_hash_table (info);
831       if (p == htab->tls_sec)
832         return FALSE;
833
834       if (htab->text_index_section != NULL)
835         return p != htab->text_index_section && p != htab->data_index_section;
836
837       return (htab->dynobj != NULL
838               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
839               && ip->output_section == p);
840
841       /* There shouldn't be section relative relocations
842          against any other section.  */
843     default:
844       return TRUE;
845     }
846 }
847
848 /* Assign dynsym indices.  In a shared library we generate a section
849    symbol for each output section, which come first.  Next come symbols
850    which have been forced to local binding.  Then all of the back-end
851    allocated local dynamic syms, followed by the rest of the global
852    symbols.  */
853
854 static unsigned long
855 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
856                                 struct bfd_link_info *info,
857                                 unsigned long *section_sym_count)
858 {
859   unsigned long dynsymcount = 0;
860
861   if (bfd_link_pic (info)
862       || elf_hash_table (info)->is_relocatable_executable)
863     {
864       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
865       asection *p;
866       for (p = output_bfd->sections; p ; p = p->next)
867         if ((p->flags & SEC_EXCLUDE) == 0
868             && (p->flags & SEC_ALLOC) != 0
869             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
870           elf_section_data (p)->dynindx = ++dynsymcount;
871         else
872           elf_section_data (p)->dynindx = 0;
873     }
874   *section_sym_count = dynsymcount;
875
876   elf_link_hash_traverse (elf_hash_table (info),
877                           elf_link_renumber_local_hash_table_dynsyms,
878                           &dynsymcount);
879
880   if (elf_hash_table (info)->dynlocal)
881     {
882       struct elf_link_local_dynamic_entry *p;
883       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
884         p->dynindx = ++dynsymcount;
885     }
886
887   elf_link_hash_traverse (elf_hash_table (info),
888                           elf_link_renumber_hash_table_dynsyms,
889                           &dynsymcount);
890
891   /* There is an unused NULL entry at the head of the table which
892      we must account for in our count.  We always create the dynsym
893      section, even if it is empty, with dynamic sections.  */
894   if (elf_hash_table (info)->dynamic_sections_created)
895     ++dynsymcount;
896
897   elf_hash_table (info)->dynsymcount = dynsymcount;
898   return dynsymcount;
899 }
900
901 /* Merge st_other field.  */
902
903 static void
904 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
905                     const Elf_Internal_Sym *isym, asection *sec,
906                     bfd_boolean definition, bfd_boolean dynamic)
907 {
908   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
909
910   /* If st_other has a processor-specific meaning, specific
911      code might be needed here.  */
912   if (bed->elf_backend_merge_symbol_attribute)
913     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
914                                                 dynamic);
915
916   if (!dynamic)
917     {
918       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
919       unsigned hvis = ELF_ST_VISIBILITY (h->other);
920
921       /* Keep the most constraining visibility.  Leave the remainder
922          of the st_other field to elf_backend_merge_symbol_attribute.  */
923       if (symvis - 1 < hvis - 1)
924         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
925     }
926   else if (definition
927            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
928            && (sec->flags & SEC_READONLY) == 0)
929     h->protected_def = 1;
930 }
931
932 /* This function is called when we want to merge a new symbol with an
933    existing symbol.  It handles the various cases which arise when we
934    find a definition in a dynamic object, or when there is already a
935    definition in a dynamic object.  The new symbol is described by
936    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
937    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
938    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
939    of an old common symbol.  We set OVERRIDE if the old symbol is
940    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
941    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
942    to change.  By OK to change, we mean that we shouldn't warn if the
943    type or size does change.  */
944
945 static bfd_boolean
946 _bfd_elf_merge_symbol (bfd *abfd,
947                        struct bfd_link_info *info,
948                        const char *name,
949                        Elf_Internal_Sym *sym,
950                        asection **psec,
951                        bfd_vma *pvalue,
952                        struct elf_link_hash_entry **sym_hash,
953                        bfd **poldbfd,
954                        bfd_boolean *pold_weak,
955                        unsigned int *pold_alignment,
956                        bfd_boolean *skip,
957                        bfd_boolean *override,
958                        bfd_boolean *type_change_ok,
959                        bfd_boolean *size_change_ok,
960                        bfd_boolean *matched)
961 {
962   asection *sec, *oldsec;
963   struct elf_link_hash_entry *h;
964   struct elf_link_hash_entry *hi;
965   struct elf_link_hash_entry *flip;
966   int bind;
967   bfd *oldbfd;
968   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
969   bfd_boolean newweak, oldweak, newfunc, oldfunc;
970   const struct elf_backend_data *bed;
971   char *new_version;
972
973   *skip = FALSE;
974   *override = FALSE;
975
976   sec = *psec;
977   bind = ELF_ST_BIND (sym->st_info);
978
979   if (! bfd_is_und_section (sec))
980     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
981   else
982     h = ((struct elf_link_hash_entry *)
983          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
984   if (h == NULL)
985     return FALSE;
986   *sym_hash = h;
987
988   bed = get_elf_backend_data (abfd);
989
990   /* NEW_VERSION is the symbol version of the new symbol.  */
991   if (h->versioned != unversioned)
992     {
993       /* Symbol version is unknown or versioned.  */
994       new_version = strrchr (name, ELF_VER_CHR);
995       if (new_version)
996         {
997           if (h->versioned == unknown)
998             {
999               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1000                 h->versioned = versioned_hidden;
1001               else
1002                 h->versioned = versioned;
1003             }
1004           new_version += 1;
1005           if (new_version[0] == '\0')
1006             new_version = NULL;
1007         }
1008       else
1009         h->versioned = unversioned;
1010     }
1011   else
1012     new_version = NULL;
1013
1014   /* For merging, we only care about real symbols.  But we need to make
1015      sure that indirect symbol dynamic flags are updated.  */
1016   hi = h;
1017   while (h->root.type == bfd_link_hash_indirect
1018          || h->root.type == bfd_link_hash_warning)
1019     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1020
1021   if (!*matched)
1022     {
1023       if (hi == h || h->root.type == bfd_link_hash_new)
1024         *matched = TRUE;
1025       else
1026         {
1027           /* OLD_HIDDEN is true if the existing symbol is only visible
1028              to the symbol with the same symbol version.  NEW_HIDDEN is
1029              true if the new symbol is only visible to the symbol with
1030              the same symbol version.  */
1031           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1032           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1033           if (!old_hidden && !new_hidden)
1034             /* The new symbol matches the existing symbol if both
1035                aren't hidden.  */
1036             *matched = TRUE;
1037           else
1038             {
1039               /* OLD_VERSION is the symbol version of the existing
1040                  symbol. */
1041               char *old_version;
1042
1043               if (h->versioned >= versioned)
1044                 old_version = strrchr (h->root.root.string,
1045                                        ELF_VER_CHR) + 1;
1046               else
1047                  old_version = NULL;
1048
1049               /* The new symbol matches the existing symbol if they
1050                  have the same symbol version.  */
1051               *matched = (old_version == new_version
1052                           || (old_version != NULL
1053                               && new_version != NULL
1054                               && strcmp (old_version, new_version) == 0));
1055             }
1056         }
1057     }
1058
1059   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1060      existing symbol.  */
1061
1062   oldbfd = NULL;
1063   oldsec = NULL;
1064   switch (h->root.type)
1065     {
1066     default:
1067       break;
1068
1069     case bfd_link_hash_undefined:
1070     case bfd_link_hash_undefweak:
1071       oldbfd = h->root.u.undef.abfd;
1072       break;
1073
1074     case bfd_link_hash_defined:
1075     case bfd_link_hash_defweak:
1076       oldbfd = h->root.u.def.section->owner;
1077       oldsec = h->root.u.def.section;
1078       break;
1079
1080     case bfd_link_hash_common:
1081       oldbfd = h->root.u.c.p->section->owner;
1082       oldsec = h->root.u.c.p->section;
1083       if (pold_alignment)
1084         *pold_alignment = h->root.u.c.p->alignment_power;
1085       break;
1086     }
1087   if (poldbfd && *poldbfd == NULL)
1088     *poldbfd = oldbfd;
1089
1090   /* Differentiate strong and weak symbols.  */
1091   newweak = bind == STB_WEAK;
1092   oldweak = (h->root.type == bfd_link_hash_defweak
1093              || h->root.type == bfd_link_hash_undefweak);
1094   if (pold_weak)
1095     *pold_weak = oldweak;
1096
1097   /* This code is for coping with dynamic objects, and is only useful
1098      if we are doing an ELF link.  */
1099   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1100     return TRUE;
1101
1102   /* We have to check it for every instance since the first few may be
1103      references and not all compilers emit symbol type for undefined
1104      symbols.  */
1105   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1106
1107   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1108      respectively, is from a dynamic object.  */
1109
1110   newdyn = (abfd->flags & DYNAMIC) != 0;
1111
1112   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1113      syms and defined syms in dynamic libraries respectively.
1114      ref_dynamic on the other hand can be set for a symbol defined in
1115      a dynamic library, and def_dynamic may not be set;  When the
1116      definition in a dynamic lib is overridden by a definition in the
1117      executable use of the symbol in the dynamic lib becomes a
1118      reference to the executable symbol.  */
1119   if (newdyn)
1120     {
1121       if (bfd_is_und_section (sec))
1122         {
1123           if (bind != STB_WEAK)
1124             {
1125               h->ref_dynamic_nonweak = 1;
1126               hi->ref_dynamic_nonweak = 1;
1127             }
1128         }
1129       else
1130         {
1131           /* Update the existing symbol only if they match. */
1132           if (*matched)
1133             h->dynamic_def = 1;
1134           hi->dynamic_def = 1;
1135         }
1136     }
1137
1138   /* If we just created the symbol, mark it as being an ELF symbol.
1139      Other than that, there is nothing to do--there is no merge issue
1140      with a newly defined symbol--so we just return.  */
1141
1142   if (h->root.type == bfd_link_hash_new)
1143     {
1144       h->non_elf = 0;
1145       return TRUE;
1146     }
1147
1148   /* In cases involving weak versioned symbols, we may wind up trying
1149      to merge a symbol with itself.  Catch that here, to avoid the
1150      confusion that results if we try to override a symbol with
1151      itself.  The additional tests catch cases like
1152      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1153      dynamic object, which we do want to handle here.  */
1154   if (abfd == oldbfd
1155       && (newweak || oldweak)
1156       && ((abfd->flags & DYNAMIC) == 0
1157           || !h->def_regular))
1158     return TRUE;
1159
1160   olddyn = FALSE;
1161   if (oldbfd != NULL)
1162     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1163   else if (oldsec != NULL)
1164     {
1165       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1166          indices used by MIPS ELF.  */
1167       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1168     }
1169
1170   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1171      respectively, appear to be a definition rather than reference.  */
1172
1173   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1174
1175   olddef = (h->root.type != bfd_link_hash_undefined
1176             && h->root.type != bfd_link_hash_undefweak
1177             && h->root.type != bfd_link_hash_common);
1178
1179   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1180      respectively, appear to be a function.  */
1181
1182   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1183              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1184
1185   oldfunc = (h->type != STT_NOTYPE
1186              && bed->is_function_type (h->type));
1187
1188   /* When we try to create a default indirect symbol from the dynamic
1189      definition with the default version, we skip it if its type and
1190      the type of existing regular definition mismatch.  */
1191   if (pold_alignment == NULL
1192       && newdyn
1193       && newdef
1194       && !olddyn
1195       && (((olddef || h->root.type == bfd_link_hash_common)
1196            && ELF_ST_TYPE (sym->st_info) != h->type
1197            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1198            && h->type != STT_NOTYPE
1199            && !(newfunc && oldfunc))
1200           || (olddef
1201               && ((h->type == STT_GNU_IFUNC)
1202                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1203     {
1204       *skip = TRUE;
1205       return TRUE;
1206     }
1207
1208   /* Check TLS symbols.  We don't check undefined symbols introduced
1209      by "ld -u" which have no type (and oldbfd NULL), and we don't
1210      check symbols from plugins because they also have no type.  */
1211   if (oldbfd != NULL
1212       && (oldbfd->flags & BFD_PLUGIN) == 0
1213       && (abfd->flags & BFD_PLUGIN) == 0
1214       && ELF_ST_TYPE (sym->st_info) != h->type
1215       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1216     {
1217       bfd *ntbfd, *tbfd;
1218       bfd_boolean ntdef, tdef;
1219       asection *ntsec, *tsec;
1220
1221       if (h->type == STT_TLS)
1222         {
1223           ntbfd = abfd;
1224           ntsec = sec;
1225           ntdef = newdef;
1226           tbfd = oldbfd;
1227           tsec = oldsec;
1228           tdef = olddef;
1229         }
1230       else
1231         {
1232           ntbfd = oldbfd;
1233           ntsec = oldsec;
1234           ntdef = olddef;
1235           tbfd = abfd;
1236           tsec = sec;
1237           tdef = newdef;
1238         }
1239
1240       if (tdef && ntdef)
1241         (*_bfd_error_handler)
1242           (_("%s: TLS definition in %B section %A "
1243              "mismatches non-TLS definition in %B section %A"),
1244            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1245       else if (!tdef && !ntdef)
1246         (*_bfd_error_handler)
1247           (_("%s: TLS reference in %B "
1248              "mismatches non-TLS reference in %B"),
1249            tbfd, ntbfd, h->root.root.string);
1250       else if (tdef)
1251         (*_bfd_error_handler)
1252           (_("%s: TLS definition in %B section %A "
1253              "mismatches non-TLS reference in %B"),
1254            tbfd, tsec, ntbfd, h->root.root.string);
1255       else
1256         (*_bfd_error_handler)
1257           (_("%s: TLS reference in %B "
1258              "mismatches non-TLS definition in %B section %A"),
1259            tbfd, ntbfd, ntsec, h->root.root.string);
1260
1261       bfd_set_error (bfd_error_bad_value);
1262       return FALSE;
1263     }
1264
1265   /* If the old symbol has non-default visibility, we ignore the new
1266      definition from a dynamic object.  */
1267   if (newdyn
1268       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1269       && !bfd_is_und_section (sec))
1270     {
1271       *skip = TRUE;
1272       /* Make sure this symbol is dynamic.  */
1273       h->ref_dynamic = 1;
1274       hi->ref_dynamic = 1;
1275       /* A protected symbol has external availability. Make sure it is
1276          recorded as dynamic.
1277
1278          FIXME: Should we check type and size for protected symbol?  */
1279       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1280         return bfd_elf_link_record_dynamic_symbol (info, h);
1281       else
1282         return TRUE;
1283     }
1284   else if (!newdyn
1285            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1286            && h->def_dynamic)
1287     {
1288       /* If the new symbol with non-default visibility comes from a
1289          relocatable file and the old definition comes from a dynamic
1290          object, we remove the old definition.  */
1291       if (hi->root.type == bfd_link_hash_indirect)
1292         {
1293           /* Handle the case where the old dynamic definition is
1294              default versioned.  We need to copy the symbol info from
1295              the symbol with default version to the normal one if it
1296              was referenced before.  */
1297           if (h->ref_regular)
1298             {
1299               hi->root.type = h->root.type;
1300               h->root.type = bfd_link_hash_indirect;
1301               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1302
1303               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1304               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1305                 {
1306                   /* If the new symbol is hidden or internal, completely undo
1307                      any dynamic link state.  */
1308                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1309                   h->forced_local = 0;
1310                   h->ref_dynamic = 0;
1311                 }
1312               else
1313                 h->ref_dynamic = 1;
1314
1315               h->def_dynamic = 0;
1316               /* FIXME: Should we check type and size for protected symbol?  */
1317               h->size = 0;
1318               h->type = 0;
1319
1320               h = hi;
1321             }
1322           else
1323             h = hi;
1324         }
1325
1326       /* If the old symbol was undefined before, then it will still be
1327          on the undefs list.  If the new symbol is undefined or
1328          common, we can't make it bfd_link_hash_new here, because new
1329          undefined or common symbols will be added to the undefs list
1330          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1331          added twice to the undefs list.  Also, if the new symbol is
1332          undefweak then we don't want to lose the strong undef.  */
1333       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1334         {
1335           h->root.type = bfd_link_hash_undefined;
1336           h->root.u.undef.abfd = abfd;
1337         }
1338       else
1339         {
1340           h->root.type = bfd_link_hash_new;
1341           h->root.u.undef.abfd = NULL;
1342         }
1343
1344       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1345         {
1346           /* If the new symbol is hidden or internal, completely undo
1347              any dynamic link state.  */
1348           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1349           h->forced_local = 0;
1350           h->ref_dynamic = 0;
1351         }
1352       else
1353         h->ref_dynamic = 1;
1354       h->def_dynamic = 0;
1355       /* FIXME: Should we check type and size for protected symbol?  */
1356       h->size = 0;
1357       h->type = 0;
1358       return TRUE;
1359     }
1360
1361   /* If a new weak symbol definition comes from a regular file and the
1362      old symbol comes from a dynamic library, we treat the new one as
1363      strong.  Similarly, an old weak symbol definition from a regular
1364      file is treated as strong when the new symbol comes from a dynamic
1365      library.  Further, an old weak symbol from a dynamic library is
1366      treated as strong if the new symbol is from a dynamic library.
1367      This reflects the way glibc's ld.so works.
1368
1369      Do this before setting *type_change_ok or *size_change_ok so that
1370      we warn properly when dynamic library symbols are overridden.  */
1371
1372   if (newdef && !newdyn && olddyn)
1373     newweak = FALSE;
1374   if (olddef && newdyn)
1375     oldweak = FALSE;
1376
1377   /* Allow changes between different types of function symbol.  */
1378   if (newfunc && oldfunc)
1379     *type_change_ok = TRUE;
1380
1381   /* It's OK to change the type if either the existing symbol or the
1382      new symbol is weak.  A type change is also OK if the old symbol
1383      is undefined and the new symbol is defined.  */
1384
1385   if (oldweak
1386       || newweak
1387       || (newdef
1388           && h->root.type == bfd_link_hash_undefined))
1389     *type_change_ok = TRUE;
1390
1391   /* It's OK to change the size if either the existing symbol or the
1392      new symbol is weak, or if the old symbol is undefined.  */
1393
1394   if (*type_change_ok
1395       || h->root.type == bfd_link_hash_undefined)
1396     *size_change_ok = TRUE;
1397
1398   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1399      symbol, respectively, appears to be a common symbol in a dynamic
1400      object.  If a symbol appears in an uninitialized section, and is
1401      not weak, and is not a function, then it may be a common symbol
1402      which was resolved when the dynamic object was created.  We want
1403      to treat such symbols specially, because they raise special
1404      considerations when setting the symbol size: if the symbol
1405      appears as a common symbol in a regular object, and the size in
1406      the regular object is larger, we must make sure that we use the
1407      larger size.  This problematic case can always be avoided in C,
1408      but it must be handled correctly when using Fortran shared
1409      libraries.
1410
1411      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1412      likewise for OLDDYNCOMMON and OLDDEF.
1413
1414      Note that this test is just a heuristic, and that it is quite
1415      possible to have an uninitialized symbol in a shared object which
1416      is really a definition, rather than a common symbol.  This could
1417      lead to some minor confusion when the symbol really is a common
1418      symbol in some regular object.  However, I think it will be
1419      harmless.  */
1420
1421   if (newdyn
1422       && newdef
1423       && !newweak
1424       && (sec->flags & SEC_ALLOC) != 0
1425       && (sec->flags & SEC_LOAD) == 0
1426       && sym->st_size > 0
1427       && !newfunc)
1428     newdyncommon = TRUE;
1429   else
1430     newdyncommon = FALSE;
1431
1432   if (olddyn
1433       && olddef
1434       && h->root.type == bfd_link_hash_defined
1435       && h->def_dynamic
1436       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1437       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1438       && h->size > 0
1439       && !oldfunc)
1440     olddyncommon = TRUE;
1441   else
1442     olddyncommon = FALSE;
1443
1444   /* We now know everything about the old and new symbols.  We ask the
1445      backend to check if we can merge them.  */
1446   if (bed->merge_symbol != NULL)
1447     {
1448       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1449         return FALSE;
1450       sec = *psec;
1451     }
1452
1453   /* If both the old and the new symbols look like common symbols in a
1454      dynamic object, set the size of the symbol to the larger of the
1455      two.  */
1456
1457   if (olddyncommon
1458       && newdyncommon
1459       && sym->st_size != h->size)
1460     {
1461       /* Since we think we have two common symbols, issue a multiple
1462          common warning if desired.  Note that we only warn if the
1463          size is different.  If the size is the same, we simply let
1464          the old symbol override the new one as normally happens with
1465          symbols defined in dynamic objects.  */
1466
1467       if (! ((*info->callbacks->multiple_common)
1468              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1469         return FALSE;
1470
1471       if (sym->st_size > h->size)
1472         h->size = sym->st_size;
1473
1474       *size_change_ok = TRUE;
1475     }
1476
1477   /* If we are looking at a dynamic object, and we have found a
1478      definition, we need to see if the symbol was already defined by
1479      some other object.  If so, we want to use the existing
1480      definition, and we do not want to report a multiple symbol
1481      definition error; we do this by clobbering *PSEC to be
1482      bfd_und_section_ptr.
1483
1484      We treat a common symbol as a definition if the symbol in the
1485      shared library is a function, since common symbols always
1486      represent variables; this can cause confusion in principle, but
1487      any such confusion would seem to indicate an erroneous program or
1488      shared library.  We also permit a common symbol in a regular
1489      object to override a weak symbol in a shared object.  */
1490
1491   if (newdyn
1492       && newdef
1493       && (olddef
1494           || (h->root.type == bfd_link_hash_common
1495               && (newweak || newfunc))))
1496     {
1497       *override = TRUE;
1498       newdef = FALSE;
1499       newdyncommon = FALSE;
1500
1501       *psec = sec = bfd_und_section_ptr;
1502       *size_change_ok = TRUE;
1503
1504       /* If we get here when the old symbol is a common symbol, then
1505          we are explicitly letting it override a weak symbol or
1506          function in a dynamic object, and we don't want to warn about
1507          a type change.  If the old symbol is a defined symbol, a type
1508          change warning may still be appropriate.  */
1509
1510       if (h->root.type == bfd_link_hash_common)
1511         *type_change_ok = TRUE;
1512     }
1513
1514   /* Handle the special case of an old common symbol merging with a
1515      new symbol which looks like a common symbol in a shared object.
1516      We change *PSEC and *PVALUE to make the new symbol look like a
1517      common symbol, and let _bfd_generic_link_add_one_symbol do the
1518      right thing.  */
1519
1520   if (newdyncommon
1521       && h->root.type == bfd_link_hash_common)
1522     {
1523       *override = TRUE;
1524       newdef = FALSE;
1525       newdyncommon = FALSE;
1526       *pvalue = sym->st_size;
1527       *psec = sec = bed->common_section (oldsec);
1528       *size_change_ok = TRUE;
1529     }
1530
1531   /* Skip weak definitions of symbols that are already defined.  */
1532   if (newdef && olddef && newweak)
1533     {
1534       /* Don't skip new non-IR weak syms.  */
1535       if (!(oldbfd != NULL
1536             && (oldbfd->flags & BFD_PLUGIN) != 0
1537             && (abfd->flags & BFD_PLUGIN) == 0))
1538         {
1539           newdef = FALSE;
1540           *skip = TRUE;
1541         }
1542
1543       /* Merge st_other.  If the symbol already has a dynamic index,
1544          but visibility says it should not be visible, turn it into a
1545          local symbol.  */
1546       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1547       if (h->dynindx != -1)
1548         switch (ELF_ST_VISIBILITY (h->other))
1549           {
1550           case STV_INTERNAL:
1551           case STV_HIDDEN:
1552             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1553             break;
1554           }
1555     }
1556
1557   /* If the old symbol is from a dynamic object, and the new symbol is
1558      a definition which is not from a dynamic object, then the new
1559      symbol overrides the old symbol.  Symbols from regular files
1560      always take precedence over symbols from dynamic objects, even if
1561      they are defined after the dynamic object in the link.
1562
1563      As above, we again permit a common symbol in a regular object to
1564      override a definition in a shared object if the shared object
1565      symbol is a function or is weak.  */
1566
1567   flip = NULL;
1568   if (!newdyn
1569       && (newdef
1570           || (bfd_is_com_section (sec)
1571               && (oldweak || oldfunc)))
1572       && olddyn
1573       && olddef
1574       && h->def_dynamic)
1575     {
1576       /* Change the hash table entry to undefined, and let
1577          _bfd_generic_link_add_one_symbol do the right thing with the
1578          new definition.  */
1579
1580       h->root.type = bfd_link_hash_undefined;
1581       h->root.u.undef.abfd = h->root.u.def.section->owner;
1582       *size_change_ok = TRUE;
1583
1584       olddef = FALSE;
1585       olddyncommon = FALSE;
1586
1587       /* We again permit a type change when a common symbol may be
1588          overriding a function.  */
1589
1590       if (bfd_is_com_section (sec))
1591         {
1592           if (oldfunc)
1593             {
1594               /* If a common symbol overrides a function, make sure
1595                  that it isn't defined dynamically nor has type
1596                  function.  */
1597               h->def_dynamic = 0;
1598               h->type = STT_NOTYPE;
1599             }
1600           *type_change_ok = TRUE;
1601         }
1602
1603       if (hi->root.type == bfd_link_hash_indirect)
1604         flip = hi;
1605       else
1606         /* This union may have been set to be non-NULL when this symbol
1607            was seen in a dynamic object.  We must force the union to be
1608            NULL, so that it is correct for a regular symbol.  */
1609         h->verinfo.vertree = NULL;
1610     }
1611
1612   /* Handle the special case of a new common symbol merging with an
1613      old symbol that looks like it might be a common symbol defined in
1614      a shared object.  Note that we have already handled the case in
1615      which a new common symbol should simply override the definition
1616      in the shared library.  */
1617
1618   if (! newdyn
1619       && bfd_is_com_section (sec)
1620       && olddyncommon)
1621     {
1622       /* It would be best if we could set the hash table entry to a
1623          common symbol, but we don't know what to use for the section
1624          or the alignment.  */
1625       if (! ((*info->callbacks->multiple_common)
1626              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1627         return FALSE;
1628
1629       /* If the presumed common symbol in the dynamic object is
1630          larger, pretend that the new symbol has its size.  */
1631
1632       if (h->size > *pvalue)
1633         *pvalue = h->size;
1634
1635       /* We need to remember the alignment required by the symbol
1636          in the dynamic object.  */
1637       BFD_ASSERT (pold_alignment);
1638       *pold_alignment = h->root.u.def.section->alignment_power;
1639
1640       olddef = FALSE;
1641       olddyncommon = FALSE;
1642
1643       h->root.type = bfd_link_hash_undefined;
1644       h->root.u.undef.abfd = h->root.u.def.section->owner;
1645
1646       *size_change_ok = TRUE;
1647       *type_change_ok = TRUE;
1648
1649       if (hi->root.type == bfd_link_hash_indirect)
1650         flip = hi;
1651       else
1652         h->verinfo.vertree = NULL;
1653     }
1654
1655   if (flip != NULL)
1656     {
1657       /* Handle the case where we had a versioned symbol in a dynamic
1658          library and now find a definition in a normal object.  In this
1659          case, we make the versioned symbol point to the normal one.  */
1660       flip->root.type = h->root.type;
1661       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1662       h->root.type = bfd_link_hash_indirect;
1663       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1664       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1665       if (h->def_dynamic)
1666         {
1667           h->def_dynamic = 0;
1668           flip->ref_dynamic = 1;
1669         }
1670     }
1671
1672   return TRUE;
1673 }
1674
1675 /* This function is called to create an indirect symbol from the
1676    default for the symbol with the default version if needed. The
1677    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1678    set DYNSYM if the new indirect symbol is dynamic.  */
1679
1680 static bfd_boolean
1681 _bfd_elf_add_default_symbol (bfd *abfd,
1682                              struct bfd_link_info *info,
1683                              struct elf_link_hash_entry *h,
1684                              const char *name,
1685                              Elf_Internal_Sym *sym,
1686                              asection *sec,
1687                              bfd_vma value,
1688                              bfd **poldbfd,
1689                              bfd_boolean *dynsym)
1690 {
1691   bfd_boolean type_change_ok;
1692   bfd_boolean size_change_ok;
1693   bfd_boolean skip;
1694   char *shortname;
1695   struct elf_link_hash_entry *hi;
1696   struct bfd_link_hash_entry *bh;
1697   const struct elf_backend_data *bed;
1698   bfd_boolean collect;
1699   bfd_boolean dynamic;
1700   bfd_boolean override;
1701   char *p;
1702   size_t len, shortlen;
1703   asection *tmp_sec;
1704   bfd_boolean matched;
1705
1706   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1707     return TRUE;
1708
1709   /* If this symbol has a version, and it is the default version, we
1710      create an indirect symbol from the default name to the fully
1711      decorated name.  This will cause external references which do not
1712      specify a version to be bound to this version of the symbol.  */
1713   p = strchr (name, ELF_VER_CHR);
1714   if (h->versioned == unknown)
1715     {
1716       if (p == NULL)
1717         {
1718           h->versioned = unversioned;
1719           return TRUE;
1720         }
1721       else
1722         {
1723           if (p[1] != ELF_VER_CHR)
1724             {
1725               h->versioned = versioned_hidden;
1726               return TRUE;
1727             }
1728           else
1729             h->versioned = versioned;
1730         }
1731     }
1732   else
1733     {
1734       /* PR ld/19073: We may see an unversioned definition after the
1735          default version.  */
1736       if (p == NULL)
1737         return TRUE;
1738     }
1739
1740   bed = get_elf_backend_data (abfd);
1741   collect = bed->collect;
1742   dynamic = (abfd->flags & DYNAMIC) != 0;
1743
1744   shortlen = p - name;
1745   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1746   if (shortname == NULL)
1747     return FALSE;
1748   memcpy (shortname, name, shortlen);
1749   shortname[shortlen] = '\0';
1750
1751   /* We are going to create a new symbol.  Merge it with any existing
1752      symbol with this name.  For the purposes of the merge, act as
1753      though we were defining the symbol we just defined, although we
1754      actually going to define an indirect symbol.  */
1755   type_change_ok = FALSE;
1756   size_change_ok = FALSE;
1757   matched = TRUE;
1758   tmp_sec = sec;
1759   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1760                               &hi, poldbfd, NULL, NULL, &skip, &override,
1761                               &type_change_ok, &size_change_ok, &matched))
1762     return FALSE;
1763
1764   if (skip)
1765     goto nondefault;
1766
1767   if (! override)
1768     {
1769       /* Add the default symbol if not performing a relocatable link.  */
1770       if (! bfd_link_relocatable (info))
1771         {
1772           bh = &hi->root;
1773           if (! (_bfd_generic_link_add_one_symbol
1774                  (info, abfd, shortname, BSF_INDIRECT,
1775                   bfd_ind_section_ptr,
1776                   0, name, FALSE, collect, &bh)))
1777             return FALSE;
1778           hi = (struct elf_link_hash_entry *) bh;
1779         }
1780     }
1781   else
1782     {
1783       /* In this case the symbol named SHORTNAME is overriding the
1784          indirect symbol we want to add.  We were planning on making
1785          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1786          is the name without a version.  NAME is the fully versioned
1787          name, and it is the default version.
1788
1789          Overriding means that we already saw a definition for the
1790          symbol SHORTNAME in a regular object, and it is overriding
1791          the symbol defined in the dynamic object.
1792
1793          When this happens, we actually want to change NAME, the
1794          symbol we just added, to refer to SHORTNAME.  This will cause
1795          references to NAME in the shared object to become references
1796          to SHORTNAME in the regular object.  This is what we expect
1797          when we override a function in a shared object: that the
1798          references in the shared object will be mapped to the
1799          definition in the regular object.  */
1800
1801       while (hi->root.type == bfd_link_hash_indirect
1802              || hi->root.type == bfd_link_hash_warning)
1803         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1804
1805       h->root.type = bfd_link_hash_indirect;
1806       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1807       if (h->def_dynamic)
1808         {
1809           h->def_dynamic = 0;
1810           hi->ref_dynamic = 1;
1811           if (hi->ref_regular
1812               || hi->def_regular)
1813             {
1814               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1815                 return FALSE;
1816             }
1817         }
1818
1819       /* Now set HI to H, so that the following code will set the
1820          other fields correctly.  */
1821       hi = h;
1822     }
1823
1824   /* Check if HI is a warning symbol.  */
1825   if (hi->root.type == bfd_link_hash_warning)
1826     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1827
1828   /* If there is a duplicate definition somewhere, then HI may not
1829      point to an indirect symbol.  We will have reported an error to
1830      the user in that case.  */
1831
1832   if (hi->root.type == bfd_link_hash_indirect)
1833     {
1834       struct elf_link_hash_entry *ht;
1835
1836       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1837       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1838
1839       /* A reference to the SHORTNAME symbol from a dynamic library
1840          will be satisfied by the versioned symbol at runtime.  In
1841          effect, we have a reference to the versioned symbol.  */
1842       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1843       hi->dynamic_def |= ht->dynamic_def;
1844
1845       /* See if the new flags lead us to realize that the symbol must
1846          be dynamic.  */
1847       if (! *dynsym)
1848         {
1849           if (! dynamic)
1850             {
1851               if (! bfd_link_executable (info)
1852                   || hi->def_dynamic
1853                   || hi->ref_dynamic)
1854                 *dynsym = TRUE;
1855             }
1856           else
1857             {
1858               if (hi->ref_regular)
1859                 *dynsym = TRUE;
1860             }
1861         }
1862     }
1863
1864   /* We also need to define an indirection from the nondefault version
1865      of the symbol.  */
1866
1867 nondefault:
1868   len = strlen (name);
1869   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1870   if (shortname == NULL)
1871     return FALSE;
1872   memcpy (shortname, name, shortlen);
1873   memcpy (shortname + shortlen, p + 1, len - shortlen);
1874
1875   /* Once again, merge with any existing symbol.  */
1876   type_change_ok = FALSE;
1877   size_change_ok = FALSE;
1878   tmp_sec = sec;
1879   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1880                               &hi, poldbfd, NULL, NULL, &skip, &override,
1881                               &type_change_ok, &size_change_ok, &matched))
1882     return FALSE;
1883
1884   if (skip)
1885     return TRUE;
1886
1887   if (override)
1888     {
1889       /* Here SHORTNAME is a versioned name, so we don't expect to see
1890          the type of override we do in the case above unless it is
1891          overridden by a versioned definition.  */
1892       if (hi->root.type != bfd_link_hash_defined
1893           && hi->root.type != bfd_link_hash_defweak)
1894         (*_bfd_error_handler)
1895           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1896            abfd, shortname);
1897     }
1898   else
1899     {
1900       bh = &hi->root;
1901       if (! (_bfd_generic_link_add_one_symbol
1902              (info, abfd, shortname, BSF_INDIRECT,
1903               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1904         return FALSE;
1905       hi = (struct elf_link_hash_entry *) bh;
1906
1907       /* If there is a duplicate definition somewhere, then HI may not
1908          point to an indirect symbol.  We will have reported an error
1909          to the user in that case.  */
1910
1911       if (hi->root.type == bfd_link_hash_indirect)
1912         {
1913           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1914           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1915           hi->dynamic_def |= h->dynamic_def;
1916
1917           /* See if the new flags lead us to realize that the symbol
1918              must be dynamic.  */
1919           if (! *dynsym)
1920             {
1921               if (! dynamic)
1922                 {
1923                   if (! bfd_link_executable (info)
1924                       || hi->ref_dynamic)
1925                     *dynsym = TRUE;
1926                 }
1927               else
1928                 {
1929                   if (hi->ref_regular)
1930                     *dynsym = TRUE;
1931                 }
1932             }
1933         }
1934     }
1935
1936   return TRUE;
1937 }
1938 \f
1939 /* This routine is used to export all defined symbols into the dynamic
1940    symbol table.  It is called via elf_link_hash_traverse.  */
1941
1942 static bfd_boolean
1943 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1944 {
1945   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1946
1947   /* Ignore indirect symbols.  These are added by the versioning code.  */
1948   if (h->root.type == bfd_link_hash_indirect)
1949     return TRUE;
1950
1951   /* Ignore this if we won't export it.  */
1952   if (!eif->info->export_dynamic && !h->dynamic)
1953     return TRUE;
1954
1955   if (h->dynindx == -1
1956       && (h->def_regular || h->ref_regular)
1957       && ! bfd_hide_sym_by_version (eif->info->version_info,
1958                                     h->root.root.string))
1959     {
1960       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1961         {
1962           eif->failed = TRUE;
1963           return FALSE;
1964         }
1965     }
1966
1967   return TRUE;
1968 }
1969 \f
1970 /* Look through the symbols which are defined in other shared
1971    libraries and referenced here.  Update the list of version
1972    dependencies.  This will be put into the .gnu.version_r section.
1973    This function is called via elf_link_hash_traverse.  */
1974
1975 static bfd_boolean
1976 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1977                                          void *data)
1978 {
1979   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1980   Elf_Internal_Verneed *t;
1981   Elf_Internal_Vernaux *a;
1982   bfd_size_type amt;
1983
1984   /* We only care about symbols defined in shared objects with version
1985      information.  */
1986   if (!h->def_dynamic
1987       || h->def_regular
1988       || h->dynindx == -1
1989       || h->verinfo.verdef == NULL
1990       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
1991           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
1992     return TRUE;
1993
1994   /* See if we already know about this version.  */
1995   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1996        t != NULL;
1997        t = t->vn_nextref)
1998     {
1999       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2000         continue;
2001
2002       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2003         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2004           return TRUE;
2005
2006       break;
2007     }
2008
2009   /* This is a new version.  Add it to tree we are building.  */
2010
2011   if (t == NULL)
2012     {
2013       amt = sizeof *t;
2014       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2015       if (t == NULL)
2016         {
2017           rinfo->failed = TRUE;
2018           return FALSE;
2019         }
2020
2021       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2022       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2023       elf_tdata (rinfo->info->output_bfd)->verref = t;
2024     }
2025
2026   amt = sizeof *a;
2027   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2028   if (a == NULL)
2029     {
2030       rinfo->failed = TRUE;
2031       return FALSE;
2032     }
2033
2034   /* Note that we are copying a string pointer here, and testing it
2035      above.  If bfd_elf_string_from_elf_section is ever changed to
2036      discard the string data when low in memory, this will have to be
2037      fixed.  */
2038   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2039
2040   a->vna_flags = h->verinfo.verdef->vd_flags;
2041   a->vna_nextptr = t->vn_auxptr;
2042
2043   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2044   ++rinfo->vers;
2045
2046   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2047
2048   t->vn_auxptr = a;
2049
2050   return TRUE;
2051 }
2052
2053 /* Figure out appropriate versions for all the symbols.  We may not
2054    have the version number script until we have read all of the input
2055    files, so until that point we don't know which symbols should be
2056    local.  This function is called via elf_link_hash_traverse.  */
2057
2058 static bfd_boolean
2059 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2060 {
2061   struct elf_info_failed *sinfo;
2062   struct bfd_link_info *info;
2063   const struct elf_backend_data *bed;
2064   struct elf_info_failed eif;
2065   char *p;
2066   bfd_size_type amt;
2067
2068   sinfo = (struct elf_info_failed *) data;
2069   info = sinfo->info;
2070
2071   /* Fix the symbol flags.  */
2072   eif.failed = FALSE;
2073   eif.info = info;
2074   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2075     {
2076       if (eif.failed)
2077         sinfo->failed = TRUE;
2078       return FALSE;
2079     }
2080
2081   /* We only need version numbers for symbols defined in regular
2082      objects.  */
2083   if (!h->def_regular)
2084     return TRUE;
2085
2086   bed = get_elf_backend_data (info->output_bfd);
2087   p = strchr (h->root.root.string, ELF_VER_CHR);
2088   if (p != NULL && h->verinfo.vertree == NULL)
2089     {
2090       struct bfd_elf_version_tree *t;
2091
2092       ++p;
2093       if (*p == ELF_VER_CHR)
2094         ++p;
2095
2096       /* If there is no version string, we can just return out.  */
2097       if (*p == '\0')
2098         return TRUE;
2099
2100       /* Look for the version.  If we find it, it is no longer weak.  */
2101       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2102         {
2103           if (strcmp (t->name, p) == 0)
2104             {
2105               size_t len;
2106               char *alc;
2107               struct bfd_elf_version_expr *d;
2108
2109               len = p - h->root.root.string;
2110               alc = (char *) bfd_malloc (len);
2111               if (alc == NULL)
2112                 {
2113                   sinfo->failed = TRUE;
2114                   return FALSE;
2115                 }
2116               memcpy (alc, h->root.root.string, len - 1);
2117               alc[len - 1] = '\0';
2118               if (alc[len - 2] == ELF_VER_CHR)
2119                 alc[len - 2] = '\0';
2120
2121               h->verinfo.vertree = t;
2122               t->used = TRUE;
2123               d = NULL;
2124
2125               if (t->globals.list != NULL)
2126                 d = (*t->match) (&t->globals, NULL, alc);
2127
2128               /* See if there is anything to force this symbol to
2129                  local scope.  */
2130               if (d == NULL && t->locals.list != NULL)
2131                 {
2132                   d = (*t->match) (&t->locals, NULL, alc);
2133                   if (d != NULL
2134                       && h->dynindx != -1
2135                       && ! info->export_dynamic)
2136                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2137                 }
2138
2139               free (alc);
2140               break;
2141             }
2142         }
2143
2144       /* If we are building an application, we need to create a
2145          version node for this version.  */
2146       if (t == NULL && bfd_link_executable (info))
2147         {
2148           struct bfd_elf_version_tree **pp;
2149           int version_index;
2150
2151           /* If we aren't going to export this symbol, we don't need
2152              to worry about it.  */
2153           if (h->dynindx == -1)
2154             return TRUE;
2155
2156           amt = sizeof *t;
2157           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2158           if (t == NULL)
2159             {
2160               sinfo->failed = TRUE;
2161               return FALSE;
2162             }
2163
2164           t->name = p;
2165           t->name_indx = (unsigned int) -1;
2166           t->used = TRUE;
2167
2168           version_index = 1;
2169           /* Don't count anonymous version tag.  */
2170           if (sinfo->info->version_info != NULL
2171               && sinfo->info->version_info->vernum == 0)
2172             version_index = 0;
2173           for (pp = &sinfo->info->version_info;
2174                *pp != NULL;
2175                pp = &(*pp)->next)
2176             ++version_index;
2177           t->vernum = version_index;
2178
2179           *pp = t;
2180
2181           h->verinfo.vertree = t;
2182         }
2183       else if (t == NULL)
2184         {
2185           /* We could not find the version for a symbol when
2186              generating a shared archive.  Return an error.  */
2187           (*_bfd_error_handler)
2188             (_("%B: version node not found for symbol %s"),
2189              info->output_bfd, h->root.root.string);
2190           bfd_set_error (bfd_error_bad_value);
2191           sinfo->failed = TRUE;
2192           return FALSE;
2193         }
2194     }
2195
2196   /* If we don't have a version for this symbol, see if we can find
2197      something.  */
2198   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2199     {
2200       bfd_boolean hide;
2201
2202       h->verinfo.vertree
2203         = bfd_find_version_for_sym (sinfo->info->version_info,
2204                                     h->root.root.string, &hide);
2205       if (h->verinfo.vertree != NULL && hide)
2206         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2207     }
2208
2209   return TRUE;
2210 }
2211 \f
2212 /* Read and swap the relocs from the section indicated by SHDR.  This
2213    may be either a REL or a RELA section.  The relocations are
2214    translated into RELA relocations and stored in INTERNAL_RELOCS,
2215    which should have already been allocated to contain enough space.
2216    The EXTERNAL_RELOCS are a buffer where the external form of the
2217    relocations should be stored.
2218
2219    Returns FALSE if something goes wrong.  */
2220
2221 static bfd_boolean
2222 elf_link_read_relocs_from_section (bfd *abfd,
2223                                    asection *sec,
2224                                    Elf_Internal_Shdr *shdr,
2225                                    void *external_relocs,
2226                                    Elf_Internal_Rela *internal_relocs)
2227 {
2228   const struct elf_backend_data *bed;
2229   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2230   const bfd_byte *erela;
2231   const bfd_byte *erelaend;
2232   Elf_Internal_Rela *irela;
2233   Elf_Internal_Shdr *symtab_hdr;
2234   size_t nsyms;
2235
2236   /* Position ourselves at the start of the section.  */
2237   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2238     return FALSE;
2239
2240   /* Read the relocations.  */
2241   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2242     return FALSE;
2243
2244   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2245   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2246
2247   bed = get_elf_backend_data (abfd);
2248
2249   /* Convert the external relocations to the internal format.  */
2250   if (shdr->sh_entsize == bed->s->sizeof_rel)
2251     swap_in = bed->s->swap_reloc_in;
2252   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2253     swap_in = bed->s->swap_reloca_in;
2254   else
2255     {
2256       bfd_set_error (bfd_error_wrong_format);
2257       return FALSE;
2258     }
2259
2260   erela = (const bfd_byte *) external_relocs;
2261   erelaend = erela + shdr->sh_size;
2262   irela = internal_relocs;
2263   while (erela < erelaend)
2264     {
2265       bfd_vma r_symndx;
2266
2267       (*swap_in) (abfd, erela, irela);
2268       r_symndx = ELF32_R_SYM (irela->r_info);
2269       if (bed->s->arch_size == 64)
2270         r_symndx >>= 24;
2271       if (nsyms > 0)
2272         {
2273           if ((size_t) r_symndx >= nsyms)
2274             {
2275               (*_bfd_error_handler)
2276                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2277                    " for offset 0x%lx in section `%A'"),
2278                  abfd, sec,
2279                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2280               bfd_set_error (bfd_error_bad_value);
2281               return FALSE;
2282             }
2283         }
2284       else if (r_symndx != STN_UNDEF)
2285         {
2286           (*_bfd_error_handler)
2287             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2288                " when the object file has no symbol table"),
2289              abfd, sec,
2290              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2291           bfd_set_error (bfd_error_bad_value);
2292           return FALSE;
2293         }
2294       irela += bed->s->int_rels_per_ext_rel;
2295       erela += shdr->sh_entsize;
2296     }
2297
2298   return TRUE;
2299 }
2300
2301 /* Read and swap the relocs for a section O.  They may have been
2302    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2303    not NULL, they are used as buffers to read into.  They are known to
2304    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2305    the return value is allocated using either malloc or bfd_alloc,
2306    according to the KEEP_MEMORY argument.  If O has two relocation
2307    sections (both REL and RELA relocations), then the REL_HDR
2308    relocations will appear first in INTERNAL_RELOCS, followed by the
2309    RELA_HDR relocations.  */
2310
2311 Elf_Internal_Rela *
2312 _bfd_elf_link_read_relocs (bfd *abfd,
2313                            asection *o,
2314                            void *external_relocs,
2315                            Elf_Internal_Rela *internal_relocs,
2316                            bfd_boolean keep_memory)
2317 {
2318   void *alloc1 = NULL;
2319   Elf_Internal_Rela *alloc2 = NULL;
2320   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2321   struct bfd_elf_section_data *esdo = elf_section_data (o);
2322   Elf_Internal_Rela *internal_rela_relocs;
2323
2324   if (esdo->relocs != NULL)
2325     return esdo->relocs;
2326
2327   if (o->reloc_count == 0)
2328     return NULL;
2329
2330   if (internal_relocs == NULL)
2331     {
2332       bfd_size_type size;
2333
2334       size = o->reloc_count;
2335       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2336       if (keep_memory)
2337         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2338       else
2339         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2340       if (internal_relocs == NULL)
2341         goto error_return;
2342     }
2343
2344   if (external_relocs == NULL)
2345     {
2346       bfd_size_type size = 0;
2347
2348       if (esdo->rel.hdr)
2349         size += esdo->rel.hdr->sh_size;
2350       if (esdo->rela.hdr)
2351         size += esdo->rela.hdr->sh_size;
2352
2353       alloc1 = bfd_malloc (size);
2354       if (alloc1 == NULL)
2355         goto error_return;
2356       external_relocs = alloc1;
2357     }
2358
2359   internal_rela_relocs = internal_relocs;
2360   if (esdo->rel.hdr)
2361     {
2362       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2363                                               external_relocs,
2364                                               internal_relocs))
2365         goto error_return;
2366       external_relocs = (((bfd_byte *) external_relocs)
2367                          + esdo->rel.hdr->sh_size);
2368       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2369                                * bed->s->int_rels_per_ext_rel);
2370     }
2371
2372   if (esdo->rela.hdr
2373       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2374                                               external_relocs,
2375                                               internal_rela_relocs)))
2376     goto error_return;
2377
2378   /* Cache the results for next time, if we can.  */
2379   if (keep_memory)
2380     esdo->relocs = internal_relocs;
2381
2382   if (alloc1 != NULL)
2383     free (alloc1);
2384
2385   /* Don't free alloc2, since if it was allocated we are passing it
2386      back (under the name of internal_relocs).  */
2387
2388   return internal_relocs;
2389
2390  error_return:
2391   if (alloc1 != NULL)
2392     free (alloc1);
2393   if (alloc2 != NULL)
2394     {
2395       if (keep_memory)
2396         bfd_release (abfd, alloc2);
2397       else
2398         free (alloc2);
2399     }
2400   return NULL;
2401 }
2402
2403 /* Compute the size of, and allocate space for, REL_HDR which is the
2404    section header for a section containing relocations for O.  */
2405
2406 static bfd_boolean
2407 _bfd_elf_link_size_reloc_section (bfd *abfd,
2408                                   struct bfd_elf_section_reloc_data *reldata)
2409 {
2410   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2411
2412   /* That allows us to calculate the size of the section.  */
2413   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2414
2415   /* The contents field must last into write_object_contents, so we
2416      allocate it with bfd_alloc rather than malloc.  Also since we
2417      cannot be sure that the contents will actually be filled in,
2418      we zero the allocated space.  */
2419   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2420   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2421     return FALSE;
2422
2423   if (reldata->hashes == NULL && reldata->count)
2424     {
2425       struct elf_link_hash_entry **p;
2426
2427       p = ((struct elf_link_hash_entry **)
2428            bfd_zmalloc (reldata->count * sizeof (*p)));
2429       if (p == NULL)
2430         return FALSE;
2431
2432       reldata->hashes = p;
2433     }
2434
2435   return TRUE;
2436 }
2437
2438 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2439    originated from the section given by INPUT_REL_HDR) to the
2440    OUTPUT_BFD.  */
2441
2442 bfd_boolean
2443 _bfd_elf_link_output_relocs (bfd *output_bfd,
2444                              asection *input_section,
2445                              Elf_Internal_Shdr *input_rel_hdr,
2446                              Elf_Internal_Rela *internal_relocs,
2447                              struct elf_link_hash_entry **rel_hash
2448                                ATTRIBUTE_UNUSED)
2449 {
2450   Elf_Internal_Rela *irela;
2451   Elf_Internal_Rela *irelaend;
2452   bfd_byte *erel;
2453   struct bfd_elf_section_reloc_data *output_reldata;
2454   asection *output_section;
2455   const struct elf_backend_data *bed;
2456   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2457   struct bfd_elf_section_data *esdo;
2458
2459   output_section = input_section->output_section;
2460
2461   bed = get_elf_backend_data (output_bfd);
2462   esdo = elf_section_data (output_section);
2463   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2464     {
2465       output_reldata = &esdo->rel;
2466       swap_out = bed->s->swap_reloc_out;
2467     }
2468   else if (esdo->rela.hdr
2469            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2470     {
2471       output_reldata = &esdo->rela;
2472       swap_out = bed->s->swap_reloca_out;
2473     }
2474   else
2475     {
2476       (*_bfd_error_handler)
2477         (_("%B: relocation size mismatch in %B section %A"),
2478          output_bfd, input_section->owner, input_section);
2479       bfd_set_error (bfd_error_wrong_format);
2480       return FALSE;
2481     }
2482
2483   erel = output_reldata->hdr->contents;
2484   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2485   irela = internal_relocs;
2486   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2487                       * bed->s->int_rels_per_ext_rel);
2488   while (irela < irelaend)
2489     {
2490       (*swap_out) (output_bfd, irela, erel);
2491       irela += bed->s->int_rels_per_ext_rel;
2492       erel += input_rel_hdr->sh_entsize;
2493     }
2494
2495   /* Bump the counter, so that we know where to add the next set of
2496      relocations.  */
2497   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2498
2499   return TRUE;
2500 }
2501 \f
2502 /* Make weak undefined symbols in PIE dynamic.  */
2503
2504 bfd_boolean
2505 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2506                                  struct elf_link_hash_entry *h)
2507 {
2508   if (bfd_link_pie (info)
2509       && h->dynindx == -1
2510       && h->root.type == bfd_link_hash_undefweak)
2511     return bfd_elf_link_record_dynamic_symbol (info, h);
2512
2513   return TRUE;
2514 }
2515
2516 /* Fix up the flags for a symbol.  This handles various cases which
2517    can only be fixed after all the input files are seen.  This is
2518    currently called by both adjust_dynamic_symbol and
2519    assign_sym_version, which is unnecessary but perhaps more robust in
2520    the face of future changes.  */
2521
2522 static bfd_boolean
2523 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2524                            struct elf_info_failed *eif)
2525 {
2526   const struct elf_backend_data *bed;
2527
2528   /* If this symbol was mentioned in a non-ELF file, try to set
2529      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2530      permit a non-ELF file to correctly refer to a symbol defined in
2531      an ELF dynamic object.  */
2532   if (h->non_elf)
2533     {
2534       while (h->root.type == bfd_link_hash_indirect)
2535         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2536
2537       if (h->root.type != bfd_link_hash_defined
2538           && h->root.type != bfd_link_hash_defweak)
2539         {
2540           h->ref_regular = 1;
2541           h->ref_regular_nonweak = 1;
2542         }
2543       else
2544         {
2545           if (h->root.u.def.section->owner != NULL
2546               && (bfd_get_flavour (h->root.u.def.section->owner)
2547                   == bfd_target_elf_flavour))
2548             {
2549               h->ref_regular = 1;
2550               h->ref_regular_nonweak = 1;
2551             }
2552           else
2553             h->def_regular = 1;
2554         }
2555
2556       if (h->dynindx == -1
2557           && (h->def_dynamic
2558               || h->ref_dynamic))
2559         {
2560           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2561             {
2562               eif->failed = TRUE;
2563               return FALSE;
2564             }
2565         }
2566     }
2567   else
2568     {
2569       /* Unfortunately, NON_ELF is only correct if the symbol
2570          was first seen in a non-ELF file.  Fortunately, if the symbol
2571          was first seen in an ELF file, we're probably OK unless the
2572          symbol was defined in a non-ELF file.  Catch that case here.
2573          FIXME: We're still in trouble if the symbol was first seen in
2574          a dynamic object, and then later in a non-ELF regular object.  */
2575       if ((h->root.type == bfd_link_hash_defined
2576            || h->root.type == bfd_link_hash_defweak)
2577           && !h->def_regular
2578           && (h->root.u.def.section->owner != NULL
2579               ? (bfd_get_flavour (h->root.u.def.section->owner)
2580                  != bfd_target_elf_flavour)
2581               : (bfd_is_abs_section (h->root.u.def.section)
2582                  && !h->def_dynamic)))
2583         h->def_regular = 1;
2584     }
2585
2586   /* Backend specific symbol fixup.  */
2587   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2588   if (bed->elf_backend_fixup_symbol
2589       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2590     return FALSE;
2591
2592   /* If this is a final link, and the symbol was defined as a common
2593      symbol in a regular object file, and there was no definition in
2594      any dynamic object, then the linker will have allocated space for
2595      the symbol in a common section but the DEF_REGULAR
2596      flag will not have been set.  */
2597   if (h->root.type == bfd_link_hash_defined
2598       && !h->def_regular
2599       && h->ref_regular
2600       && !h->def_dynamic
2601       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2602     h->def_regular = 1;
2603
2604   /* If -Bsymbolic was used (which means to bind references to global
2605      symbols to the definition within the shared object), and this
2606      symbol was defined in a regular object, then it actually doesn't
2607      need a PLT entry.  Likewise, if the symbol has non-default
2608      visibility.  If the symbol has hidden or internal visibility, we
2609      will force it local.  */
2610   if (h->needs_plt
2611       && bfd_link_pic (eif->info)
2612       && is_elf_hash_table (eif->info->hash)
2613       && (SYMBOLIC_BIND (eif->info, h)
2614           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2615       && h->def_regular)
2616     {
2617       bfd_boolean force_local;
2618
2619       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2620                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2621       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2622     }
2623
2624   /* If a weak undefined symbol has non-default visibility, we also
2625      hide it from the dynamic linker.  */
2626   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2627       && h->root.type == bfd_link_hash_undefweak)
2628     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2629
2630   /* If this is a weak defined symbol in a dynamic object, and we know
2631      the real definition in the dynamic object, copy interesting flags
2632      over to the real definition.  */
2633   if (h->u.weakdef != NULL)
2634     {
2635       /* If the real definition is defined by a regular object file,
2636          don't do anything special.  See the longer description in
2637          _bfd_elf_adjust_dynamic_symbol, below.  */
2638       if (h->u.weakdef->def_regular)
2639         h->u.weakdef = NULL;
2640       else
2641         {
2642           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2643
2644           while (h->root.type == bfd_link_hash_indirect)
2645             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2646
2647           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2648                       || h->root.type == bfd_link_hash_defweak);
2649           BFD_ASSERT (weakdef->def_dynamic);
2650           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2651                       || weakdef->root.type == bfd_link_hash_defweak);
2652           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2653         }
2654     }
2655
2656   return TRUE;
2657 }
2658
2659 /* Make the backend pick a good value for a dynamic symbol.  This is
2660    called via elf_link_hash_traverse, and also calls itself
2661    recursively.  */
2662
2663 static bfd_boolean
2664 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2665 {
2666   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2667   bfd *dynobj;
2668   const struct elf_backend_data *bed;
2669
2670   if (! is_elf_hash_table (eif->info->hash))
2671     return FALSE;
2672
2673   /* Ignore indirect symbols.  These are added by the versioning code.  */
2674   if (h->root.type == bfd_link_hash_indirect)
2675     return TRUE;
2676
2677   /* Fix the symbol flags.  */
2678   if (! _bfd_elf_fix_symbol_flags (h, eif))
2679     return FALSE;
2680
2681   /* If this symbol does not require a PLT entry, and it is not
2682      defined by a dynamic object, or is not referenced by a regular
2683      object, ignore it.  We do have to handle a weak defined symbol,
2684      even if no regular object refers to it, if we decided to add it
2685      to the dynamic symbol table.  FIXME: Do we normally need to worry
2686      about symbols which are defined by one dynamic object and
2687      referenced by another one?  */
2688   if (!h->needs_plt
2689       && h->type != STT_GNU_IFUNC
2690       && (h->def_regular
2691           || !h->def_dynamic
2692           || (!h->ref_regular
2693               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2694     {
2695       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2696       return TRUE;
2697     }
2698
2699   /* If we've already adjusted this symbol, don't do it again.  This
2700      can happen via a recursive call.  */
2701   if (h->dynamic_adjusted)
2702     return TRUE;
2703
2704   /* Don't look at this symbol again.  Note that we must set this
2705      after checking the above conditions, because we may look at a
2706      symbol once, decide not to do anything, and then get called
2707      recursively later after REF_REGULAR is set below.  */
2708   h->dynamic_adjusted = 1;
2709
2710   /* If this is a weak definition, and we know a real definition, and
2711      the real symbol is not itself defined by a regular object file,
2712      then get a good value for the real definition.  We handle the
2713      real symbol first, for the convenience of the backend routine.
2714
2715      Note that there is a confusing case here.  If the real definition
2716      is defined by a regular object file, we don't get the real symbol
2717      from the dynamic object, but we do get the weak symbol.  If the
2718      processor backend uses a COPY reloc, then if some routine in the
2719      dynamic object changes the real symbol, we will not see that
2720      change in the corresponding weak symbol.  This is the way other
2721      ELF linkers work as well, and seems to be a result of the shared
2722      library model.
2723
2724      I will clarify this issue.  Most SVR4 shared libraries define the
2725      variable _timezone and define timezone as a weak synonym.  The
2726      tzset call changes _timezone.  If you write
2727        extern int timezone;
2728        int _timezone = 5;
2729        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2730      you might expect that, since timezone is a synonym for _timezone,
2731      the same number will print both times.  However, if the processor
2732      backend uses a COPY reloc, then actually timezone will be copied
2733      into your process image, and, since you define _timezone
2734      yourself, _timezone will not.  Thus timezone and _timezone will
2735      wind up at different memory locations.  The tzset call will set
2736      _timezone, leaving timezone unchanged.  */
2737
2738   if (h->u.weakdef != NULL)
2739     {
2740       /* If we get to this point, there is an implicit reference to
2741          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2742       h->u.weakdef->ref_regular = 1;
2743
2744       /* Ensure that the backend adjust_dynamic_symbol function sees
2745          H->U.WEAKDEF before H by recursively calling ourselves.  */
2746       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2747         return FALSE;
2748     }
2749
2750   /* If a symbol has no type and no size and does not require a PLT
2751      entry, then we are probably about to do the wrong thing here: we
2752      are probably going to create a COPY reloc for an empty object.
2753      This case can arise when a shared object is built with assembly
2754      code, and the assembly code fails to set the symbol type.  */
2755   if (h->size == 0
2756       && h->type == STT_NOTYPE
2757       && !h->needs_plt)
2758     (*_bfd_error_handler)
2759       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2760        h->root.root.string);
2761
2762   dynobj = elf_hash_table (eif->info)->dynobj;
2763   bed = get_elf_backend_data (dynobj);
2764
2765   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2766     {
2767       eif->failed = TRUE;
2768       return FALSE;
2769     }
2770
2771   return TRUE;
2772 }
2773
2774 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2775    DYNBSS.  */
2776
2777 bfd_boolean
2778 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2779                               struct elf_link_hash_entry *h,
2780                               asection *dynbss)
2781 {
2782   unsigned int power_of_two;
2783   bfd_vma mask;
2784   asection *sec = h->root.u.def.section;
2785
2786   /* The section aligment of definition is the maximum alignment
2787      requirement of symbols defined in the section.  Since we don't
2788      know the symbol alignment requirement, we start with the
2789      maximum alignment and check low bits of the symbol address
2790      for the minimum alignment.  */
2791   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2792   mask = ((bfd_vma) 1 << power_of_two) - 1;
2793   while ((h->root.u.def.value & mask) != 0)
2794     {
2795        mask >>= 1;
2796        --power_of_two;
2797     }
2798
2799   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2800                                                 dynbss))
2801     {
2802       /* Adjust the section alignment if needed.  */
2803       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2804                                        power_of_two))
2805         return FALSE;
2806     }
2807
2808   /* We make sure that the symbol will be aligned properly.  */
2809   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2810
2811   /* Define the symbol as being at this point in DYNBSS.  */
2812   h->root.u.def.section = dynbss;
2813   h->root.u.def.value = dynbss->size;
2814
2815   /* Increment the size of DYNBSS to make room for the symbol.  */
2816   dynbss->size += h->size;
2817
2818   /* No error if extern_protected_data is true.  */
2819   if (h->protected_def
2820       && (!info->extern_protected_data
2821           || (info->extern_protected_data < 0
2822               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2823     info->callbacks->einfo
2824       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2825        h->root.root.string);
2826
2827   return TRUE;
2828 }
2829
2830 /* Adjust all external symbols pointing into SEC_MERGE sections
2831    to reflect the object merging within the sections.  */
2832
2833 static bfd_boolean
2834 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2835 {
2836   asection *sec;
2837
2838   if ((h->root.type == bfd_link_hash_defined
2839        || h->root.type == bfd_link_hash_defweak)
2840       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2841       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2842     {
2843       bfd *output_bfd = (bfd *) data;
2844
2845       h->root.u.def.value =
2846         _bfd_merged_section_offset (output_bfd,
2847                                     &h->root.u.def.section,
2848                                     elf_section_data (sec)->sec_info,
2849                                     h->root.u.def.value);
2850     }
2851
2852   return TRUE;
2853 }
2854
2855 /* Returns false if the symbol referred to by H should be considered
2856    to resolve local to the current module, and true if it should be
2857    considered to bind dynamically.  */
2858
2859 bfd_boolean
2860 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2861                            struct bfd_link_info *info,
2862                            bfd_boolean not_local_protected)
2863 {
2864   bfd_boolean binding_stays_local_p;
2865   const struct elf_backend_data *bed;
2866   struct elf_link_hash_table *hash_table;
2867
2868   if (h == NULL)
2869     return FALSE;
2870
2871   while (h->root.type == bfd_link_hash_indirect
2872          || h->root.type == bfd_link_hash_warning)
2873     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2874
2875   /* If it was forced local, then clearly it's not dynamic.  */
2876   if (h->dynindx == -1)
2877     return FALSE;
2878   if (h->forced_local)
2879     return FALSE;
2880
2881   /* Identify the cases where name binding rules say that a
2882      visible symbol resolves locally.  */
2883   binding_stays_local_p = (bfd_link_executable (info)
2884                            || SYMBOLIC_BIND (info, h));
2885
2886   switch (ELF_ST_VISIBILITY (h->other))
2887     {
2888     case STV_INTERNAL:
2889     case STV_HIDDEN:
2890       return FALSE;
2891
2892     case STV_PROTECTED:
2893       hash_table = elf_hash_table (info);
2894       if (!is_elf_hash_table (hash_table))
2895         return FALSE;
2896
2897       bed = get_elf_backend_data (hash_table->dynobj);
2898
2899       /* Proper resolution for function pointer equality may require
2900          that these symbols perhaps be resolved dynamically, even though
2901          we should be resolving them to the current module.  */
2902       if (!not_local_protected || !bed->is_function_type (h->type))
2903         binding_stays_local_p = TRUE;
2904       break;
2905
2906     default:
2907       break;
2908     }
2909
2910   /* If it isn't defined locally, then clearly it's dynamic.  */
2911   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2912     return TRUE;
2913
2914   /* Otherwise, the symbol is dynamic if binding rules don't tell
2915      us that it remains local.  */
2916   return !binding_stays_local_p;
2917 }
2918
2919 /* Return true if the symbol referred to by H should be considered
2920    to resolve local to the current module, and false otherwise.  Differs
2921    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2922    undefined symbols.  The two functions are virtually identical except
2923    for the place where forced_local and dynindx == -1 are tested.  If
2924    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2925    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2926    the symbol is local only for defined symbols.
2927    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2928    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2929    treatment of undefined weak symbols.  For those that do not make
2930    undefined weak symbols dynamic, both functions may return false.  */
2931
2932 bfd_boolean
2933 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2934                               struct bfd_link_info *info,
2935                               bfd_boolean local_protected)
2936 {
2937   const struct elf_backend_data *bed;
2938   struct elf_link_hash_table *hash_table;
2939
2940   /* If it's a local sym, of course we resolve locally.  */
2941   if (h == NULL)
2942     return TRUE;
2943
2944   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2945   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2946       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2947     return TRUE;
2948
2949   /* Common symbols that become definitions don't get the DEF_REGULAR
2950      flag set, so test it first, and don't bail out.  */
2951   if (ELF_COMMON_DEF_P (h))
2952     /* Do nothing.  */;
2953   /* If we don't have a definition in a regular file, then we can't
2954      resolve locally.  The sym is either undefined or dynamic.  */
2955   else if (!h->def_regular)
2956     return FALSE;
2957
2958   /* Forced local symbols resolve locally.  */
2959   if (h->forced_local)
2960     return TRUE;
2961
2962   /* As do non-dynamic symbols.  */
2963   if (h->dynindx == -1)
2964     return TRUE;
2965
2966   /* At this point, we know the symbol is defined and dynamic.  In an
2967      executable it must resolve locally, likewise when building symbolic
2968      shared libraries.  */
2969   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
2970     return TRUE;
2971
2972   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2973      with default visibility might not resolve locally.  */
2974   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2975     return FALSE;
2976
2977   hash_table = elf_hash_table (info);
2978   if (!is_elf_hash_table (hash_table))
2979     return TRUE;
2980
2981   bed = get_elf_backend_data (hash_table->dynobj);
2982
2983   /* If extern_protected_data is false, STV_PROTECTED non-function
2984      symbols are local.  */
2985   if ((!info->extern_protected_data
2986        || (info->extern_protected_data < 0
2987            && !bed->extern_protected_data))
2988       && !bed->is_function_type (h->type))
2989     return TRUE;
2990
2991   /* Function pointer equality tests may require that STV_PROTECTED
2992      symbols be treated as dynamic symbols.  If the address of a
2993      function not defined in an executable is set to that function's
2994      plt entry in the executable, then the address of the function in
2995      a shared library must also be the plt entry in the executable.  */
2996   return local_protected;
2997 }
2998
2999 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3000    aligned.  Returns the first TLS output section.  */
3001
3002 struct bfd_section *
3003 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3004 {
3005   struct bfd_section *sec, *tls;
3006   unsigned int align = 0;
3007
3008   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3009     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3010       break;
3011   tls = sec;
3012
3013   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3014     if (sec->alignment_power > align)
3015       align = sec->alignment_power;
3016
3017   elf_hash_table (info)->tls_sec = tls;
3018
3019   /* Ensure the alignment of the first section is the largest alignment,
3020      so that the tls segment starts aligned.  */
3021   if (tls != NULL)
3022     tls->alignment_power = align;
3023
3024   return tls;
3025 }
3026
3027 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3028 static bfd_boolean
3029 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3030                                   Elf_Internal_Sym *sym)
3031 {
3032   const struct elf_backend_data *bed;
3033
3034   /* Local symbols do not count, but target specific ones might.  */
3035   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3036       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3037     return FALSE;
3038
3039   bed = get_elf_backend_data (abfd);
3040   /* Function symbols do not count.  */
3041   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3042     return FALSE;
3043
3044   /* If the section is undefined, then so is the symbol.  */
3045   if (sym->st_shndx == SHN_UNDEF)
3046     return FALSE;
3047
3048   /* If the symbol is defined in the common section, then
3049      it is a common definition and so does not count.  */
3050   if (bed->common_definition (sym))
3051     return FALSE;
3052
3053   /* If the symbol is in a target specific section then we
3054      must rely upon the backend to tell us what it is.  */
3055   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3056     /* FIXME - this function is not coded yet:
3057
3058        return _bfd_is_global_symbol_definition (abfd, sym);
3059
3060        Instead for now assume that the definition is not global,
3061        Even if this is wrong, at least the linker will behave
3062        in the same way that it used to do.  */
3063     return FALSE;
3064
3065   return TRUE;
3066 }
3067
3068 /* Search the symbol table of the archive element of the archive ABFD
3069    whose archive map contains a mention of SYMDEF, and determine if
3070    the symbol is defined in this element.  */
3071 static bfd_boolean
3072 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3073 {
3074   Elf_Internal_Shdr * hdr;
3075   bfd_size_type symcount;
3076   bfd_size_type extsymcount;
3077   bfd_size_type extsymoff;
3078   Elf_Internal_Sym *isymbuf;
3079   Elf_Internal_Sym *isym;
3080   Elf_Internal_Sym *isymend;
3081   bfd_boolean result;
3082
3083   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3084   if (abfd == NULL)
3085     return FALSE;
3086
3087   /* Return FALSE if the object has been claimed by plugin.  */
3088   if (abfd->plugin_format == bfd_plugin_yes)
3089     return FALSE;
3090
3091   if (! bfd_check_format (abfd, bfd_object))
3092     return FALSE;
3093
3094   /* Select the appropriate symbol table.  */
3095   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3096     hdr = &elf_tdata (abfd)->symtab_hdr;
3097   else
3098     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3099
3100   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3101
3102   /* The sh_info field of the symtab header tells us where the
3103      external symbols start.  We don't care about the local symbols.  */
3104   if (elf_bad_symtab (abfd))
3105     {
3106       extsymcount = symcount;
3107       extsymoff = 0;
3108     }
3109   else
3110     {
3111       extsymcount = symcount - hdr->sh_info;
3112       extsymoff = hdr->sh_info;
3113     }
3114
3115   if (extsymcount == 0)
3116     return FALSE;
3117
3118   /* Read in the symbol table.  */
3119   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3120                                   NULL, NULL, NULL);
3121   if (isymbuf == NULL)
3122     return FALSE;
3123
3124   /* Scan the symbol table looking for SYMDEF.  */
3125   result = FALSE;
3126   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3127     {
3128       const char *name;
3129
3130       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3131                                               isym->st_name);
3132       if (name == NULL)
3133         break;
3134
3135       if (strcmp (name, symdef->name) == 0)
3136         {
3137           result = is_global_data_symbol_definition (abfd, isym);
3138           break;
3139         }
3140     }
3141
3142   free (isymbuf);
3143
3144   return result;
3145 }
3146 \f
3147 /* Add an entry to the .dynamic table.  */
3148
3149 bfd_boolean
3150 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3151                             bfd_vma tag,
3152                             bfd_vma val)
3153 {
3154   struct elf_link_hash_table *hash_table;
3155   const struct elf_backend_data *bed;
3156   asection *s;
3157   bfd_size_type newsize;
3158   bfd_byte *newcontents;
3159   Elf_Internal_Dyn dyn;
3160
3161   hash_table = elf_hash_table (info);
3162   if (! is_elf_hash_table (hash_table))
3163     return FALSE;
3164
3165   bed = get_elf_backend_data (hash_table->dynobj);
3166   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3167   BFD_ASSERT (s != NULL);
3168
3169   newsize = s->size + bed->s->sizeof_dyn;
3170   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3171   if (newcontents == NULL)
3172     return FALSE;
3173
3174   dyn.d_tag = tag;
3175   dyn.d_un.d_val = val;
3176   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3177
3178   s->size = newsize;
3179   s->contents = newcontents;
3180
3181   return TRUE;
3182 }
3183
3184 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3185    otherwise just check whether one already exists.  Returns -1 on error,
3186    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3187
3188 static int
3189 elf_add_dt_needed_tag (bfd *abfd,
3190                        struct bfd_link_info *info,
3191                        const char *soname,
3192                        bfd_boolean do_it)
3193 {
3194   struct elf_link_hash_table *hash_table;
3195   bfd_size_type strindex;
3196
3197   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3198     return -1;
3199
3200   hash_table = elf_hash_table (info);
3201   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3202   if (strindex == (bfd_size_type) -1)
3203     return -1;
3204
3205   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3206     {
3207       asection *sdyn;
3208       const struct elf_backend_data *bed;
3209       bfd_byte *extdyn;
3210
3211       bed = get_elf_backend_data (hash_table->dynobj);
3212       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3213       if (sdyn != NULL)
3214         for (extdyn = sdyn->contents;
3215              extdyn < sdyn->contents + sdyn->size;
3216              extdyn += bed->s->sizeof_dyn)
3217           {
3218             Elf_Internal_Dyn dyn;
3219
3220             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3221             if (dyn.d_tag == DT_NEEDED
3222                 && dyn.d_un.d_val == strindex)
3223               {
3224                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3225                 return 1;
3226               }
3227           }
3228     }
3229
3230   if (do_it)
3231     {
3232       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3233         return -1;
3234
3235       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3236         return -1;
3237     }
3238   else
3239     /* We were just checking for existence of the tag.  */
3240     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3241
3242   return 0;
3243 }
3244
3245 static bfd_boolean
3246 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3247 {
3248   for (; needed != NULL; needed = needed->next)
3249     if ((elf_dyn_lib_class (needed->by) & DYN_AS_NEEDED) == 0
3250         && strcmp (soname, needed->name) == 0)
3251       return TRUE;
3252
3253   return FALSE;
3254 }
3255
3256 /* Sort symbol by value, section, and size.  */
3257 static int
3258 elf_sort_symbol (const void *arg1, const void *arg2)
3259 {
3260   const struct elf_link_hash_entry *h1;
3261   const struct elf_link_hash_entry *h2;
3262   bfd_signed_vma vdiff;
3263
3264   h1 = *(const struct elf_link_hash_entry **) arg1;
3265   h2 = *(const struct elf_link_hash_entry **) arg2;
3266   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3267   if (vdiff != 0)
3268     return vdiff > 0 ? 1 : -1;
3269   else
3270     {
3271       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3272       if (sdiff != 0)
3273         return sdiff > 0 ? 1 : -1;
3274     }
3275   vdiff = h1->size - h2->size;
3276   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3277 }
3278
3279 /* This function is used to adjust offsets into .dynstr for
3280    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3281
3282 static bfd_boolean
3283 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3284 {
3285   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3286
3287   if (h->dynindx != -1)
3288     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3289   return TRUE;
3290 }
3291
3292 /* Assign string offsets in .dynstr, update all structures referencing
3293    them.  */
3294
3295 static bfd_boolean
3296 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3297 {
3298   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3299   struct elf_link_local_dynamic_entry *entry;
3300   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3301   bfd *dynobj = hash_table->dynobj;
3302   asection *sdyn;
3303   bfd_size_type size;
3304   const struct elf_backend_data *bed;
3305   bfd_byte *extdyn;
3306
3307   _bfd_elf_strtab_finalize (dynstr);
3308   size = _bfd_elf_strtab_size (dynstr);
3309
3310   bed = get_elf_backend_data (dynobj);
3311   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3312   BFD_ASSERT (sdyn != NULL);
3313
3314   /* Update all .dynamic entries referencing .dynstr strings.  */
3315   for (extdyn = sdyn->contents;
3316        extdyn < sdyn->contents + sdyn->size;
3317        extdyn += bed->s->sizeof_dyn)
3318     {
3319       Elf_Internal_Dyn dyn;
3320
3321       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3322       switch (dyn.d_tag)
3323         {
3324         case DT_STRSZ:
3325           dyn.d_un.d_val = size;
3326           break;
3327         case DT_NEEDED:
3328         case DT_SONAME:
3329         case DT_RPATH:
3330         case DT_RUNPATH:
3331         case DT_FILTER:
3332         case DT_AUXILIARY:
3333         case DT_AUDIT:
3334         case DT_DEPAUDIT:
3335           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3336           break;
3337         default:
3338           continue;
3339         }
3340       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3341     }
3342
3343   /* Now update local dynamic symbols.  */
3344   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3345     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3346                                                   entry->isym.st_name);
3347
3348   /* And the rest of dynamic symbols.  */
3349   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3350
3351   /* Adjust version definitions.  */
3352   if (elf_tdata (output_bfd)->cverdefs)
3353     {
3354       asection *s;
3355       bfd_byte *p;
3356       bfd_size_type i;
3357       Elf_Internal_Verdef def;
3358       Elf_Internal_Verdaux defaux;
3359
3360       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3361       p = s->contents;
3362       do
3363         {
3364           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3365                                    &def);
3366           p += sizeof (Elf_External_Verdef);
3367           if (def.vd_aux != sizeof (Elf_External_Verdef))
3368             continue;
3369           for (i = 0; i < def.vd_cnt; ++i)
3370             {
3371               _bfd_elf_swap_verdaux_in (output_bfd,
3372                                         (Elf_External_Verdaux *) p, &defaux);
3373               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3374                                                         defaux.vda_name);
3375               _bfd_elf_swap_verdaux_out (output_bfd,
3376                                          &defaux, (Elf_External_Verdaux *) p);
3377               p += sizeof (Elf_External_Verdaux);
3378             }
3379         }
3380       while (def.vd_next);
3381     }
3382
3383   /* Adjust version references.  */
3384   if (elf_tdata (output_bfd)->verref)
3385     {
3386       asection *s;
3387       bfd_byte *p;
3388       bfd_size_type i;
3389       Elf_Internal_Verneed need;
3390       Elf_Internal_Vernaux needaux;
3391
3392       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3393       p = s->contents;
3394       do
3395         {
3396           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3397                                     &need);
3398           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3399           _bfd_elf_swap_verneed_out (output_bfd, &need,
3400                                      (Elf_External_Verneed *) p);
3401           p += sizeof (Elf_External_Verneed);
3402           for (i = 0; i < need.vn_cnt; ++i)
3403             {
3404               _bfd_elf_swap_vernaux_in (output_bfd,
3405                                         (Elf_External_Vernaux *) p, &needaux);
3406               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3407                                                          needaux.vna_name);
3408               _bfd_elf_swap_vernaux_out (output_bfd,
3409                                          &needaux,
3410                                          (Elf_External_Vernaux *) p);
3411               p += sizeof (Elf_External_Vernaux);
3412             }
3413         }
3414       while (need.vn_next);
3415     }
3416
3417   return TRUE;
3418 }
3419 \f
3420 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3421    The default is to only match when the INPUT and OUTPUT are exactly
3422    the same target.  */
3423
3424 bfd_boolean
3425 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3426                                     const bfd_target *output)
3427 {
3428   return input == output;
3429 }
3430
3431 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3432    This version is used when different targets for the same architecture
3433    are virtually identical.  */
3434
3435 bfd_boolean
3436 _bfd_elf_relocs_compatible (const bfd_target *input,
3437                             const bfd_target *output)
3438 {
3439   const struct elf_backend_data *obed, *ibed;
3440
3441   if (input == output)
3442     return TRUE;
3443
3444   ibed = xvec_get_elf_backend_data (input);
3445   obed = xvec_get_elf_backend_data (output);
3446
3447   if (ibed->arch != obed->arch)
3448     return FALSE;
3449
3450   /* If both backends are using this function, deem them compatible.  */
3451   return ibed->relocs_compatible == obed->relocs_compatible;
3452 }
3453
3454 /* Make a special call to the linker "notice" function to tell it that
3455    we are about to handle an as-needed lib, or have finished
3456    processing the lib.  */
3457
3458 bfd_boolean
3459 _bfd_elf_notice_as_needed (bfd *ibfd,
3460                            struct bfd_link_info *info,
3461                            enum notice_asneeded_action act)
3462 {
3463   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3464 }
3465
3466 /* Add symbols from an ELF object file to the linker hash table.  */
3467
3468 static bfd_boolean
3469 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3470 {
3471   Elf_Internal_Ehdr *ehdr;
3472   Elf_Internal_Shdr *hdr;
3473   bfd_size_type symcount;
3474   bfd_size_type extsymcount;
3475   bfd_size_type extsymoff;
3476   struct elf_link_hash_entry **sym_hash;
3477   bfd_boolean dynamic;
3478   Elf_External_Versym *extversym = NULL;
3479   Elf_External_Versym *ever;
3480   struct elf_link_hash_entry *weaks;
3481   struct elf_link_hash_entry **nondeflt_vers = NULL;
3482   bfd_size_type nondeflt_vers_cnt = 0;
3483   Elf_Internal_Sym *isymbuf = NULL;
3484   Elf_Internal_Sym *isym;
3485   Elf_Internal_Sym *isymend;
3486   const struct elf_backend_data *bed;
3487   bfd_boolean add_needed;
3488   struct elf_link_hash_table *htab;
3489   bfd_size_type amt;
3490   void *alloc_mark = NULL;
3491   struct bfd_hash_entry **old_table = NULL;
3492   unsigned int old_size = 0;
3493   unsigned int old_count = 0;
3494   void *old_tab = NULL;
3495   void *old_ent;
3496   struct bfd_link_hash_entry *old_undefs = NULL;
3497   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3498   long old_dynsymcount = 0;
3499   bfd_size_type old_dynstr_size = 0;
3500   size_t tabsize = 0;
3501   asection *s;
3502   bfd_boolean just_syms;
3503
3504   htab = elf_hash_table (info);
3505   bed = get_elf_backend_data (abfd);
3506
3507   if ((abfd->flags & DYNAMIC) == 0)
3508     dynamic = FALSE;
3509   else
3510     {
3511       dynamic = TRUE;
3512
3513       /* You can't use -r against a dynamic object.  Also, there's no
3514          hope of using a dynamic object which does not exactly match
3515          the format of the output file.  */
3516       if (bfd_link_relocatable (info)
3517           || !is_elf_hash_table (htab)
3518           || info->output_bfd->xvec != abfd->xvec)
3519         {
3520           if (bfd_link_relocatable (info))
3521             bfd_set_error (bfd_error_invalid_operation);
3522           else
3523             bfd_set_error (bfd_error_wrong_format);
3524           goto error_return;
3525         }
3526     }
3527
3528   ehdr = elf_elfheader (abfd);
3529   if (info->warn_alternate_em
3530       && bed->elf_machine_code != ehdr->e_machine
3531       && ((bed->elf_machine_alt1 != 0
3532            && ehdr->e_machine == bed->elf_machine_alt1)
3533           || (bed->elf_machine_alt2 != 0
3534               && ehdr->e_machine == bed->elf_machine_alt2)))
3535     info->callbacks->einfo
3536       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3537        ehdr->e_machine, abfd, bed->elf_machine_code);
3538
3539   /* As a GNU extension, any input sections which are named
3540      .gnu.warning.SYMBOL are treated as warning symbols for the given
3541      symbol.  This differs from .gnu.warning sections, which generate
3542      warnings when they are included in an output file.  */
3543   /* PR 12761: Also generate this warning when building shared libraries.  */
3544   for (s = abfd->sections; s != NULL; s = s->next)
3545     {
3546       const char *name;
3547
3548       name = bfd_get_section_name (abfd, s);
3549       if (CONST_STRNEQ (name, ".gnu.warning."))
3550         {
3551           char *msg;
3552           bfd_size_type sz;
3553
3554           name += sizeof ".gnu.warning." - 1;
3555
3556           /* If this is a shared object, then look up the symbol
3557              in the hash table.  If it is there, and it is already
3558              been defined, then we will not be using the entry
3559              from this shared object, so we don't need to warn.
3560              FIXME: If we see the definition in a regular object
3561              later on, we will warn, but we shouldn't.  The only
3562              fix is to keep track of what warnings we are supposed
3563              to emit, and then handle them all at the end of the
3564              link.  */
3565           if (dynamic)
3566             {
3567               struct elf_link_hash_entry *h;
3568
3569               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3570
3571               /* FIXME: What about bfd_link_hash_common?  */
3572               if (h != NULL
3573                   && (h->root.type == bfd_link_hash_defined
3574                       || h->root.type == bfd_link_hash_defweak))
3575                 continue;
3576             }
3577
3578           sz = s->size;
3579           msg = (char *) bfd_alloc (abfd, sz + 1);
3580           if (msg == NULL)
3581             goto error_return;
3582
3583           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3584             goto error_return;
3585
3586           msg[sz] = '\0';
3587
3588           if (! (_bfd_generic_link_add_one_symbol
3589                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3590                   FALSE, bed->collect, NULL)))
3591             goto error_return;
3592
3593           if (bfd_link_executable (info))
3594             {
3595               /* Clobber the section size so that the warning does
3596                  not get copied into the output file.  */
3597               s->size = 0;
3598
3599               /* Also set SEC_EXCLUDE, so that symbols defined in
3600                  the warning section don't get copied to the output.  */
3601               s->flags |= SEC_EXCLUDE;
3602             }
3603         }
3604     }
3605
3606   just_syms = ((s = abfd->sections) != NULL
3607                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3608
3609   add_needed = TRUE;
3610   if (! dynamic)
3611     {
3612       /* If we are creating a shared library, create all the dynamic
3613          sections immediately.  We need to attach them to something,
3614          so we attach them to this BFD, provided it is the right
3615          format and is not from ld --just-symbols.  Always create the
3616          dynamic sections for -E/--dynamic-list.  FIXME: If there
3617          are no input BFD's of the same format as the output, we can't
3618          make a shared library.  */
3619       if (!just_syms
3620           && (bfd_link_pic (info)
3621               || info->export_dynamic
3622               || info->dynamic)
3623           && is_elf_hash_table (htab)
3624           && info->output_bfd->xvec == abfd->xvec
3625           && !htab->dynamic_sections_created)
3626         {
3627           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3628             goto error_return;
3629         }
3630     }
3631   else if (!is_elf_hash_table (htab))
3632     goto error_return;
3633   else
3634     {
3635       const char *soname = NULL;
3636       char *audit = NULL;
3637       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3638       int ret;
3639
3640       /* ld --just-symbols and dynamic objects don't mix very well.
3641          ld shouldn't allow it.  */
3642       if (just_syms)
3643         abort ();
3644
3645       /* If this dynamic lib was specified on the command line with
3646          --as-needed in effect, then we don't want to add a DT_NEEDED
3647          tag unless the lib is actually used.  Similary for libs brought
3648          in by another lib's DT_NEEDED.  When --no-add-needed is used
3649          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3650          any dynamic library in DT_NEEDED tags in the dynamic lib at
3651          all.  */
3652       add_needed = (elf_dyn_lib_class (abfd)
3653                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3654                        | DYN_NO_NEEDED)) == 0;
3655
3656       s = bfd_get_section_by_name (abfd, ".dynamic");
3657       if (s != NULL)
3658         {
3659           bfd_byte *dynbuf;
3660           bfd_byte *extdyn;
3661           unsigned int elfsec;
3662           unsigned long shlink;
3663
3664           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3665             {
3666 error_free_dyn:
3667               free (dynbuf);
3668               goto error_return;
3669             }
3670
3671           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3672           if (elfsec == SHN_BAD)
3673             goto error_free_dyn;
3674           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3675
3676           for (extdyn = dynbuf;
3677                extdyn < dynbuf + s->size;
3678                extdyn += bed->s->sizeof_dyn)
3679             {
3680               Elf_Internal_Dyn dyn;
3681
3682               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3683               if (dyn.d_tag == DT_SONAME)
3684                 {
3685                   unsigned int tagv = dyn.d_un.d_val;
3686                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3687                   if (soname == NULL)
3688                     goto error_free_dyn;
3689                 }
3690               if (dyn.d_tag == DT_NEEDED)
3691                 {
3692                   struct bfd_link_needed_list *n, **pn;
3693                   char *fnm, *anm;
3694                   unsigned int tagv = dyn.d_un.d_val;
3695
3696                   amt = sizeof (struct bfd_link_needed_list);
3697                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3698                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3699                   if (n == NULL || fnm == NULL)
3700                     goto error_free_dyn;
3701                   amt = strlen (fnm) + 1;
3702                   anm = (char *) bfd_alloc (abfd, amt);
3703                   if (anm == NULL)
3704                     goto error_free_dyn;
3705                   memcpy (anm, fnm, amt);
3706                   n->name = anm;
3707                   n->by = abfd;
3708                   n->next = NULL;
3709                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3710                     ;
3711                   *pn = n;
3712                 }
3713               if (dyn.d_tag == DT_RUNPATH)
3714                 {
3715                   struct bfd_link_needed_list *n, **pn;
3716                   char *fnm, *anm;
3717                   unsigned int tagv = dyn.d_un.d_val;
3718
3719                   amt = sizeof (struct bfd_link_needed_list);
3720                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3721                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3722                   if (n == NULL || fnm == NULL)
3723                     goto error_free_dyn;
3724                   amt = strlen (fnm) + 1;
3725                   anm = (char *) bfd_alloc (abfd, amt);
3726                   if (anm == NULL)
3727                     goto error_free_dyn;
3728                   memcpy (anm, fnm, amt);
3729                   n->name = anm;
3730                   n->by = abfd;
3731                   n->next = NULL;
3732                   for (pn = & runpath;
3733                        *pn != NULL;
3734                        pn = &(*pn)->next)
3735                     ;
3736                   *pn = n;
3737                 }
3738               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3739               if (!runpath && dyn.d_tag == DT_RPATH)
3740                 {
3741                   struct bfd_link_needed_list *n, **pn;
3742                   char *fnm, *anm;
3743                   unsigned int tagv = dyn.d_un.d_val;
3744
3745                   amt = sizeof (struct bfd_link_needed_list);
3746                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3747                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3748                   if (n == NULL || fnm == NULL)
3749                     goto error_free_dyn;
3750                   amt = strlen (fnm) + 1;
3751                   anm = (char *) bfd_alloc (abfd, amt);
3752                   if (anm == NULL)
3753                     goto error_free_dyn;
3754                   memcpy (anm, fnm, amt);
3755                   n->name = anm;
3756                   n->by = abfd;
3757                   n->next = NULL;
3758                   for (pn = & rpath;
3759                        *pn != NULL;
3760                        pn = &(*pn)->next)
3761                     ;
3762                   *pn = n;
3763                 }
3764               if (dyn.d_tag == DT_AUDIT)
3765                 {
3766                   unsigned int tagv = dyn.d_un.d_val;
3767                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3768                 }
3769             }
3770
3771           free (dynbuf);
3772         }
3773
3774       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3775          frees all more recently bfd_alloc'd blocks as well.  */
3776       if (runpath)
3777         rpath = runpath;
3778
3779       if (rpath)
3780         {
3781           struct bfd_link_needed_list **pn;
3782           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3783             ;
3784           *pn = rpath;
3785         }
3786
3787       /* We do not want to include any of the sections in a dynamic
3788          object in the output file.  We hack by simply clobbering the
3789          list of sections in the BFD.  This could be handled more
3790          cleanly by, say, a new section flag; the existing
3791          SEC_NEVER_LOAD flag is not the one we want, because that one
3792          still implies that the section takes up space in the output
3793          file.  */
3794       bfd_section_list_clear (abfd);
3795
3796       /* Find the name to use in a DT_NEEDED entry that refers to this
3797          object.  If the object has a DT_SONAME entry, we use it.
3798          Otherwise, if the generic linker stuck something in
3799          elf_dt_name, we use that.  Otherwise, we just use the file
3800          name.  */
3801       if (soname == NULL || *soname == '\0')
3802         {
3803           soname = elf_dt_name (abfd);
3804           if (soname == NULL || *soname == '\0')
3805             soname = bfd_get_filename (abfd);
3806         }
3807
3808       /* Save the SONAME because sometimes the linker emulation code
3809          will need to know it.  */
3810       elf_dt_name (abfd) = soname;
3811
3812       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3813       if (ret < 0)
3814         goto error_return;
3815
3816       /* If we have already included this dynamic object in the
3817          link, just ignore it.  There is no reason to include a
3818          particular dynamic object more than once.  */
3819       if (ret > 0)
3820         return TRUE;
3821
3822       /* Save the DT_AUDIT entry for the linker emulation code. */
3823       elf_dt_audit (abfd) = audit;
3824     }
3825
3826   /* If this is a dynamic object, we always link against the .dynsym
3827      symbol table, not the .symtab symbol table.  The dynamic linker
3828      will only see the .dynsym symbol table, so there is no reason to
3829      look at .symtab for a dynamic object.  */
3830
3831   if (! dynamic || elf_dynsymtab (abfd) == 0)
3832     hdr = &elf_tdata (abfd)->symtab_hdr;
3833   else
3834     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3835
3836   symcount = hdr->sh_size / bed->s->sizeof_sym;
3837
3838   /* The sh_info field of the symtab header tells us where the
3839      external symbols start.  We don't care about the local symbols at
3840      this point.  */
3841   if (elf_bad_symtab (abfd))
3842     {
3843       extsymcount = symcount;
3844       extsymoff = 0;
3845     }
3846   else
3847     {
3848       extsymcount = symcount - hdr->sh_info;
3849       extsymoff = hdr->sh_info;
3850     }
3851
3852   sym_hash = elf_sym_hashes (abfd);
3853   if (extsymcount != 0)
3854     {
3855       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3856                                       NULL, NULL, NULL);
3857       if (isymbuf == NULL)
3858         goto error_return;
3859
3860       if (sym_hash == NULL)
3861         {
3862           /* We store a pointer to the hash table entry for each
3863              external symbol.  */
3864           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3865           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3866           if (sym_hash == NULL)
3867             goto error_free_sym;
3868           elf_sym_hashes (abfd) = sym_hash;
3869         }
3870     }
3871
3872   if (dynamic)
3873     {
3874       /* Read in any version definitions.  */
3875       if (!_bfd_elf_slurp_version_tables (abfd,
3876                                           info->default_imported_symver))
3877         goto error_free_sym;
3878
3879       /* Read in the symbol versions, but don't bother to convert them
3880          to internal format.  */
3881       if (elf_dynversym (abfd) != 0)
3882         {
3883           Elf_Internal_Shdr *versymhdr;
3884
3885           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3886           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3887           if (extversym == NULL)
3888             goto error_free_sym;
3889           amt = versymhdr->sh_size;
3890           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3891               || bfd_bread (extversym, amt, abfd) != amt)
3892             goto error_free_vers;
3893         }
3894     }
3895
3896   /* If we are loading an as-needed shared lib, save the symbol table
3897      state before we start adding symbols.  If the lib turns out
3898      to be unneeded, restore the state.  */
3899   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3900     {
3901       unsigned int i;
3902       size_t entsize;
3903
3904       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3905         {
3906           struct bfd_hash_entry *p;
3907           struct elf_link_hash_entry *h;
3908
3909           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3910             {
3911               h = (struct elf_link_hash_entry *) p;
3912               entsize += htab->root.table.entsize;
3913               if (h->root.type == bfd_link_hash_warning)
3914                 entsize += htab->root.table.entsize;
3915             }
3916         }
3917
3918       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3919       old_tab = bfd_malloc (tabsize + entsize);
3920       if (old_tab == NULL)
3921         goto error_free_vers;
3922
3923       /* Remember the current objalloc pointer, so that all mem for
3924          symbols added can later be reclaimed.  */
3925       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3926       if (alloc_mark == NULL)
3927         goto error_free_vers;
3928
3929       /* Make a special call to the linker "notice" function to
3930          tell it that we are about to handle an as-needed lib.  */
3931       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
3932         goto error_free_vers;
3933
3934       /* Clone the symbol table.  Remember some pointers into the
3935          symbol table, and dynamic symbol count.  */
3936       old_ent = (char *) old_tab + tabsize;
3937       memcpy (old_tab, htab->root.table.table, tabsize);
3938       old_undefs = htab->root.undefs;
3939       old_undefs_tail = htab->root.undefs_tail;
3940       old_table = htab->root.table.table;
3941       old_size = htab->root.table.size;
3942       old_count = htab->root.table.count;
3943       old_dynsymcount = htab->dynsymcount;
3944       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
3945
3946       for (i = 0; i < htab->root.table.size; i++)
3947         {
3948           struct bfd_hash_entry *p;
3949           struct elf_link_hash_entry *h;
3950
3951           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3952             {
3953               memcpy (old_ent, p, htab->root.table.entsize);
3954               old_ent = (char *) old_ent + htab->root.table.entsize;
3955               h = (struct elf_link_hash_entry *) p;
3956               if (h->root.type == bfd_link_hash_warning)
3957                 {
3958                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3959                   old_ent = (char *) old_ent + htab->root.table.entsize;
3960                 }
3961             }
3962         }
3963     }
3964
3965   weaks = NULL;
3966   ever = extversym != NULL ? extversym + extsymoff : NULL;
3967   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3968        isym < isymend;
3969        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3970     {
3971       int bind;
3972       bfd_vma value;
3973       asection *sec, *new_sec;
3974       flagword flags;
3975       const char *name;
3976       struct elf_link_hash_entry *h;
3977       struct elf_link_hash_entry *hi;
3978       bfd_boolean definition;
3979       bfd_boolean size_change_ok;
3980       bfd_boolean type_change_ok;
3981       bfd_boolean new_weakdef;
3982       bfd_boolean new_weak;
3983       bfd_boolean old_weak;
3984       bfd_boolean override;
3985       bfd_boolean common;
3986       unsigned int old_alignment;
3987       bfd *old_bfd;
3988       bfd_boolean matched;
3989
3990       override = FALSE;
3991
3992       flags = BSF_NO_FLAGS;
3993       sec = NULL;
3994       value = isym->st_value;
3995       common = bed->common_definition (isym);
3996
3997       bind = ELF_ST_BIND (isym->st_info);
3998       switch (bind)
3999         {
4000         case STB_LOCAL:
4001           /* This should be impossible, since ELF requires that all
4002              global symbols follow all local symbols, and that sh_info
4003              point to the first global symbol.  Unfortunately, Irix 5
4004              screws this up.  */
4005           continue;
4006
4007         case STB_GLOBAL:
4008           if (isym->st_shndx != SHN_UNDEF && !common)
4009             flags = BSF_GLOBAL;
4010           break;
4011
4012         case STB_WEAK:
4013           flags = BSF_WEAK;
4014           break;
4015
4016         case STB_GNU_UNIQUE:
4017           flags = BSF_GNU_UNIQUE;
4018           break;
4019
4020         default:
4021           /* Leave it up to the processor backend.  */
4022           break;
4023         }
4024
4025       if (isym->st_shndx == SHN_UNDEF)
4026         sec = bfd_und_section_ptr;
4027       else if (isym->st_shndx == SHN_ABS)
4028         sec = bfd_abs_section_ptr;
4029       else if (isym->st_shndx == SHN_COMMON)
4030         {
4031           sec = bfd_com_section_ptr;
4032           /* What ELF calls the size we call the value.  What ELF
4033              calls the value we call the alignment.  */
4034           value = isym->st_size;
4035         }
4036       else
4037         {
4038           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4039           if (sec == NULL)
4040             sec = bfd_abs_section_ptr;
4041           else if (discarded_section (sec))
4042             {
4043               /* Symbols from discarded section are undefined.  We keep
4044                  its visibility.  */
4045               sec = bfd_und_section_ptr;
4046               isym->st_shndx = SHN_UNDEF;
4047             }
4048           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4049             value -= sec->vma;
4050         }
4051
4052       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4053                                               isym->st_name);
4054       if (name == NULL)
4055         goto error_free_vers;
4056
4057       if (isym->st_shndx == SHN_COMMON
4058           && (abfd->flags & BFD_PLUGIN) != 0)
4059         {
4060           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4061
4062           if (xc == NULL)
4063             {
4064               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4065                                  | SEC_EXCLUDE);
4066               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4067               if (xc == NULL)
4068                 goto error_free_vers;
4069             }
4070           sec = xc;
4071         }
4072       else if (isym->st_shndx == SHN_COMMON
4073                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4074                && !bfd_link_relocatable (info))
4075         {
4076           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4077
4078           if (tcomm == NULL)
4079             {
4080               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4081                                  | SEC_LINKER_CREATED);
4082               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4083               if (tcomm == NULL)
4084                 goto error_free_vers;
4085             }
4086           sec = tcomm;
4087         }
4088       else if (bed->elf_add_symbol_hook)
4089         {
4090           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4091                                              &sec, &value))
4092             goto error_free_vers;
4093
4094           /* The hook function sets the name to NULL if this symbol
4095              should be skipped for some reason.  */
4096           if (name == NULL)
4097             continue;
4098         }
4099
4100       /* Sanity check that all possibilities were handled.  */
4101       if (sec == NULL)
4102         {
4103           bfd_set_error (bfd_error_bad_value);
4104           goto error_free_vers;
4105         }
4106
4107       /* Silently discard TLS symbols from --just-syms.  There's
4108          no way to combine a static TLS block with a new TLS block
4109          for this executable.  */
4110       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4111           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4112         continue;
4113
4114       if (bfd_is_und_section (sec)
4115           || bfd_is_com_section (sec))
4116         definition = FALSE;
4117       else
4118         definition = TRUE;
4119
4120       size_change_ok = FALSE;
4121       type_change_ok = bed->type_change_ok;
4122       old_weak = FALSE;
4123       matched = FALSE;
4124       old_alignment = 0;
4125       old_bfd = NULL;
4126       new_sec = sec;
4127
4128       if (is_elf_hash_table (htab))
4129         {
4130           Elf_Internal_Versym iver;
4131           unsigned int vernum = 0;
4132           bfd_boolean skip;
4133
4134           if (ever == NULL)
4135             {
4136               if (info->default_imported_symver)
4137                 /* Use the default symbol version created earlier.  */
4138                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4139               else
4140                 iver.vs_vers = 0;
4141             }
4142           else
4143             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4144
4145           vernum = iver.vs_vers & VERSYM_VERSION;
4146
4147           /* If this is a hidden symbol, or if it is not version
4148              1, we append the version name to the symbol name.
4149              However, we do not modify a non-hidden absolute symbol
4150              if it is not a function, because it might be the version
4151              symbol itself.  FIXME: What if it isn't?  */
4152           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4153               || (vernum > 1
4154                   && (!bfd_is_abs_section (sec)
4155                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4156             {
4157               const char *verstr;
4158               size_t namelen, verlen, newlen;
4159               char *newname, *p;
4160
4161               if (isym->st_shndx != SHN_UNDEF)
4162                 {
4163                   if (vernum > elf_tdata (abfd)->cverdefs)
4164                     verstr = NULL;
4165                   else if (vernum > 1)
4166                     verstr =
4167                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4168                   else
4169                     verstr = "";
4170
4171                   if (verstr == NULL)
4172                     {
4173                       (*_bfd_error_handler)
4174                         (_("%B: %s: invalid version %u (max %d)"),
4175                          abfd, name, vernum,
4176                          elf_tdata (abfd)->cverdefs);
4177                       bfd_set_error (bfd_error_bad_value);
4178                       goto error_free_vers;
4179                     }
4180                 }
4181               else
4182                 {
4183                   /* We cannot simply test for the number of
4184                      entries in the VERNEED section since the
4185                      numbers for the needed versions do not start
4186                      at 0.  */
4187                   Elf_Internal_Verneed *t;
4188
4189                   verstr = NULL;
4190                   for (t = elf_tdata (abfd)->verref;
4191                        t != NULL;
4192                        t = t->vn_nextref)
4193                     {
4194                       Elf_Internal_Vernaux *a;
4195
4196                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4197                         {
4198                           if (a->vna_other == vernum)
4199                             {
4200                               verstr = a->vna_nodename;
4201                               break;
4202                             }
4203                         }
4204                       if (a != NULL)
4205                         break;
4206                     }
4207                   if (verstr == NULL)
4208                     {
4209                       (*_bfd_error_handler)
4210                         (_("%B: %s: invalid needed version %d"),
4211                          abfd, name, vernum);
4212                       bfd_set_error (bfd_error_bad_value);
4213                       goto error_free_vers;
4214                     }
4215                 }
4216
4217               namelen = strlen (name);
4218               verlen = strlen (verstr);
4219               newlen = namelen + verlen + 2;
4220               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4221                   && isym->st_shndx != SHN_UNDEF)
4222                 ++newlen;
4223
4224               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4225               if (newname == NULL)
4226                 goto error_free_vers;
4227               memcpy (newname, name, namelen);
4228               p = newname + namelen;
4229               *p++ = ELF_VER_CHR;
4230               /* If this is a defined non-hidden version symbol,
4231                  we add another @ to the name.  This indicates the
4232                  default version of the symbol.  */
4233               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4234                   && isym->st_shndx != SHN_UNDEF)
4235                 *p++ = ELF_VER_CHR;
4236               memcpy (p, verstr, verlen + 1);
4237
4238               name = newname;
4239             }
4240
4241           /* If this symbol has default visibility and the user has
4242              requested we not re-export it, then mark it as hidden.  */
4243           if (!bfd_is_und_section (sec)
4244               && !dynamic
4245               && abfd->no_export
4246               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4247             isym->st_other = (STV_HIDDEN
4248                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4249
4250           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4251                                       sym_hash, &old_bfd, &old_weak,
4252                                       &old_alignment, &skip, &override,
4253                                       &type_change_ok, &size_change_ok,
4254                                       &matched))
4255             goto error_free_vers;
4256
4257           if (skip)
4258             continue;
4259
4260           /* Override a definition only if the new symbol matches the
4261              existing one.  */
4262           if (override && matched)
4263             definition = FALSE;
4264
4265           h = *sym_hash;
4266           while (h->root.type == bfd_link_hash_indirect
4267                  || h->root.type == bfd_link_hash_warning)
4268             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4269
4270           if (elf_tdata (abfd)->verdef != NULL
4271               && vernum > 1
4272               && definition)
4273             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4274         }
4275
4276       if (! (_bfd_generic_link_add_one_symbol
4277              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4278               (struct bfd_link_hash_entry **) sym_hash)))
4279         goto error_free_vers;
4280
4281       h = *sym_hash;
4282       /* We need to make sure that indirect symbol dynamic flags are
4283          updated.  */
4284       hi = h;
4285       while (h->root.type == bfd_link_hash_indirect
4286              || h->root.type == bfd_link_hash_warning)
4287         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4288
4289       *sym_hash = h;
4290
4291       new_weak = (flags & BSF_WEAK) != 0;
4292       new_weakdef = FALSE;
4293       if (dynamic
4294           && definition
4295           && new_weak
4296           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4297           && is_elf_hash_table (htab)
4298           && h->u.weakdef == NULL)
4299         {
4300           /* Keep a list of all weak defined non function symbols from
4301              a dynamic object, using the weakdef field.  Later in this
4302              function we will set the weakdef field to the correct
4303              value.  We only put non-function symbols from dynamic
4304              objects on this list, because that happens to be the only
4305              time we need to know the normal symbol corresponding to a
4306              weak symbol, and the information is time consuming to
4307              figure out.  If the weakdef field is not already NULL,
4308              then this symbol was already defined by some previous
4309              dynamic object, and we will be using that previous
4310              definition anyhow.  */
4311
4312           h->u.weakdef = weaks;
4313           weaks = h;
4314           new_weakdef = TRUE;
4315         }
4316
4317       /* Set the alignment of a common symbol.  */
4318       if ((common || bfd_is_com_section (sec))
4319           && h->root.type == bfd_link_hash_common)
4320         {
4321           unsigned int align;
4322
4323           if (common)
4324             align = bfd_log2 (isym->st_value);
4325           else
4326             {
4327               /* The new symbol is a common symbol in a shared object.
4328                  We need to get the alignment from the section.  */
4329               align = new_sec->alignment_power;
4330             }
4331           if (align > old_alignment)
4332             h->root.u.c.p->alignment_power = align;
4333           else
4334             h->root.u.c.p->alignment_power = old_alignment;
4335         }
4336
4337       if (is_elf_hash_table (htab))
4338         {
4339           /* Set a flag in the hash table entry indicating the type of
4340              reference or definition we just found.  A dynamic symbol
4341              is one which is referenced or defined by both a regular
4342              object and a shared object.  */
4343           bfd_boolean dynsym = FALSE;
4344
4345           /* Plugin symbols aren't normal.  Don't set def_regular or
4346              ref_regular for them, or make them dynamic.  */
4347           if ((abfd->flags & BFD_PLUGIN) != 0)
4348             ;
4349           else if (! dynamic)
4350             {
4351               if (! definition)
4352                 {
4353                   h->ref_regular = 1;
4354                   if (bind != STB_WEAK)
4355                     h->ref_regular_nonweak = 1;
4356                 }
4357               else
4358                 {
4359                   h->def_regular = 1;
4360                   if (h->def_dynamic)
4361                     {
4362                       h->def_dynamic = 0;
4363                       h->ref_dynamic = 1;
4364                     }
4365                 }
4366
4367               /* If the indirect symbol has been forced local, don't
4368                  make the real symbol dynamic.  */
4369               if ((h == hi || !hi->forced_local)
4370                   && (bfd_link_dll (info)
4371                       || h->def_dynamic
4372                       || h->ref_dynamic))
4373                 dynsym = TRUE;
4374             }
4375           else
4376             {
4377               if (! definition)
4378                 {
4379                   h->ref_dynamic = 1;
4380                   hi->ref_dynamic = 1;
4381                 }
4382               else
4383                 {
4384                   h->def_dynamic = 1;
4385                   hi->def_dynamic = 1;
4386                 }
4387
4388               /* If the indirect symbol has been forced local, don't
4389                  make the real symbol dynamic.  */
4390               if ((h == hi || !hi->forced_local)
4391                   && (h->def_regular
4392                       || h->ref_regular
4393                       || (h->u.weakdef != NULL
4394                           && ! new_weakdef
4395                           && h->u.weakdef->dynindx != -1)))
4396                 dynsym = TRUE;
4397             }
4398
4399           /* Check to see if we need to add an indirect symbol for
4400              the default name.  */
4401           if (definition
4402               || (!override && h->root.type == bfd_link_hash_common))
4403             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4404                                               sec, value, &old_bfd, &dynsym))
4405               goto error_free_vers;
4406
4407           /* Check the alignment when a common symbol is involved. This
4408              can change when a common symbol is overridden by a normal
4409              definition or a common symbol is ignored due to the old
4410              normal definition. We need to make sure the maximum
4411              alignment is maintained.  */
4412           if ((old_alignment || common)
4413               && h->root.type != bfd_link_hash_common)
4414             {
4415               unsigned int common_align;
4416               unsigned int normal_align;
4417               unsigned int symbol_align;
4418               bfd *normal_bfd;
4419               bfd *common_bfd;
4420
4421               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4422                           || h->root.type == bfd_link_hash_defweak);
4423
4424               symbol_align = ffs (h->root.u.def.value) - 1;
4425               if (h->root.u.def.section->owner != NULL
4426                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4427                 {
4428                   normal_align = h->root.u.def.section->alignment_power;
4429                   if (normal_align > symbol_align)
4430                     normal_align = symbol_align;
4431                 }
4432               else
4433                 normal_align = symbol_align;
4434
4435               if (old_alignment)
4436                 {
4437                   common_align = old_alignment;
4438                   common_bfd = old_bfd;
4439                   normal_bfd = abfd;
4440                 }
4441               else
4442                 {
4443                   common_align = bfd_log2 (isym->st_value);
4444                   common_bfd = abfd;
4445                   normal_bfd = old_bfd;
4446                 }
4447
4448               if (normal_align < common_align)
4449                 {
4450                   /* PR binutils/2735 */
4451                   if (normal_bfd == NULL)
4452                     (*_bfd_error_handler)
4453                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4454                          " greater than the alignment (%u) of its section %A"),
4455                        common_bfd, h->root.u.def.section,
4456                        1 << common_align, name, 1 << normal_align);
4457                   else
4458                     (*_bfd_error_handler)
4459                       (_("Warning: alignment %u of symbol `%s' in %B"
4460                          " is smaller than %u in %B"),
4461                        normal_bfd, common_bfd,
4462                        1 << normal_align, name, 1 << common_align);
4463                 }
4464             }
4465
4466           /* Remember the symbol size if it isn't undefined.  */
4467           if (isym->st_size != 0
4468               && isym->st_shndx != SHN_UNDEF
4469               && (definition || h->size == 0))
4470             {
4471               if (h->size != 0
4472                   && h->size != isym->st_size
4473                   && ! size_change_ok)
4474                 (*_bfd_error_handler)
4475                   (_("Warning: size of symbol `%s' changed"
4476                      " from %lu in %B to %lu in %B"),
4477                    old_bfd, abfd,
4478                    name, (unsigned long) h->size,
4479                    (unsigned long) isym->st_size);
4480
4481               h->size = isym->st_size;
4482             }
4483
4484           /* If this is a common symbol, then we always want H->SIZE
4485              to be the size of the common symbol.  The code just above
4486              won't fix the size if a common symbol becomes larger.  We
4487              don't warn about a size change here, because that is
4488              covered by --warn-common.  Allow changes between different
4489              function types.  */
4490           if (h->root.type == bfd_link_hash_common)
4491             h->size = h->root.u.c.size;
4492
4493           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4494               && ((definition && !new_weak)
4495                   || (old_weak && h->root.type == bfd_link_hash_common)
4496                   || h->type == STT_NOTYPE))
4497             {
4498               unsigned int type = ELF_ST_TYPE (isym->st_info);
4499
4500               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4501                  symbol.  */
4502               if (type == STT_GNU_IFUNC
4503                   && (abfd->flags & DYNAMIC) != 0)
4504                 type = STT_FUNC;
4505
4506               if (h->type != type)
4507                 {
4508                   if (h->type != STT_NOTYPE && ! type_change_ok)
4509                     (*_bfd_error_handler)
4510                       (_("Warning: type of symbol `%s' changed"
4511                          " from %d to %d in %B"),
4512                        abfd, name, h->type, type);
4513
4514                   h->type = type;
4515                 }
4516             }
4517
4518           /* Merge st_other field.  */
4519           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4520
4521           /* We don't want to make debug symbol dynamic.  */
4522           if (definition
4523               && (sec->flags & SEC_DEBUGGING)
4524               && !bfd_link_relocatable (info))
4525             dynsym = FALSE;
4526
4527           /* Nor should we make plugin symbols dynamic.  */
4528           if ((abfd->flags & BFD_PLUGIN) != 0)
4529             dynsym = FALSE;
4530
4531           if (definition)
4532             {
4533               h->target_internal = isym->st_target_internal;
4534               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4535             }
4536
4537           if (definition && !dynamic)
4538             {
4539               char *p = strchr (name, ELF_VER_CHR);
4540               if (p != NULL && p[1] != ELF_VER_CHR)
4541                 {
4542                   /* Queue non-default versions so that .symver x, x@FOO
4543                      aliases can be checked.  */
4544                   if (!nondeflt_vers)
4545                     {
4546                       amt = ((isymend - isym + 1)
4547                              * sizeof (struct elf_link_hash_entry *));
4548                       nondeflt_vers
4549                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4550                       if (!nondeflt_vers)
4551                         goto error_free_vers;
4552                     }
4553                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4554                 }
4555             }
4556
4557           if (dynsym && h->dynindx == -1)
4558             {
4559               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4560                 goto error_free_vers;
4561               if (h->u.weakdef != NULL
4562                   && ! new_weakdef
4563                   && h->u.weakdef->dynindx == -1)
4564                 {
4565                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4566                     goto error_free_vers;
4567                 }
4568             }
4569           else if (dynsym && h->dynindx != -1)
4570             /* If the symbol already has a dynamic index, but
4571                visibility says it should not be visible, turn it into
4572                a local symbol.  */
4573             switch (ELF_ST_VISIBILITY (h->other))
4574               {
4575               case STV_INTERNAL:
4576               case STV_HIDDEN:
4577                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4578                 dynsym = FALSE;
4579                 break;
4580               }
4581
4582           /* Don't add DT_NEEDED for references from the dummy bfd nor
4583              for unmatched symbol.  */
4584           if (!add_needed
4585               && matched
4586               && definition
4587               && ((dynsym
4588                    && h->ref_regular_nonweak
4589                    && (old_bfd == NULL
4590                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4591                   || (h->ref_dynamic_nonweak
4592                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4593                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4594             {
4595               int ret;
4596               const char *soname = elf_dt_name (abfd);
4597
4598               info->callbacks->minfo ("%!", soname, old_bfd,
4599                                       h->root.root.string);
4600
4601               /* A symbol from a library loaded via DT_NEEDED of some
4602                  other library is referenced by a regular object.
4603                  Add a DT_NEEDED entry for it.  Issue an error if
4604                  --no-add-needed is used and the reference was not
4605                  a weak one.  */
4606               if (old_bfd != NULL
4607                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4608                 {
4609                   (*_bfd_error_handler)
4610                     (_("%B: undefined reference to symbol '%s'"),
4611                      old_bfd, name);
4612                   bfd_set_error (bfd_error_missing_dso);
4613                   goto error_free_vers;
4614                 }
4615
4616               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4617                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4618
4619               add_needed = TRUE;
4620               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4621               if (ret < 0)
4622                 goto error_free_vers;
4623
4624               BFD_ASSERT (ret == 0);
4625             }
4626         }
4627     }
4628
4629   if (extversym != NULL)
4630     {
4631       free (extversym);
4632       extversym = NULL;
4633     }
4634
4635   if (isymbuf != NULL)
4636     {
4637       free (isymbuf);
4638       isymbuf = NULL;
4639     }
4640
4641   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4642     {
4643       unsigned int i;
4644
4645       /* Restore the symbol table.  */
4646       old_ent = (char *) old_tab + tabsize;
4647       memset (elf_sym_hashes (abfd), 0,
4648               extsymcount * sizeof (struct elf_link_hash_entry *));
4649       htab->root.table.table = old_table;
4650       htab->root.table.size = old_size;
4651       htab->root.table.count = old_count;
4652       memcpy (htab->root.table.table, old_tab, tabsize);
4653       htab->root.undefs = old_undefs;
4654       htab->root.undefs_tail = old_undefs_tail;
4655       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4656       for (i = 0; i < htab->root.table.size; i++)
4657         {
4658           struct bfd_hash_entry *p;
4659           struct elf_link_hash_entry *h;
4660           bfd_size_type size;
4661           unsigned int alignment_power;
4662
4663           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4664             {
4665               h = (struct elf_link_hash_entry *) p;
4666               if (h->root.type == bfd_link_hash_warning)
4667                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4668               if (h->dynindx >= old_dynsymcount
4669                   && h->dynstr_index < old_dynstr_size)
4670                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4671
4672               /* Preserve the maximum alignment and size for common
4673                  symbols even if this dynamic lib isn't on DT_NEEDED
4674                  since it can still be loaded at run time by another
4675                  dynamic lib.  */
4676               if (h->root.type == bfd_link_hash_common)
4677                 {
4678                   size = h->root.u.c.size;
4679                   alignment_power = h->root.u.c.p->alignment_power;
4680                 }
4681               else
4682                 {
4683                   size = 0;
4684                   alignment_power = 0;
4685                 }
4686               memcpy (p, old_ent, htab->root.table.entsize);
4687               old_ent = (char *) old_ent + htab->root.table.entsize;
4688               h = (struct elf_link_hash_entry *) p;
4689               if (h->root.type == bfd_link_hash_warning)
4690                 {
4691                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4692                   old_ent = (char *) old_ent + htab->root.table.entsize;
4693                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4694                 }
4695               if (h->root.type == bfd_link_hash_common)
4696                 {
4697                   if (size > h->root.u.c.size)
4698                     h->root.u.c.size = size;
4699                   if (alignment_power > h->root.u.c.p->alignment_power)
4700                     h->root.u.c.p->alignment_power = alignment_power;
4701                 }
4702             }
4703         }
4704
4705       /* Make a special call to the linker "notice" function to
4706          tell it that symbols added for crefs may need to be removed.  */
4707       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4708         goto error_free_vers;
4709
4710       free (old_tab);
4711       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4712                            alloc_mark);
4713       if (nondeflt_vers != NULL)
4714         free (nondeflt_vers);
4715       return TRUE;
4716     }
4717
4718   if (old_tab != NULL)
4719     {
4720       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4721         goto error_free_vers;
4722       free (old_tab);
4723       old_tab = NULL;
4724     }
4725
4726   /* Now that all the symbols from this input file are created, if
4727      not performing a relocatable link, handle .symver foo, foo@BAR
4728      such that any relocs against foo become foo@BAR.  */
4729   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4730     {
4731       bfd_size_type cnt, symidx;
4732
4733       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4734         {
4735           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4736           char *shortname, *p;
4737
4738           p = strchr (h->root.root.string, ELF_VER_CHR);
4739           if (p == NULL
4740               || (h->root.type != bfd_link_hash_defined
4741                   && h->root.type != bfd_link_hash_defweak))
4742             continue;
4743
4744           amt = p - h->root.root.string;
4745           shortname = (char *) bfd_malloc (amt + 1);
4746           if (!shortname)
4747             goto error_free_vers;
4748           memcpy (shortname, h->root.root.string, amt);
4749           shortname[amt] = '\0';
4750
4751           hi = (struct elf_link_hash_entry *)
4752                bfd_link_hash_lookup (&htab->root, shortname,
4753                                      FALSE, FALSE, FALSE);
4754           if (hi != NULL
4755               && hi->root.type == h->root.type
4756               && hi->root.u.def.value == h->root.u.def.value
4757               && hi->root.u.def.section == h->root.u.def.section)
4758             {
4759               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4760               hi->root.type = bfd_link_hash_indirect;
4761               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4762               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4763               sym_hash = elf_sym_hashes (abfd);
4764               if (sym_hash)
4765                 for (symidx = 0; symidx < extsymcount; ++symidx)
4766                   if (sym_hash[symidx] == hi)
4767                     {
4768                       sym_hash[symidx] = h;
4769                       break;
4770                     }
4771             }
4772           free (shortname);
4773         }
4774       free (nondeflt_vers);
4775       nondeflt_vers = NULL;
4776     }
4777
4778   /* Now set the weakdefs field correctly for all the weak defined
4779      symbols we found.  The only way to do this is to search all the
4780      symbols.  Since we only need the information for non functions in
4781      dynamic objects, that's the only time we actually put anything on
4782      the list WEAKS.  We need this information so that if a regular
4783      object refers to a symbol defined weakly in a dynamic object, the
4784      real symbol in the dynamic object is also put in the dynamic
4785      symbols; we also must arrange for both symbols to point to the
4786      same memory location.  We could handle the general case of symbol
4787      aliasing, but a general symbol alias can only be generated in
4788      assembler code, handling it correctly would be very time
4789      consuming, and other ELF linkers don't handle general aliasing
4790      either.  */
4791   if (weaks != NULL)
4792     {
4793       struct elf_link_hash_entry **hpp;
4794       struct elf_link_hash_entry **hppend;
4795       struct elf_link_hash_entry **sorted_sym_hash;
4796       struct elf_link_hash_entry *h;
4797       size_t sym_count;
4798
4799       /* Since we have to search the whole symbol list for each weak
4800          defined symbol, search time for N weak defined symbols will be
4801          O(N^2). Binary search will cut it down to O(NlogN).  */
4802       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4803       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4804       if (sorted_sym_hash == NULL)
4805         goto error_return;
4806       sym_hash = sorted_sym_hash;
4807       hpp = elf_sym_hashes (abfd);
4808       hppend = hpp + extsymcount;
4809       sym_count = 0;
4810       for (; hpp < hppend; hpp++)
4811         {
4812           h = *hpp;
4813           if (h != NULL
4814               && h->root.type == bfd_link_hash_defined
4815               && !bed->is_function_type (h->type))
4816             {
4817               *sym_hash = h;
4818               sym_hash++;
4819               sym_count++;
4820             }
4821         }
4822
4823       qsort (sorted_sym_hash, sym_count,
4824              sizeof (struct elf_link_hash_entry *),
4825              elf_sort_symbol);
4826
4827       while (weaks != NULL)
4828         {
4829           struct elf_link_hash_entry *hlook;
4830           asection *slook;
4831           bfd_vma vlook;
4832           size_t i, j, idx = 0;
4833
4834           hlook = weaks;
4835           weaks = hlook->u.weakdef;
4836           hlook->u.weakdef = NULL;
4837
4838           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4839                       || hlook->root.type == bfd_link_hash_defweak
4840                       || hlook->root.type == bfd_link_hash_common
4841                       || hlook->root.type == bfd_link_hash_indirect);
4842           slook = hlook->root.u.def.section;
4843           vlook = hlook->root.u.def.value;
4844
4845           i = 0;
4846           j = sym_count;
4847           while (i != j)
4848             {
4849               bfd_signed_vma vdiff;
4850               idx = (i + j) / 2;
4851               h = sorted_sym_hash[idx];
4852               vdiff = vlook - h->root.u.def.value;
4853               if (vdiff < 0)
4854                 j = idx;
4855               else if (vdiff > 0)
4856                 i = idx + 1;
4857               else
4858                 {
4859                   int sdiff = slook->id - h->root.u.def.section->id;
4860                   if (sdiff < 0)
4861                     j = idx;
4862                   else if (sdiff > 0)
4863                     i = idx + 1;
4864                   else
4865                     break;
4866                 }
4867             }
4868
4869           /* We didn't find a value/section match.  */
4870           if (i == j)
4871             continue;
4872
4873           /* With multiple aliases, or when the weak symbol is already
4874              strongly defined, we have multiple matching symbols and
4875              the binary search above may land on any of them.  Step
4876              one past the matching symbol(s).  */
4877           while (++idx != j)
4878             {
4879               h = sorted_sym_hash[idx];
4880               if (h->root.u.def.section != slook
4881                   || h->root.u.def.value != vlook)
4882                 break;
4883             }
4884
4885           /* Now look back over the aliases.  Since we sorted by size
4886              as well as value and section, we'll choose the one with
4887              the largest size.  */
4888           while (idx-- != i)
4889             {
4890               h = sorted_sym_hash[idx];
4891
4892               /* Stop if value or section doesn't match.  */
4893               if (h->root.u.def.section != slook
4894                   || h->root.u.def.value != vlook)
4895                 break;
4896               else if (h != hlook)
4897                 {
4898                   hlook->u.weakdef = h;
4899
4900                   /* If the weak definition is in the list of dynamic
4901                      symbols, make sure the real definition is put
4902                      there as well.  */
4903                   if (hlook->dynindx != -1 && h->dynindx == -1)
4904                     {
4905                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4906                         {
4907                         err_free_sym_hash:
4908                           free (sorted_sym_hash);
4909                           goto error_return;
4910                         }
4911                     }
4912
4913                   /* If the real definition is in the list of dynamic
4914                      symbols, make sure the weak definition is put
4915                      there as well.  If we don't do this, then the
4916                      dynamic loader might not merge the entries for the
4917                      real definition and the weak definition.  */
4918                   if (h->dynindx != -1 && hlook->dynindx == -1)
4919                     {
4920                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4921                         goto err_free_sym_hash;
4922                     }
4923                   break;
4924                 }
4925             }
4926         }
4927
4928       free (sorted_sym_hash);
4929     }
4930
4931   if (bed->check_directives
4932       && !(*bed->check_directives) (abfd, info))
4933     return FALSE;
4934
4935   /* If this object is the same format as the output object, and it is
4936      not a shared library, then let the backend look through the
4937      relocs.
4938
4939      This is required to build global offset table entries and to
4940      arrange for dynamic relocs.  It is not required for the
4941      particular common case of linking non PIC code, even when linking
4942      against shared libraries, but unfortunately there is no way of
4943      knowing whether an object file has been compiled PIC or not.
4944      Looking through the relocs is not particularly time consuming.
4945      The problem is that we must either (1) keep the relocs in memory,
4946      which causes the linker to require additional runtime memory or
4947      (2) read the relocs twice from the input file, which wastes time.
4948      This would be a good case for using mmap.
4949
4950      I have no idea how to handle linking PIC code into a file of a
4951      different format.  It probably can't be done.  */
4952   if (! dynamic
4953       && is_elf_hash_table (htab)
4954       && bed->check_relocs != NULL
4955       && elf_object_id (abfd) == elf_hash_table_id (htab)
4956       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4957     {
4958       asection *o;
4959
4960       for (o = abfd->sections; o != NULL; o = o->next)
4961         {
4962           Elf_Internal_Rela *internal_relocs;
4963           bfd_boolean ok;
4964
4965           if ((o->flags & SEC_RELOC) == 0
4966               || o->reloc_count == 0
4967               || ((info->strip == strip_all || info->strip == strip_debugger)
4968                   && (o->flags & SEC_DEBUGGING) != 0)
4969               || bfd_is_abs_section (o->output_section))
4970             continue;
4971
4972           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4973                                                        info->keep_memory);
4974           if (internal_relocs == NULL)
4975             goto error_return;
4976
4977           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4978
4979           if (elf_section_data (o)->relocs != internal_relocs)
4980             free (internal_relocs);
4981
4982           if (! ok)
4983             goto error_return;
4984         }
4985     }
4986
4987   /* If this is a non-traditional link, try to optimize the handling
4988      of the .stab/.stabstr sections.  */
4989   if (! dynamic
4990       && ! info->traditional_format
4991       && is_elf_hash_table (htab)
4992       && (info->strip != strip_all && info->strip != strip_debugger))
4993     {
4994       asection *stabstr;
4995
4996       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4997       if (stabstr != NULL)
4998         {
4999           bfd_size_type string_offset = 0;
5000           asection *stab;
5001
5002           for (stab = abfd->sections; stab; stab = stab->next)
5003             if (CONST_STRNEQ (stab->name, ".stab")
5004                 && (!stab->name[5] ||
5005                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5006                 && (stab->flags & SEC_MERGE) == 0
5007                 && !bfd_is_abs_section (stab->output_section))
5008               {
5009                 struct bfd_elf_section_data *secdata;
5010
5011                 secdata = elf_section_data (stab);
5012                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5013                                                stabstr, &secdata->sec_info,
5014                                                &string_offset))
5015                   goto error_return;
5016                 if (secdata->sec_info)
5017                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5018             }
5019         }
5020     }
5021
5022   if (is_elf_hash_table (htab) && add_needed)
5023     {
5024       /* Add this bfd to the loaded list.  */
5025       struct elf_link_loaded_list *n;
5026
5027       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5028       if (n == NULL)
5029         goto error_return;
5030       n->abfd = abfd;
5031       n->next = htab->loaded;
5032       htab->loaded = n;
5033     }
5034
5035   return TRUE;
5036
5037  error_free_vers:
5038   if (old_tab != NULL)
5039     free (old_tab);
5040   if (nondeflt_vers != NULL)
5041     free (nondeflt_vers);
5042   if (extversym != NULL)
5043     free (extversym);
5044  error_free_sym:
5045   if (isymbuf != NULL)
5046     free (isymbuf);
5047  error_return:
5048   return FALSE;
5049 }
5050
5051 /* Return the linker hash table entry of a symbol that might be
5052    satisfied by an archive symbol.  Return -1 on error.  */
5053
5054 struct elf_link_hash_entry *
5055 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5056                                 struct bfd_link_info *info,
5057                                 const char *name)
5058 {
5059   struct elf_link_hash_entry *h;
5060   char *p, *copy;
5061   size_t len, first;
5062
5063   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5064   if (h != NULL)
5065     return h;
5066
5067   /* If this is a default version (the name contains @@), look up the
5068      symbol again with only one `@' as well as without the version.
5069      The effect is that references to the symbol with and without the
5070      version will be matched by the default symbol in the archive.  */
5071
5072   p = strchr (name, ELF_VER_CHR);
5073   if (p == NULL || p[1] != ELF_VER_CHR)
5074     return h;
5075
5076   /* First check with only one `@'.  */
5077   len = strlen (name);
5078   copy = (char *) bfd_alloc (abfd, len);
5079   if (copy == NULL)
5080     return (struct elf_link_hash_entry *) 0 - 1;
5081
5082   first = p - name + 1;
5083   memcpy (copy, name, first);
5084   memcpy (copy + first, name + first + 1, len - first);
5085
5086   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5087   if (h == NULL)
5088     {
5089       /* We also need to check references to the symbol without the
5090          version.  */
5091       copy[first - 1] = '\0';
5092       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5093                                 FALSE, FALSE, TRUE);
5094     }
5095
5096   bfd_release (abfd, copy);
5097   return h;
5098 }
5099
5100 /* Add symbols from an ELF archive file to the linker hash table.  We
5101    don't use _bfd_generic_link_add_archive_symbols because we need to
5102    handle versioned symbols.
5103
5104    Fortunately, ELF archive handling is simpler than that done by
5105    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5106    oddities.  In ELF, if we find a symbol in the archive map, and the
5107    symbol is currently undefined, we know that we must pull in that
5108    object file.
5109
5110    Unfortunately, we do have to make multiple passes over the symbol
5111    table until nothing further is resolved.  */
5112
5113 static bfd_boolean
5114 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5115 {
5116   symindex c;
5117   unsigned char *included = NULL;
5118   carsym *symdefs;
5119   bfd_boolean loop;
5120   bfd_size_type amt;
5121   const struct elf_backend_data *bed;
5122   struct elf_link_hash_entry * (*archive_symbol_lookup)
5123     (bfd *, struct bfd_link_info *, const char *);
5124
5125   if (! bfd_has_map (abfd))
5126     {
5127       /* An empty archive is a special case.  */
5128       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5129         return TRUE;
5130       bfd_set_error (bfd_error_no_armap);
5131       return FALSE;
5132     }
5133
5134   /* Keep track of all symbols we know to be already defined, and all
5135      files we know to be already included.  This is to speed up the
5136      second and subsequent passes.  */
5137   c = bfd_ardata (abfd)->symdef_count;
5138   if (c == 0)
5139     return TRUE;
5140   amt = c;
5141   amt *= sizeof (*included);
5142   included = (unsigned char *) bfd_zmalloc (amt);
5143   if (included == NULL)
5144     return FALSE;
5145
5146   symdefs = bfd_ardata (abfd)->symdefs;
5147   bed = get_elf_backend_data (abfd);
5148   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5149
5150   do
5151     {
5152       file_ptr last;
5153       symindex i;
5154       carsym *symdef;
5155       carsym *symdefend;
5156
5157       loop = FALSE;
5158       last = -1;
5159
5160       symdef = symdefs;
5161       symdefend = symdef + c;
5162       for (i = 0; symdef < symdefend; symdef++, i++)
5163         {
5164           struct elf_link_hash_entry *h;
5165           bfd *element;
5166           struct bfd_link_hash_entry *undefs_tail;
5167           symindex mark;
5168
5169           if (included[i])
5170             continue;
5171           if (symdef->file_offset == last)
5172             {
5173               included[i] = TRUE;
5174               continue;
5175             }
5176
5177           h = archive_symbol_lookup (abfd, info, symdef->name);
5178           if (h == (struct elf_link_hash_entry *) 0 - 1)
5179             goto error_return;
5180
5181           if (h == NULL)
5182             continue;
5183
5184           if (h->root.type == bfd_link_hash_common)
5185             {
5186               /* We currently have a common symbol.  The archive map contains
5187                  a reference to this symbol, so we may want to include it.  We
5188                  only want to include it however, if this archive element
5189                  contains a definition of the symbol, not just another common
5190                  declaration of it.
5191
5192                  Unfortunately some archivers (including GNU ar) will put
5193                  declarations of common symbols into their archive maps, as
5194                  well as real definitions, so we cannot just go by the archive
5195                  map alone.  Instead we must read in the element's symbol
5196                  table and check that to see what kind of symbol definition
5197                  this is.  */
5198               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5199                 continue;
5200             }
5201           else if (h->root.type != bfd_link_hash_undefined)
5202             {
5203               if (h->root.type != bfd_link_hash_undefweak)
5204                 /* Symbol must be defined.  Don't check it again.  */
5205                 included[i] = TRUE;
5206               continue;
5207             }
5208
5209           /* We need to include this archive member.  */
5210           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5211           if (element == NULL)
5212             goto error_return;
5213
5214           if (! bfd_check_format (element, bfd_object))
5215             goto error_return;
5216
5217           undefs_tail = info->hash->undefs_tail;
5218
5219           if (!(*info->callbacks
5220                 ->add_archive_element) (info, element, symdef->name, &element))
5221             goto error_return;
5222           if (!bfd_link_add_symbols (element, info))
5223             goto error_return;
5224
5225           /* If there are any new undefined symbols, we need to make
5226              another pass through the archive in order to see whether
5227              they can be defined.  FIXME: This isn't perfect, because
5228              common symbols wind up on undefs_tail and because an
5229              undefined symbol which is defined later on in this pass
5230              does not require another pass.  This isn't a bug, but it
5231              does make the code less efficient than it could be.  */
5232           if (undefs_tail != info->hash->undefs_tail)
5233             loop = TRUE;
5234
5235           /* Look backward to mark all symbols from this object file
5236              which we have already seen in this pass.  */
5237           mark = i;
5238           do
5239             {
5240               included[mark] = TRUE;
5241               if (mark == 0)
5242                 break;
5243               --mark;
5244             }
5245           while (symdefs[mark].file_offset == symdef->file_offset);
5246
5247           /* We mark subsequent symbols from this object file as we go
5248              on through the loop.  */
5249           last = symdef->file_offset;
5250         }
5251     }
5252   while (loop);
5253
5254   free (included);
5255
5256   return TRUE;
5257
5258  error_return:
5259   if (included != NULL)
5260     free (included);
5261   return FALSE;
5262 }
5263
5264 /* Given an ELF BFD, add symbols to the global hash table as
5265    appropriate.  */
5266
5267 bfd_boolean
5268 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5269 {
5270   switch (bfd_get_format (abfd))
5271     {
5272     case bfd_object:
5273       return elf_link_add_object_symbols (abfd, info);
5274     case bfd_archive:
5275       return elf_link_add_archive_symbols (abfd, info);
5276     default:
5277       bfd_set_error (bfd_error_wrong_format);
5278       return FALSE;
5279     }
5280 }
5281 \f
5282 struct hash_codes_info
5283 {
5284   unsigned long *hashcodes;
5285   bfd_boolean error;
5286 };
5287
5288 /* This function will be called though elf_link_hash_traverse to store
5289    all hash value of the exported symbols in an array.  */
5290
5291 static bfd_boolean
5292 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5293 {
5294   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5295   const char *name;
5296   unsigned long ha;
5297   char *alc = NULL;
5298
5299   /* Ignore indirect symbols.  These are added by the versioning code.  */
5300   if (h->dynindx == -1)
5301     return TRUE;
5302
5303   name = h->root.root.string;
5304   if (h->versioned >= versioned)
5305     {
5306       char *p = strchr (name, ELF_VER_CHR);
5307       if (p != NULL)
5308         {
5309           alc = (char *) bfd_malloc (p - name + 1);
5310           if (alc == NULL)
5311             {
5312               inf->error = TRUE;
5313               return FALSE;
5314             }
5315           memcpy (alc, name, p - name);
5316           alc[p - name] = '\0';
5317           name = alc;
5318         }
5319     }
5320
5321   /* Compute the hash value.  */
5322   ha = bfd_elf_hash (name);
5323
5324   /* Store the found hash value in the array given as the argument.  */
5325   *(inf->hashcodes)++ = ha;
5326
5327   /* And store it in the struct so that we can put it in the hash table
5328      later.  */
5329   h->u.elf_hash_value = ha;
5330
5331   if (alc != NULL)
5332     free (alc);
5333
5334   return TRUE;
5335 }
5336
5337 struct collect_gnu_hash_codes
5338 {
5339   bfd *output_bfd;
5340   const struct elf_backend_data *bed;
5341   unsigned long int nsyms;
5342   unsigned long int maskbits;
5343   unsigned long int *hashcodes;
5344   unsigned long int *hashval;
5345   unsigned long int *indx;
5346   unsigned long int *counts;
5347   bfd_vma *bitmask;
5348   bfd_byte *contents;
5349   long int min_dynindx;
5350   unsigned long int bucketcount;
5351   unsigned long int symindx;
5352   long int local_indx;
5353   long int shift1, shift2;
5354   unsigned long int mask;
5355   bfd_boolean error;
5356 };
5357
5358 /* This function will be called though elf_link_hash_traverse to store
5359    all hash value of the exported symbols in an array.  */
5360
5361 static bfd_boolean
5362 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5363 {
5364   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5365   const char *name;
5366   unsigned long ha;
5367   char *alc = NULL;
5368
5369   /* Ignore indirect symbols.  These are added by the versioning code.  */
5370   if (h->dynindx == -1)
5371     return TRUE;
5372
5373   /* Ignore also local symbols and undefined symbols.  */
5374   if (! (*s->bed->elf_hash_symbol) (h))
5375     return TRUE;
5376
5377   name = h->root.root.string;
5378   if (h->versioned >= versioned)
5379     {
5380       char *p = strchr (name, ELF_VER_CHR);
5381       if (p != NULL)
5382         {
5383           alc = (char *) bfd_malloc (p - name + 1);
5384           if (alc == NULL)
5385             {
5386               s->error = TRUE;
5387               return FALSE;
5388             }
5389           memcpy (alc, name, p - name);
5390           alc[p - name] = '\0';
5391           name = alc;
5392         }
5393     }
5394
5395   /* Compute the hash value.  */
5396   ha = bfd_elf_gnu_hash (name);
5397
5398   /* Store the found hash value in the array for compute_bucket_count,
5399      and also for .dynsym reordering purposes.  */
5400   s->hashcodes[s->nsyms] = ha;
5401   s->hashval[h->dynindx] = ha;
5402   ++s->nsyms;
5403   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5404     s->min_dynindx = h->dynindx;
5405
5406   if (alc != NULL)
5407     free (alc);
5408
5409   return TRUE;
5410 }
5411
5412 /* This function will be called though elf_link_hash_traverse to do
5413    final dynaminc symbol renumbering.  */
5414
5415 static bfd_boolean
5416 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5417 {
5418   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5419   unsigned long int bucket;
5420   unsigned long int val;
5421
5422   /* Ignore indirect symbols.  */
5423   if (h->dynindx == -1)
5424     return TRUE;
5425
5426   /* Ignore also local symbols and undefined symbols.  */
5427   if (! (*s->bed->elf_hash_symbol) (h))
5428     {
5429       if (h->dynindx >= s->min_dynindx)
5430         h->dynindx = s->local_indx++;
5431       return TRUE;
5432     }
5433
5434   bucket = s->hashval[h->dynindx] % s->bucketcount;
5435   val = (s->hashval[h->dynindx] >> s->shift1)
5436         & ((s->maskbits >> s->shift1) - 1);
5437   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5438   s->bitmask[val]
5439     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5440   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5441   if (s->counts[bucket] == 1)
5442     /* Last element terminates the chain.  */
5443     val |= 1;
5444   bfd_put_32 (s->output_bfd, val,
5445               s->contents + (s->indx[bucket] - s->symindx) * 4);
5446   --s->counts[bucket];
5447   h->dynindx = s->indx[bucket]++;
5448   return TRUE;
5449 }
5450
5451 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5452
5453 bfd_boolean
5454 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5455 {
5456   return !(h->forced_local
5457            || h->root.type == bfd_link_hash_undefined
5458            || h->root.type == bfd_link_hash_undefweak
5459            || ((h->root.type == bfd_link_hash_defined
5460                 || h->root.type == bfd_link_hash_defweak)
5461                && h->root.u.def.section->output_section == NULL));
5462 }
5463
5464 /* Array used to determine the number of hash table buckets to use
5465    based on the number of symbols there are.  If there are fewer than
5466    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5467    fewer than 37 we use 17 buckets, and so forth.  We never use more
5468    than 32771 buckets.  */
5469
5470 static const size_t elf_buckets[] =
5471 {
5472   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5473   16411, 32771, 0
5474 };
5475
5476 /* Compute bucket count for hashing table.  We do not use a static set
5477    of possible tables sizes anymore.  Instead we determine for all
5478    possible reasonable sizes of the table the outcome (i.e., the
5479    number of collisions etc) and choose the best solution.  The
5480    weighting functions are not too simple to allow the table to grow
5481    without bounds.  Instead one of the weighting factors is the size.
5482    Therefore the result is always a good payoff between few collisions
5483    (= short chain lengths) and table size.  */
5484 static size_t
5485 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5486                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5487                       unsigned long int nsyms,
5488                       int gnu_hash)
5489 {
5490   size_t best_size = 0;
5491   unsigned long int i;
5492
5493   /* We have a problem here.  The following code to optimize the table
5494      size requires an integer type with more the 32 bits.  If
5495      BFD_HOST_U_64_BIT is set we know about such a type.  */
5496 #ifdef BFD_HOST_U_64_BIT
5497   if (info->optimize)
5498     {
5499       size_t minsize;
5500       size_t maxsize;
5501       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5502       bfd *dynobj = elf_hash_table (info)->dynobj;
5503       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5504       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5505       unsigned long int *counts;
5506       bfd_size_type amt;
5507       unsigned int no_improvement_count = 0;
5508
5509       /* Possible optimization parameters: if we have NSYMS symbols we say
5510          that the hashing table must at least have NSYMS/4 and at most
5511          2*NSYMS buckets.  */
5512       minsize = nsyms / 4;
5513       if (minsize == 0)
5514         minsize = 1;
5515       best_size = maxsize = nsyms * 2;
5516       if (gnu_hash)
5517         {
5518           if (minsize < 2)
5519             minsize = 2;
5520           if ((best_size & 31) == 0)
5521             ++best_size;
5522         }
5523
5524       /* Create array where we count the collisions in.  We must use bfd_malloc
5525          since the size could be large.  */
5526       amt = maxsize;
5527       amt *= sizeof (unsigned long int);
5528       counts = (unsigned long int *) bfd_malloc (amt);
5529       if (counts == NULL)
5530         return 0;
5531
5532       /* Compute the "optimal" size for the hash table.  The criteria is a
5533          minimal chain length.  The minor criteria is (of course) the size
5534          of the table.  */
5535       for (i = minsize; i < maxsize; ++i)
5536         {
5537           /* Walk through the array of hashcodes and count the collisions.  */
5538           BFD_HOST_U_64_BIT max;
5539           unsigned long int j;
5540           unsigned long int fact;
5541
5542           if (gnu_hash && (i & 31) == 0)
5543             continue;
5544
5545           memset (counts, '\0', i * sizeof (unsigned long int));
5546
5547           /* Determine how often each hash bucket is used.  */
5548           for (j = 0; j < nsyms; ++j)
5549             ++counts[hashcodes[j] % i];
5550
5551           /* For the weight function we need some information about the
5552              pagesize on the target.  This is information need not be 100%
5553              accurate.  Since this information is not available (so far) we
5554              define it here to a reasonable default value.  If it is crucial
5555              to have a better value some day simply define this value.  */
5556 # ifndef BFD_TARGET_PAGESIZE
5557 #  define BFD_TARGET_PAGESIZE   (4096)
5558 # endif
5559
5560           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5561              and the chains.  */
5562           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5563
5564 # if 1
5565           /* Variant 1: optimize for short chains.  We add the squares
5566              of all the chain lengths (which favors many small chain
5567              over a few long chains).  */
5568           for (j = 0; j < i; ++j)
5569             max += counts[j] * counts[j];
5570
5571           /* This adds penalties for the overall size of the table.  */
5572           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5573           max *= fact * fact;
5574 # else
5575           /* Variant 2: Optimize a lot more for small table.  Here we
5576              also add squares of the size but we also add penalties for
5577              empty slots (the +1 term).  */
5578           for (j = 0; j < i; ++j)
5579             max += (1 + counts[j]) * (1 + counts[j]);
5580
5581           /* The overall size of the table is considered, but not as
5582              strong as in variant 1, where it is squared.  */
5583           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5584           max *= fact;
5585 # endif
5586
5587           /* Compare with current best results.  */
5588           if (max < best_chlen)
5589             {
5590               best_chlen = max;
5591               best_size = i;
5592               no_improvement_count = 0;
5593             }
5594           /* PR 11843: Avoid futile long searches for the best bucket size
5595              when there are a large number of symbols.  */
5596           else if (++no_improvement_count == 100)
5597             break;
5598         }
5599
5600       free (counts);
5601     }
5602   else
5603 #endif /* defined (BFD_HOST_U_64_BIT) */
5604     {
5605       /* This is the fallback solution if no 64bit type is available or if we
5606          are not supposed to spend much time on optimizations.  We select the
5607          bucket count using a fixed set of numbers.  */
5608       for (i = 0; elf_buckets[i] != 0; i++)
5609         {
5610           best_size = elf_buckets[i];
5611           if (nsyms < elf_buckets[i + 1])
5612             break;
5613         }
5614       if (gnu_hash && best_size < 2)
5615         best_size = 2;
5616     }
5617
5618   return best_size;
5619 }
5620
5621 /* Size any SHT_GROUP section for ld -r.  */
5622
5623 bfd_boolean
5624 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5625 {
5626   bfd *ibfd;
5627
5628   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5629     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5630         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5631       return FALSE;
5632   return TRUE;
5633 }
5634
5635 /* Set a default stack segment size.  The value in INFO wins.  If it
5636    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5637    undefined it is initialized.  */
5638
5639 bfd_boolean
5640 bfd_elf_stack_segment_size (bfd *output_bfd,
5641                             struct bfd_link_info *info,
5642                             const char *legacy_symbol,
5643                             bfd_vma default_size)
5644 {
5645   struct elf_link_hash_entry *h = NULL;
5646
5647   /* Look for legacy symbol.  */
5648   if (legacy_symbol)
5649     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5650                               FALSE, FALSE, FALSE);
5651   if (h && (h->root.type == bfd_link_hash_defined
5652             || h->root.type == bfd_link_hash_defweak)
5653       && h->def_regular
5654       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5655     {
5656       /* The symbol has no type if specified on the command line.  */
5657       h->type = STT_OBJECT;
5658       if (info->stacksize)
5659         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5660                                output_bfd, legacy_symbol);
5661       else if (h->root.u.def.section != bfd_abs_section_ptr)
5662         (*_bfd_error_handler) (_("%B: %s not absolute"),
5663                                output_bfd, legacy_symbol);
5664       else
5665         info->stacksize = h->root.u.def.value;
5666     }
5667
5668   if (!info->stacksize)
5669     /* If the user didn't set a size, or explicitly inhibit the
5670        size, set it now.  */
5671     info->stacksize = default_size;
5672
5673   /* Provide the legacy symbol, if it is referenced.  */
5674   if (h && (h->root.type == bfd_link_hash_undefined
5675             || h->root.type == bfd_link_hash_undefweak))
5676     {
5677       struct bfd_link_hash_entry *bh = NULL;
5678
5679       if (!(_bfd_generic_link_add_one_symbol
5680             (info, output_bfd, legacy_symbol,
5681              BSF_GLOBAL, bfd_abs_section_ptr,
5682              info->stacksize >= 0 ? info->stacksize : 0,
5683              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5684         return FALSE;
5685
5686       h = (struct elf_link_hash_entry *) bh;
5687       h->def_regular = 1;
5688       h->type = STT_OBJECT;
5689     }
5690
5691   return TRUE;
5692 }
5693
5694 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5695    called by the ELF linker emulation before_allocation routine.  We
5696    must set the sizes of the sections before the linker sets the
5697    addresses of the various sections.  */
5698
5699 bfd_boolean
5700 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5701                                const char *soname,
5702                                const char *rpath,
5703                                const char *filter_shlib,
5704                                const char *audit,
5705                                const char *depaudit,
5706                                const char * const *auxiliary_filters,
5707                                struct bfd_link_info *info,
5708                                asection **sinterpptr)
5709 {
5710   bfd_size_type soname_indx;
5711   bfd *dynobj;
5712   const struct elf_backend_data *bed;
5713   struct elf_info_failed asvinfo;
5714
5715   *sinterpptr = NULL;
5716
5717   soname_indx = (bfd_size_type) -1;
5718
5719   if (!is_elf_hash_table (info->hash))
5720     return TRUE;
5721
5722   bed = get_elf_backend_data (output_bfd);
5723
5724   /* Any syms created from now on start with -1 in
5725      got.refcount/offset and plt.refcount/offset.  */
5726   elf_hash_table (info)->init_got_refcount
5727     = elf_hash_table (info)->init_got_offset;
5728   elf_hash_table (info)->init_plt_refcount
5729     = elf_hash_table (info)->init_plt_offset;
5730
5731   if (bfd_link_relocatable (info)
5732       && !_bfd_elf_size_group_sections (info))
5733     return FALSE;
5734
5735   /* The backend may have to create some sections regardless of whether
5736      we're dynamic or not.  */
5737   if (bed->elf_backend_always_size_sections
5738       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5739     return FALSE;
5740
5741   /* Determine any GNU_STACK segment requirements, after the backend
5742      has had a chance to set a default segment size.  */
5743   if (info->execstack)
5744     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5745   else if (info->noexecstack)
5746     elf_stack_flags (output_bfd) = PF_R | PF_W;
5747   else
5748     {
5749       bfd *inputobj;
5750       asection *notesec = NULL;
5751       int exec = 0;
5752
5753       for (inputobj = info->input_bfds;
5754            inputobj;
5755            inputobj = inputobj->link.next)
5756         {
5757           asection *s;
5758
5759           if (inputobj->flags
5760               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5761             continue;
5762           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5763           if (s)
5764             {
5765               if (s->flags & SEC_CODE)
5766                 exec = PF_X;
5767               notesec = s;
5768             }
5769           else if (bed->default_execstack)
5770             exec = PF_X;
5771         }
5772       if (notesec || info->stacksize > 0)
5773         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5774       if (notesec && exec && bfd_link_relocatable (info)
5775           && notesec->output_section != bfd_abs_section_ptr)
5776         notesec->output_section->flags |= SEC_CODE;
5777     }
5778
5779   dynobj = elf_hash_table (info)->dynobj;
5780
5781   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5782     {
5783       struct elf_info_failed eif;
5784       struct elf_link_hash_entry *h;
5785       asection *dynstr;
5786       struct bfd_elf_version_tree *t;
5787       struct bfd_elf_version_expr *d;
5788       asection *s;
5789       bfd_boolean all_defined;
5790
5791       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5792       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
5793
5794       if (soname != NULL)
5795         {
5796           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5797                                              soname, TRUE);
5798           if (soname_indx == (bfd_size_type) -1
5799               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5800             return FALSE;
5801         }
5802
5803       if (info->symbolic)
5804         {
5805           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5806             return FALSE;
5807           info->flags |= DF_SYMBOLIC;
5808         }
5809
5810       if (rpath != NULL)
5811         {
5812           bfd_size_type indx;
5813           bfd_vma tag;
5814
5815           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5816                                       TRUE);
5817           if (indx == (bfd_size_type) -1)
5818             return FALSE;
5819
5820           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5821           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5822             return FALSE;
5823         }
5824
5825       if (filter_shlib != NULL)
5826         {
5827           bfd_size_type indx;
5828
5829           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5830                                       filter_shlib, TRUE);
5831           if (indx == (bfd_size_type) -1
5832               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5833             return FALSE;
5834         }
5835
5836       if (auxiliary_filters != NULL)
5837         {
5838           const char * const *p;
5839
5840           for (p = auxiliary_filters; *p != NULL; p++)
5841             {
5842               bfd_size_type indx;
5843
5844               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5845                                           *p, TRUE);
5846               if (indx == (bfd_size_type) -1
5847                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5848                 return FALSE;
5849             }
5850         }
5851
5852       if (audit != NULL)
5853         {
5854           bfd_size_type indx;
5855
5856           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5857                                       TRUE);
5858           if (indx == (bfd_size_type) -1
5859               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5860             return FALSE;
5861         }
5862
5863       if (depaudit != NULL)
5864         {
5865           bfd_size_type indx;
5866
5867           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5868                                       TRUE);
5869           if (indx == (bfd_size_type) -1
5870               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5871             return FALSE;
5872         }
5873
5874       eif.info = info;
5875       eif.failed = FALSE;
5876
5877       /* If we are supposed to export all symbols into the dynamic symbol
5878          table (this is not the normal case), then do so.  */
5879       if (info->export_dynamic
5880           || (bfd_link_executable (info) && info->dynamic))
5881         {
5882           elf_link_hash_traverse (elf_hash_table (info),
5883                                   _bfd_elf_export_symbol,
5884                                   &eif);
5885           if (eif.failed)
5886             return FALSE;
5887         }
5888
5889       /* Make all global versions with definition.  */
5890       for (t = info->version_info; t != NULL; t = t->next)
5891         for (d = t->globals.list; d != NULL; d = d->next)
5892           if (!d->symver && d->literal)
5893             {
5894               const char *verstr, *name;
5895               size_t namelen, verlen, newlen;
5896               char *newname, *p, leading_char;
5897               struct elf_link_hash_entry *newh;
5898
5899               leading_char = bfd_get_symbol_leading_char (output_bfd);
5900               name = d->pattern;
5901               namelen = strlen (name) + (leading_char != '\0');
5902               verstr = t->name;
5903               verlen = strlen (verstr);
5904               newlen = namelen + verlen + 3;
5905
5906               newname = (char *) bfd_malloc (newlen);
5907               if (newname == NULL)
5908                 return FALSE;
5909               newname[0] = leading_char;
5910               memcpy (newname + (leading_char != '\0'), name, namelen);
5911
5912               /* Check the hidden versioned definition.  */
5913               p = newname + namelen;
5914               *p++ = ELF_VER_CHR;
5915               memcpy (p, verstr, verlen + 1);
5916               newh = elf_link_hash_lookup (elf_hash_table (info),
5917                                            newname, FALSE, FALSE,
5918                                            FALSE);
5919               if (newh == NULL
5920                   || (newh->root.type != bfd_link_hash_defined
5921                       && newh->root.type != bfd_link_hash_defweak))
5922                 {
5923                   /* Check the default versioned definition.  */
5924                   *p++ = ELF_VER_CHR;
5925                   memcpy (p, verstr, verlen + 1);
5926                   newh = elf_link_hash_lookup (elf_hash_table (info),
5927                                                newname, FALSE, FALSE,
5928                                                FALSE);
5929                 }
5930               free (newname);
5931
5932               /* Mark this version if there is a definition and it is
5933                  not defined in a shared object.  */
5934               if (newh != NULL
5935                   && !newh->def_dynamic
5936                   && (newh->root.type == bfd_link_hash_defined
5937                       || newh->root.type == bfd_link_hash_defweak))
5938                 d->symver = 1;
5939             }
5940
5941       /* Attach all the symbols to their version information.  */
5942       asvinfo.info = info;
5943       asvinfo.failed = FALSE;
5944
5945       elf_link_hash_traverse (elf_hash_table (info),
5946                               _bfd_elf_link_assign_sym_version,
5947                               &asvinfo);
5948       if (asvinfo.failed)
5949         return FALSE;
5950
5951       if (!info->allow_undefined_version)
5952         {
5953           /* Check if all global versions have a definition.  */
5954           all_defined = TRUE;
5955           for (t = info->version_info; t != NULL; t = t->next)
5956             for (d = t->globals.list; d != NULL; d = d->next)
5957               if (d->literal && !d->symver && !d->script)
5958                 {
5959                   (*_bfd_error_handler)
5960                     (_("%s: undefined version: %s"),
5961                      d->pattern, t->name);
5962                   all_defined = FALSE;
5963                 }
5964
5965           if (!all_defined)
5966             {
5967               bfd_set_error (bfd_error_bad_value);
5968               return FALSE;
5969             }
5970         }
5971
5972       /* Find all symbols which were defined in a dynamic object and make
5973          the backend pick a reasonable value for them.  */
5974       elf_link_hash_traverse (elf_hash_table (info),
5975                               _bfd_elf_adjust_dynamic_symbol,
5976                               &eif);
5977       if (eif.failed)
5978         return FALSE;
5979
5980       /* Add some entries to the .dynamic section.  We fill in some of the
5981          values later, in bfd_elf_final_link, but we must add the entries
5982          now so that we know the final size of the .dynamic section.  */
5983
5984       /* If there are initialization and/or finalization functions to
5985          call then add the corresponding DT_INIT/DT_FINI entries.  */
5986       h = (info->init_function
5987            ? elf_link_hash_lookup (elf_hash_table (info),
5988                                    info->init_function, FALSE,
5989                                    FALSE, FALSE)
5990            : NULL);
5991       if (h != NULL
5992           && (h->ref_regular
5993               || h->def_regular))
5994         {
5995           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5996             return FALSE;
5997         }
5998       h = (info->fini_function
5999            ? elf_link_hash_lookup (elf_hash_table (info),
6000                                    info->fini_function, FALSE,
6001                                    FALSE, FALSE)
6002            : NULL);
6003       if (h != NULL
6004           && (h->ref_regular
6005               || h->def_regular))
6006         {
6007           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6008             return FALSE;
6009         }
6010
6011       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6012       if (s != NULL && s->linker_has_input)
6013         {
6014           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6015           if (! bfd_link_executable (info))
6016             {
6017               bfd *sub;
6018               asection *o;
6019
6020               for (sub = info->input_bfds; sub != NULL;
6021                    sub = sub->link.next)
6022                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6023                   for (o = sub->sections; o != NULL; o = o->next)
6024                     if (elf_section_data (o)->this_hdr.sh_type
6025                         == SHT_PREINIT_ARRAY)
6026                       {
6027                         (*_bfd_error_handler)
6028                           (_("%B: .preinit_array section is not allowed in DSO"),
6029                            sub);
6030                         break;
6031                       }
6032
6033               bfd_set_error (bfd_error_nonrepresentable_section);
6034               return FALSE;
6035             }
6036
6037           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6038               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6039             return FALSE;
6040         }
6041       s = bfd_get_section_by_name (output_bfd, ".init_array");
6042       if (s != NULL && s->linker_has_input)
6043         {
6044           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6045               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6046             return FALSE;
6047         }
6048       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6049       if (s != NULL && s->linker_has_input)
6050         {
6051           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6052               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6053             return FALSE;
6054         }
6055
6056       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6057       /* If .dynstr is excluded from the link, we don't want any of
6058          these tags.  Strictly, we should be checking each section
6059          individually;  This quick check covers for the case where
6060          someone does a /DISCARD/ : { *(*) }.  */
6061       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6062         {
6063           bfd_size_type strsize;
6064
6065           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6066           if ((info->emit_hash
6067                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6068               || (info->emit_gnu_hash
6069                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6070               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6071               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6072               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6073               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6074                                               bed->s->sizeof_sym))
6075             return FALSE;
6076         }
6077     }
6078
6079   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6080     return FALSE;
6081
6082   /* The backend must work out the sizes of all the other dynamic
6083      sections.  */
6084   if (dynobj != NULL
6085       && bed->elf_backend_size_dynamic_sections != NULL
6086       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6087     return FALSE;
6088
6089   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6090     {
6091       unsigned long section_sym_count;
6092       struct bfd_elf_version_tree *verdefs;
6093       asection *s;
6094
6095       /* Set up the version definition section.  */
6096       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6097       BFD_ASSERT (s != NULL);
6098
6099       /* We may have created additional version definitions if we are
6100          just linking a regular application.  */
6101       verdefs = info->version_info;
6102
6103       /* Skip anonymous version tag.  */
6104       if (verdefs != NULL && verdefs->vernum == 0)
6105         verdefs = verdefs->next;
6106
6107       if (verdefs == NULL && !info->create_default_symver)
6108         s->flags |= SEC_EXCLUDE;
6109       else
6110         {
6111           unsigned int cdefs;
6112           bfd_size_type size;
6113           struct bfd_elf_version_tree *t;
6114           bfd_byte *p;
6115           Elf_Internal_Verdef def;
6116           Elf_Internal_Verdaux defaux;
6117           struct bfd_link_hash_entry *bh;
6118           struct elf_link_hash_entry *h;
6119           const char *name;
6120
6121           cdefs = 0;
6122           size = 0;
6123
6124           /* Make space for the base version.  */
6125           size += sizeof (Elf_External_Verdef);
6126           size += sizeof (Elf_External_Verdaux);
6127           ++cdefs;
6128
6129           /* Make space for the default version.  */
6130           if (info->create_default_symver)
6131             {
6132               size += sizeof (Elf_External_Verdef);
6133               ++cdefs;
6134             }
6135
6136           for (t = verdefs; t != NULL; t = t->next)
6137             {
6138               struct bfd_elf_version_deps *n;
6139
6140               /* Don't emit base version twice.  */
6141               if (t->vernum == 0)
6142                 continue;
6143
6144               size += sizeof (Elf_External_Verdef);
6145               size += sizeof (Elf_External_Verdaux);
6146               ++cdefs;
6147
6148               for (n = t->deps; n != NULL; n = n->next)
6149                 size += sizeof (Elf_External_Verdaux);
6150             }
6151
6152           s->size = size;
6153           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6154           if (s->contents == NULL && s->size != 0)
6155             return FALSE;
6156
6157           /* Fill in the version definition section.  */
6158
6159           p = s->contents;
6160
6161           def.vd_version = VER_DEF_CURRENT;
6162           def.vd_flags = VER_FLG_BASE;
6163           def.vd_ndx = 1;
6164           def.vd_cnt = 1;
6165           if (info->create_default_symver)
6166             {
6167               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6168               def.vd_next = sizeof (Elf_External_Verdef);
6169             }
6170           else
6171             {
6172               def.vd_aux = sizeof (Elf_External_Verdef);
6173               def.vd_next = (sizeof (Elf_External_Verdef)
6174                              + sizeof (Elf_External_Verdaux));
6175             }
6176
6177           if (soname_indx != (bfd_size_type) -1)
6178             {
6179               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6180                                       soname_indx);
6181               def.vd_hash = bfd_elf_hash (soname);
6182               defaux.vda_name = soname_indx;
6183               name = soname;
6184             }
6185           else
6186             {
6187               bfd_size_type indx;
6188
6189               name = lbasename (output_bfd->filename);
6190               def.vd_hash = bfd_elf_hash (name);
6191               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6192                                           name, FALSE);
6193               if (indx == (bfd_size_type) -1)
6194                 return FALSE;
6195               defaux.vda_name = indx;
6196             }
6197           defaux.vda_next = 0;
6198
6199           _bfd_elf_swap_verdef_out (output_bfd, &def,
6200                                     (Elf_External_Verdef *) p);
6201           p += sizeof (Elf_External_Verdef);
6202           if (info->create_default_symver)
6203             {
6204               /* Add a symbol representing this version.  */
6205               bh = NULL;
6206               if (! (_bfd_generic_link_add_one_symbol
6207                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6208                       0, NULL, FALSE,
6209                       get_elf_backend_data (dynobj)->collect, &bh)))
6210                 return FALSE;
6211               h = (struct elf_link_hash_entry *) bh;
6212               h->non_elf = 0;
6213               h->def_regular = 1;
6214               h->type = STT_OBJECT;
6215               h->verinfo.vertree = NULL;
6216
6217               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6218                 return FALSE;
6219
6220               /* Create a duplicate of the base version with the same
6221                  aux block, but different flags.  */
6222               def.vd_flags = 0;
6223               def.vd_ndx = 2;
6224               def.vd_aux = sizeof (Elf_External_Verdef);
6225               if (verdefs)
6226                 def.vd_next = (sizeof (Elf_External_Verdef)
6227                                + sizeof (Elf_External_Verdaux));
6228               else
6229                 def.vd_next = 0;
6230               _bfd_elf_swap_verdef_out (output_bfd, &def,
6231                                         (Elf_External_Verdef *) p);
6232               p += sizeof (Elf_External_Verdef);
6233             }
6234           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6235                                      (Elf_External_Verdaux *) p);
6236           p += sizeof (Elf_External_Verdaux);
6237
6238           for (t = verdefs; t != NULL; t = t->next)
6239             {
6240               unsigned int cdeps;
6241               struct bfd_elf_version_deps *n;
6242
6243               /* Don't emit the base version twice.  */
6244               if (t->vernum == 0)
6245                 continue;
6246
6247               cdeps = 0;
6248               for (n = t->deps; n != NULL; n = n->next)
6249                 ++cdeps;
6250
6251               /* Add a symbol representing this version.  */
6252               bh = NULL;
6253               if (! (_bfd_generic_link_add_one_symbol
6254                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6255                       0, NULL, FALSE,
6256                       get_elf_backend_data (dynobj)->collect, &bh)))
6257                 return FALSE;
6258               h = (struct elf_link_hash_entry *) bh;
6259               h->non_elf = 0;
6260               h->def_regular = 1;
6261               h->type = STT_OBJECT;
6262               h->verinfo.vertree = t;
6263
6264               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6265                 return FALSE;
6266
6267               def.vd_version = VER_DEF_CURRENT;
6268               def.vd_flags = 0;
6269               if (t->globals.list == NULL
6270                   && t->locals.list == NULL
6271                   && ! t->used)
6272                 def.vd_flags |= VER_FLG_WEAK;
6273               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6274               def.vd_cnt = cdeps + 1;
6275               def.vd_hash = bfd_elf_hash (t->name);
6276               def.vd_aux = sizeof (Elf_External_Verdef);
6277               def.vd_next = 0;
6278
6279               /* If a basever node is next, it *must* be the last node in
6280                  the chain, otherwise Verdef construction breaks.  */
6281               if (t->next != NULL && t->next->vernum == 0)
6282                 BFD_ASSERT (t->next->next == NULL);
6283
6284               if (t->next != NULL && t->next->vernum != 0)
6285                 def.vd_next = (sizeof (Elf_External_Verdef)
6286                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6287
6288               _bfd_elf_swap_verdef_out (output_bfd, &def,
6289                                         (Elf_External_Verdef *) p);
6290               p += sizeof (Elf_External_Verdef);
6291
6292               defaux.vda_name = h->dynstr_index;
6293               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6294                                       h->dynstr_index);
6295               defaux.vda_next = 0;
6296               if (t->deps != NULL)
6297                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6298               t->name_indx = defaux.vda_name;
6299
6300               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6301                                          (Elf_External_Verdaux *) p);
6302               p += sizeof (Elf_External_Verdaux);
6303
6304               for (n = t->deps; n != NULL; n = n->next)
6305                 {
6306                   if (n->version_needed == NULL)
6307                     {
6308                       /* This can happen if there was an error in the
6309                          version script.  */
6310                       defaux.vda_name = 0;
6311                     }
6312                   else
6313                     {
6314                       defaux.vda_name = n->version_needed->name_indx;
6315                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6316                                               defaux.vda_name);
6317                     }
6318                   if (n->next == NULL)
6319                     defaux.vda_next = 0;
6320                   else
6321                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6322
6323                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6324                                              (Elf_External_Verdaux *) p);
6325                   p += sizeof (Elf_External_Verdaux);
6326                 }
6327             }
6328
6329           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6330               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6331             return FALSE;
6332
6333           elf_tdata (output_bfd)->cverdefs = cdefs;
6334         }
6335
6336       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6337         {
6338           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6339             return FALSE;
6340         }
6341       else if (info->flags & DF_BIND_NOW)
6342         {
6343           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6344             return FALSE;
6345         }
6346
6347       if (info->flags_1)
6348         {
6349           if (bfd_link_executable (info))
6350             info->flags_1 &= ~ (DF_1_INITFIRST
6351                                 | DF_1_NODELETE
6352                                 | DF_1_NOOPEN);
6353           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6354             return FALSE;
6355         }
6356
6357       /* Work out the size of the version reference section.  */
6358
6359       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6360       BFD_ASSERT (s != NULL);
6361       {
6362         struct elf_find_verdep_info sinfo;
6363
6364         sinfo.info = info;
6365         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6366         if (sinfo.vers == 0)
6367           sinfo.vers = 1;
6368         sinfo.failed = FALSE;
6369
6370         elf_link_hash_traverse (elf_hash_table (info),
6371                                 _bfd_elf_link_find_version_dependencies,
6372                                 &sinfo);
6373         if (sinfo.failed)
6374           return FALSE;
6375
6376         if (elf_tdata (output_bfd)->verref == NULL)
6377           s->flags |= SEC_EXCLUDE;
6378         else
6379           {
6380             Elf_Internal_Verneed *t;
6381             unsigned int size;
6382             unsigned int crefs;
6383             bfd_byte *p;
6384
6385             /* Build the version dependency section.  */
6386             size = 0;
6387             crefs = 0;
6388             for (t = elf_tdata (output_bfd)->verref;
6389                  t != NULL;
6390                  t = t->vn_nextref)
6391               {
6392                 Elf_Internal_Vernaux *a;
6393
6394                 size += sizeof (Elf_External_Verneed);
6395                 ++crefs;
6396                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6397                   size += sizeof (Elf_External_Vernaux);
6398               }
6399
6400             s->size = size;
6401             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6402             if (s->contents == NULL)
6403               return FALSE;
6404
6405             p = s->contents;
6406             for (t = elf_tdata (output_bfd)->verref;
6407                  t != NULL;
6408                  t = t->vn_nextref)
6409               {
6410                 unsigned int caux;
6411                 Elf_Internal_Vernaux *a;
6412                 bfd_size_type indx;
6413
6414                 caux = 0;
6415                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6416                   ++caux;
6417
6418                 t->vn_version = VER_NEED_CURRENT;
6419                 t->vn_cnt = caux;
6420                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6421                                             elf_dt_name (t->vn_bfd) != NULL
6422                                             ? elf_dt_name (t->vn_bfd)
6423                                             : lbasename (t->vn_bfd->filename),
6424                                             FALSE);
6425                 if (indx == (bfd_size_type) -1)
6426                   return FALSE;
6427                 t->vn_file = indx;
6428                 t->vn_aux = sizeof (Elf_External_Verneed);
6429                 if (t->vn_nextref == NULL)
6430                   t->vn_next = 0;
6431                 else
6432                   t->vn_next = (sizeof (Elf_External_Verneed)
6433                                 + caux * sizeof (Elf_External_Vernaux));
6434
6435                 _bfd_elf_swap_verneed_out (output_bfd, t,
6436                                            (Elf_External_Verneed *) p);
6437                 p += sizeof (Elf_External_Verneed);
6438
6439                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6440                   {
6441                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6442                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6443                                                 a->vna_nodename, FALSE);
6444                     if (indx == (bfd_size_type) -1)
6445                       return FALSE;
6446                     a->vna_name = indx;
6447                     if (a->vna_nextptr == NULL)
6448                       a->vna_next = 0;
6449                     else
6450                       a->vna_next = sizeof (Elf_External_Vernaux);
6451
6452                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6453                                                (Elf_External_Vernaux *) p);
6454                     p += sizeof (Elf_External_Vernaux);
6455                   }
6456               }
6457
6458             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6459                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6460               return FALSE;
6461
6462             elf_tdata (output_bfd)->cverrefs = crefs;
6463           }
6464       }
6465
6466       if ((elf_tdata (output_bfd)->cverrefs == 0
6467            && elf_tdata (output_bfd)->cverdefs == 0)
6468           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6469                                              &section_sym_count) == 0)
6470         {
6471           s = bfd_get_linker_section (dynobj, ".gnu.version");
6472           s->flags |= SEC_EXCLUDE;
6473         }
6474     }
6475   return TRUE;
6476 }
6477
6478 /* Find the first non-excluded output section.  We'll use its
6479    section symbol for some emitted relocs.  */
6480 void
6481 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6482 {
6483   asection *s;
6484
6485   for (s = output_bfd->sections; s != NULL; s = s->next)
6486     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6487         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6488       {
6489         elf_hash_table (info)->text_index_section = s;
6490         break;
6491       }
6492 }
6493
6494 /* Find two non-excluded output sections, one for code, one for data.
6495    We'll use their section symbols for some emitted relocs.  */
6496 void
6497 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6498 {
6499   asection *s;
6500
6501   /* Data first, since setting text_index_section changes
6502      _bfd_elf_link_omit_section_dynsym.  */
6503   for (s = output_bfd->sections; s != NULL; s = s->next)
6504     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6505         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6506       {
6507         elf_hash_table (info)->data_index_section = s;
6508         break;
6509       }
6510
6511   for (s = output_bfd->sections; s != NULL; s = s->next)
6512     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6513          == (SEC_ALLOC | SEC_READONLY))
6514         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6515       {
6516         elf_hash_table (info)->text_index_section = s;
6517         break;
6518       }
6519
6520   if (elf_hash_table (info)->text_index_section == NULL)
6521     elf_hash_table (info)->text_index_section
6522       = elf_hash_table (info)->data_index_section;
6523 }
6524
6525 bfd_boolean
6526 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6527 {
6528   const struct elf_backend_data *bed;
6529
6530   if (!is_elf_hash_table (info->hash))
6531     return TRUE;
6532
6533   bed = get_elf_backend_data (output_bfd);
6534   (*bed->elf_backend_init_index_section) (output_bfd, info);
6535
6536   if (elf_hash_table (info)->dynamic_sections_created)
6537     {
6538       bfd *dynobj;
6539       asection *s;
6540       bfd_size_type dynsymcount;
6541       unsigned long section_sym_count;
6542       unsigned int dtagcount;
6543
6544       dynobj = elf_hash_table (info)->dynobj;
6545
6546       /* Assign dynsym indicies.  In a shared library we generate a
6547          section symbol for each output section, which come first.
6548          Next come all of the back-end allocated local dynamic syms,
6549          followed by the rest of the global symbols.  */
6550
6551       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6552                                                     &section_sym_count);
6553
6554       /* Work out the size of the symbol version section.  */
6555       s = bfd_get_linker_section (dynobj, ".gnu.version");
6556       BFD_ASSERT (s != NULL);
6557       if (dynsymcount != 0
6558           && (s->flags & SEC_EXCLUDE) == 0)
6559         {
6560           s->size = dynsymcount * sizeof (Elf_External_Versym);
6561           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6562           if (s->contents == NULL)
6563             return FALSE;
6564
6565           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6566             return FALSE;
6567         }
6568
6569       /* Set the size of the .dynsym and .hash sections.  We counted
6570          the number of dynamic symbols in elf_link_add_object_symbols.
6571          We will build the contents of .dynsym and .hash when we build
6572          the final symbol table, because until then we do not know the
6573          correct value to give the symbols.  We built the .dynstr
6574          section as we went along in elf_link_add_object_symbols.  */
6575       s = elf_hash_table (info)->dynsym;
6576       BFD_ASSERT (s != NULL);
6577       s->size = dynsymcount * bed->s->sizeof_sym;
6578
6579       if (dynsymcount != 0)
6580         {
6581           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6582           if (s->contents == NULL)
6583             return FALSE;
6584
6585           /* The first entry in .dynsym is a dummy symbol.
6586              Clear all the section syms, in case we don't output them all.  */
6587           ++section_sym_count;
6588           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6589         }
6590
6591       elf_hash_table (info)->bucketcount = 0;
6592
6593       /* Compute the size of the hashing table.  As a side effect this
6594          computes the hash values for all the names we export.  */
6595       if (info->emit_hash)
6596         {
6597           unsigned long int *hashcodes;
6598           struct hash_codes_info hashinf;
6599           bfd_size_type amt;
6600           unsigned long int nsyms;
6601           size_t bucketcount;
6602           size_t hash_entry_size;
6603
6604           /* Compute the hash values for all exported symbols.  At the same
6605              time store the values in an array so that we could use them for
6606              optimizations.  */
6607           amt = dynsymcount * sizeof (unsigned long int);
6608           hashcodes = (unsigned long int *) bfd_malloc (amt);
6609           if (hashcodes == NULL)
6610             return FALSE;
6611           hashinf.hashcodes = hashcodes;
6612           hashinf.error = FALSE;
6613
6614           /* Put all hash values in HASHCODES.  */
6615           elf_link_hash_traverse (elf_hash_table (info),
6616                                   elf_collect_hash_codes, &hashinf);
6617           if (hashinf.error)
6618             {
6619               free (hashcodes);
6620               return FALSE;
6621             }
6622
6623           nsyms = hashinf.hashcodes - hashcodes;
6624           bucketcount
6625             = compute_bucket_count (info, hashcodes, nsyms, 0);
6626           free (hashcodes);
6627
6628           if (bucketcount == 0)
6629             return FALSE;
6630
6631           elf_hash_table (info)->bucketcount = bucketcount;
6632
6633           s = bfd_get_linker_section (dynobj, ".hash");
6634           BFD_ASSERT (s != NULL);
6635           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6636           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6637           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6638           if (s->contents == NULL)
6639             return FALSE;
6640
6641           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6642           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6643                    s->contents + hash_entry_size);
6644         }
6645
6646       if (info->emit_gnu_hash)
6647         {
6648           size_t i, cnt;
6649           unsigned char *contents;
6650           struct collect_gnu_hash_codes cinfo;
6651           bfd_size_type amt;
6652           size_t bucketcount;
6653
6654           memset (&cinfo, 0, sizeof (cinfo));
6655
6656           /* Compute the hash values for all exported symbols.  At the same
6657              time store the values in an array so that we could use them for
6658              optimizations.  */
6659           amt = dynsymcount * 2 * sizeof (unsigned long int);
6660           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6661           if (cinfo.hashcodes == NULL)
6662             return FALSE;
6663
6664           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6665           cinfo.min_dynindx = -1;
6666           cinfo.output_bfd = output_bfd;
6667           cinfo.bed = bed;
6668
6669           /* Put all hash values in HASHCODES.  */
6670           elf_link_hash_traverse (elf_hash_table (info),
6671                                   elf_collect_gnu_hash_codes, &cinfo);
6672           if (cinfo.error)
6673             {
6674               free (cinfo.hashcodes);
6675               return FALSE;
6676             }
6677
6678           bucketcount
6679             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6680
6681           if (bucketcount == 0)
6682             {
6683               free (cinfo.hashcodes);
6684               return FALSE;
6685             }
6686
6687           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6688           BFD_ASSERT (s != NULL);
6689
6690           if (cinfo.nsyms == 0)
6691             {
6692               /* Empty .gnu.hash section is special.  */
6693               BFD_ASSERT (cinfo.min_dynindx == -1);
6694               free (cinfo.hashcodes);
6695               s->size = 5 * 4 + bed->s->arch_size / 8;
6696               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6697               if (contents == NULL)
6698                 return FALSE;
6699               s->contents = contents;
6700               /* 1 empty bucket.  */
6701               bfd_put_32 (output_bfd, 1, contents);
6702               /* SYMIDX above the special symbol 0.  */
6703               bfd_put_32 (output_bfd, 1, contents + 4);
6704               /* Just one word for bitmask.  */
6705               bfd_put_32 (output_bfd, 1, contents + 8);
6706               /* Only hash fn bloom filter.  */
6707               bfd_put_32 (output_bfd, 0, contents + 12);
6708               /* No hashes are valid - empty bitmask.  */
6709               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6710               /* No hashes in the only bucket.  */
6711               bfd_put_32 (output_bfd, 0,
6712                           contents + 16 + bed->s->arch_size / 8);
6713             }
6714           else
6715             {
6716               unsigned long int maskwords, maskbitslog2, x;
6717               BFD_ASSERT (cinfo.min_dynindx != -1);
6718
6719               x = cinfo.nsyms;
6720               maskbitslog2 = 1;
6721               while ((x >>= 1) != 0)
6722                 ++maskbitslog2;
6723               if (maskbitslog2 < 3)
6724                 maskbitslog2 = 5;
6725               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6726                 maskbitslog2 = maskbitslog2 + 3;
6727               else
6728                 maskbitslog2 = maskbitslog2 + 2;
6729               if (bed->s->arch_size == 64)
6730                 {
6731                   if (maskbitslog2 == 5)
6732                     maskbitslog2 = 6;
6733                   cinfo.shift1 = 6;
6734                 }
6735               else
6736                 cinfo.shift1 = 5;
6737               cinfo.mask = (1 << cinfo.shift1) - 1;
6738               cinfo.shift2 = maskbitslog2;
6739               cinfo.maskbits = 1 << maskbitslog2;
6740               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6741               amt = bucketcount * sizeof (unsigned long int) * 2;
6742               amt += maskwords * sizeof (bfd_vma);
6743               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6744               if (cinfo.bitmask == NULL)
6745                 {
6746                   free (cinfo.hashcodes);
6747                   return FALSE;
6748                 }
6749
6750               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6751               cinfo.indx = cinfo.counts + bucketcount;
6752               cinfo.symindx = dynsymcount - cinfo.nsyms;
6753               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6754
6755               /* Determine how often each hash bucket is used.  */
6756               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6757               for (i = 0; i < cinfo.nsyms; ++i)
6758                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6759
6760               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6761                 if (cinfo.counts[i] != 0)
6762                   {
6763                     cinfo.indx[i] = cnt;
6764                     cnt += cinfo.counts[i];
6765                   }
6766               BFD_ASSERT (cnt == dynsymcount);
6767               cinfo.bucketcount = bucketcount;
6768               cinfo.local_indx = cinfo.min_dynindx;
6769
6770               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6771               s->size += cinfo.maskbits / 8;
6772               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6773               if (contents == NULL)
6774                 {
6775                   free (cinfo.bitmask);
6776                   free (cinfo.hashcodes);
6777                   return FALSE;
6778                 }
6779
6780               s->contents = contents;
6781               bfd_put_32 (output_bfd, bucketcount, contents);
6782               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6783               bfd_put_32 (output_bfd, maskwords, contents + 8);
6784               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6785               contents += 16 + cinfo.maskbits / 8;
6786
6787               for (i = 0; i < bucketcount; ++i)
6788                 {
6789                   if (cinfo.counts[i] == 0)
6790                     bfd_put_32 (output_bfd, 0, contents);
6791                   else
6792                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6793                   contents += 4;
6794                 }
6795
6796               cinfo.contents = contents;
6797
6798               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6799               elf_link_hash_traverse (elf_hash_table (info),
6800                                       elf_renumber_gnu_hash_syms, &cinfo);
6801
6802               contents = s->contents + 16;
6803               for (i = 0; i < maskwords; ++i)
6804                 {
6805                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6806                            contents);
6807                   contents += bed->s->arch_size / 8;
6808                 }
6809
6810               free (cinfo.bitmask);
6811               free (cinfo.hashcodes);
6812             }
6813         }
6814
6815       s = bfd_get_linker_section (dynobj, ".dynstr");
6816       BFD_ASSERT (s != NULL);
6817
6818       elf_finalize_dynstr (output_bfd, info);
6819
6820       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6821
6822       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6823         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6824           return FALSE;
6825     }
6826
6827   return TRUE;
6828 }
6829 \f
6830 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6831
6832 static void
6833 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6834                             asection *sec)
6835 {
6836   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6837   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6838 }
6839
6840 /* Finish SHF_MERGE section merging.  */
6841
6842 bfd_boolean
6843 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
6844 {
6845   bfd *ibfd;
6846   asection *sec;
6847
6848   if (!is_elf_hash_table (info->hash))
6849     return FALSE;
6850
6851   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6852     if ((ibfd->flags & DYNAMIC) == 0
6853         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6854         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
6855             == get_elf_backend_data (obfd)->s->elfclass))
6856       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6857         if ((sec->flags & SEC_MERGE) != 0
6858             && !bfd_is_abs_section (sec->output_section))
6859           {
6860             struct bfd_elf_section_data *secdata;
6861
6862             secdata = elf_section_data (sec);
6863             if (! _bfd_add_merge_section (obfd,
6864                                           &elf_hash_table (info)->merge_info,
6865                                           sec, &secdata->sec_info))
6866               return FALSE;
6867             else if (secdata->sec_info)
6868               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6869           }
6870
6871   if (elf_hash_table (info)->merge_info != NULL)
6872     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
6873                          merge_sections_remove_hook);
6874   return TRUE;
6875 }
6876
6877 /* Create an entry in an ELF linker hash table.  */
6878
6879 struct bfd_hash_entry *
6880 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6881                             struct bfd_hash_table *table,
6882                             const char *string)
6883 {
6884   /* Allocate the structure if it has not already been allocated by a
6885      subclass.  */
6886   if (entry == NULL)
6887     {
6888       entry = (struct bfd_hash_entry *)
6889         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6890       if (entry == NULL)
6891         return entry;
6892     }
6893
6894   /* Call the allocation method of the superclass.  */
6895   entry = _bfd_link_hash_newfunc (entry, table, string);
6896   if (entry != NULL)
6897     {
6898       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6899       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6900
6901       /* Set local fields.  */
6902       ret->indx = -1;
6903       ret->dynindx = -1;
6904       ret->got = htab->init_got_refcount;
6905       ret->plt = htab->init_plt_refcount;
6906       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6907                               - offsetof (struct elf_link_hash_entry, size)));
6908       /* Assume that we have been called by a non-ELF symbol reader.
6909          This flag is then reset by the code which reads an ELF input
6910          file.  This ensures that a symbol created by a non-ELF symbol
6911          reader will have the flag set correctly.  */
6912       ret->non_elf = 1;
6913     }
6914
6915   return entry;
6916 }
6917
6918 /* Copy data from an indirect symbol to its direct symbol, hiding the
6919    old indirect symbol.  Also used for copying flags to a weakdef.  */
6920
6921 void
6922 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6923                                   struct elf_link_hash_entry *dir,
6924                                   struct elf_link_hash_entry *ind)
6925 {
6926   struct elf_link_hash_table *htab;
6927
6928   /* Copy down any references that we may have already seen to the
6929      symbol which just became indirect if DIR isn't a hidden versioned
6930      symbol.  */
6931
6932   if (dir->versioned != versioned_hidden)
6933     {
6934       dir->ref_dynamic |= ind->ref_dynamic;
6935       dir->ref_regular |= ind->ref_regular;
6936       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6937       dir->non_got_ref |= ind->non_got_ref;
6938       dir->needs_plt |= ind->needs_plt;
6939       dir->pointer_equality_needed |= ind->pointer_equality_needed;
6940     }
6941
6942   if (ind->root.type != bfd_link_hash_indirect)
6943     return;
6944
6945   /* Copy over the global and procedure linkage table refcount entries.
6946      These may have been already set up by a check_relocs routine.  */
6947   htab = elf_hash_table (info);
6948   if (ind->got.refcount > htab->init_got_refcount.refcount)
6949     {
6950       if (dir->got.refcount < 0)
6951         dir->got.refcount = 0;
6952       dir->got.refcount += ind->got.refcount;
6953       ind->got.refcount = htab->init_got_refcount.refcount;
6954     }
6955
6956   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6957     {
6958       if (dir->plt.refcount < 0)
6959         dir->plt.refcount = 0;
6960       dir->plt.refcount += ind->plt.refcount;
6961       ind->plt.refcount = htab->init_plt_refcount.refcount;
6962     }
6963
6964   if (ind->dynindx != -1)
6965     {
6966       if (dir->dynindx != -1)
6967         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6968       dir->dynindx = ind->dynindx;
6969       dir->dynstr_index = ind->dynstr_index;
6970       ind->dynindx = -1;
6971       ind->dynstr_index = 0;
6972     }
6973 }
6974
6975 void
6976 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6977                                 struct elf_link_hash_entry *h,
6978                                 bfd_boolean force_local)
6979 {
6980   /* STT_GNU_IFUNC symbol must go through PLT.  */
6981   if (h->type != STT_GNU_IFUNC)
6982     {
6983       h->plt = elf_hash_table (info)->init_plt_offset;
6984       h->needs_plt = 0;
6985     }
6986   if (force_local)
6987     {
6988       h->forced_local = 1;
6989       if (h->dynindx != -1)
6990         {
6991           h->dynindx = -1;
6992           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6993                                   h->dynstr_index);
6994         }
6995     }
6996 }
6997
6998 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
6999    caller.  */
7000
7001 bfd_boolean
7002 _bfd_elf_link_hash_table_init
7003   (struct elf_link_hash_table *table,
7004    bfd *abfd,
7005    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7006                                       struct bfd_hash_table *,
7007                                       const char *),
7008    unsigned int entsize,
7009    enum elf_target_id target_id)
7010 {
7011   bfd_boolean ret;
7012   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7013
7014   table->init_got_refcount.refcount = can_refcount - 1;
7015   table->init_plt_refcount.refcount = can_refcount - 1;
7016   table->init_got_offset.offset = -(bfd_vma) 1;
7017   table->init_plt_offset.offset = -(bfd_vma) 1;
7018   /* The first dynamic symbol is a dummy.  */
7019   table->dynsymcount = 1;
7020
7021   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7022
7023   table->root.type = bfd_link_elf_hash_table;
7024   table->hash_table_id = target_id;
7025
7026   return ret;
7027 }
7028
7029 /* Create an ELF linker hash table.  */
7030
7031 struct bfd_link_hash_table *
7032 _bfd_elf_link_hash_table_create (bfd *abfd)
7033 {
7034   struct elf_link_hash_table *ret;
7035   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7036
7037   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7038   if (ret == NULL)
7039     return NULL;
7040
7041   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7042                                        sizeof (struct elf_link_hash_entry),
7043                                        GENERIC_ELF_DATA))
7044     {
7045       free (ret);
7046       return NULL;
7047     }
7048   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7049
7050   return &ret->root;
7051 }
7052
7053 /* Destroy an ELF linker hash table.  */
7054
7055 void
7056 _bfd_elf_link_hash_table_free (bfd *obfd)
7057 {
7058   struct elf_link_hash_table *htab;
7059
7060   htab = (struct elf_link_hash_table *) obfd->link.hash;
7061   if (htab->dynstr != NULL)
7062     _bfd_elf_strtab_free (htab->dynstr);
7063   _bfd_merge_sections_free (htab->merge_info);
7064   _bfd_generic_link_hash_table_free (obfd);
7065 }
7066
7067 /* This is a hook for the ELF emulation code in the generic linker to
7068    tell the backend linker what file name to use for the DT_NEEDED
7069    entry for a dynamic object.  */
7070
7071 void
7072 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7073 {
7074   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7075       && bfd_get_format (abfd) == bfd_object)
7076     elf_dt_name (abfd) = name;
7077 }
7078
7079 int
7080 bfd_elf_get_dyn_lib_class (bfd *abfd)
7081 {
7082   int lib_class;
7083   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7084       && bfd_get_format (abfd) == bfd_object)
7085     lib_class = elf_dyn_lib_class (abfd);
7086   else
7087     lib_class = 0;
7088   return lib_class;
7089 }
7090
7091 void
7092 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7093 {
7094   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7095       && bfd_get_format (abfd) == bfd_object)
7096     elf_dyn_lib_class (abfd) = lib_class;
7097 }
7098
7099 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7100    the linker ELF emulation code.  */
7101
7102 struct bfd_link_needed_list *
7103 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7104                          struct bfd_link_info *info)
7105 {
7106   if (! is_elf_hash_table (info->hash))
7107     return NULL;
7108   return elf_hash_table (info)->needed;
7109 }
7110
7111 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7112    hook for the linker ELF emulation code.  */
7113
7114 struct bfd_link_needed_list *
7115 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7116                           struct bfd_link_info *info)
7117 {
7118   if (! is_elf_hash_table (info->hash))
7119     return NULL;
7120   return elf_hash_table (info)->runpath;
7121 }
7122
7123 /* Get the name actually used for a dynamic object for a link.  This
7124    is the SONAME entry if there is one.  Otherwise, it is the string
7125    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7126
7127 const char *
7128 bfd_elf_get_dt_soname (bfd *abfd)
7129 {
7130   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7131       && bfd_get_format (abfd) == bfd_object)
7132     return elf_dt_name (abfd);
7133   return NULL;
7134 }
7135
7136 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7137    the ELF linker emulation code.  */
7138
7139 bfd_boolean
7140 bfd_elf_get_bfd_needed_list (bfd *abfd,
7141                              struct bfd_link_needed_list **pneeded)
7142 {
7143   asection *s;
7144   bfd_byte *dynbuf = NULL;
7145   unsigned int elfsec;
7146   unsigned long shlink;
7147   bfd_byte *extdyn, *extdynend;
7148   size_t extdynsize;
7149   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7150
7151   *pneeded = NULL;
7152
7153   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7154       || bfd_get_format (abfd) != bfd_object)
7155     return TRUE;
7156
7157   s = bfd_get_section_by_name (abfd, ".dynamic");
7158   if (s == NULL || s->size == 0)
7159     return TRUE;
7160
7161   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7162     goto error_return;
7163
7164   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7165   if (elfsec == SHN_BAD)
7166     goto error_return;
7167
7168   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7169
7170   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7171   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7172
7173   extdyn = dynbuf;
7174   extdynend = extdyn + s->size;
7175   for (; extdyn < extdynend; extdyn += extdynsize)
7176     {
7177       Elf_Internal_Dyn dyn;
7178
7179       (*swap_dyn_in) (abfd, extdyn, &dyn);
7180
7181       if (dyn.d_tag == DT_NULL)
7182         break;
7183
7184       if (dyn.d_tag == DT_NEEDED)
7185         {
7186           const char *string;
7187           struct bfd_link_needed_list *l;
7188           unsigned int tagv = dyn.d_un.d_val;
7189           bfd_size_type amt;
7190
7191           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7192           if (string == NULL)
7193             goto error_return;
7194
7195           amt = sizeof *l;
7196           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7197           if (l == NULL)
7198             goto error_return;
7199
7200           l->by = abfd;
7201           l->name = string;
7202           l->next = *pneeded;
7203           *pneeded = l;
7204         }
7205     }
7206
7207   free (dynbuf);
7208
7209   return TRUE;
7210
7211  error_return:
7212   if (dynbuf != NULL)
7213     free (dynbuf);
7214   return FALSE;
7215 }
7216
7217 struct elf_symbuf_symbol
7218 {
7219   unsigned long st_name;        /* Symbol name, index in string tbl */
7220   unsigned char st_info;        /* Type and binding attributes */
7221   unsigned char st_other;       /* Visibilty, and target specific */
7222 };
7223
7224 struct elf_symbuf_head
7225 {
7226   struct elf_symbuf_symbol *ssym;
7227   bfd_size_type count;
7228   unsigned int st_shndx;
7229 };
7230
7231 struct elf_symbol
7232 {
7233   union
7234     {
7235       Elf_Internal_Sym *isym;
7236       struct elf_symbuf_symbol *ssym;
7237     } u;
7238   const char *name;
7239 };
7240
7241 /* Sort references to symbols by ascending section number.  */
7242
7243 static int
7244 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7245 {
7246   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7247   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7248
7249   return s1->st_shndx - s2->st_shndx;
7250 }
7251
7252 static int
7253 elf_sym_name_compare (const void *arg1, const void *arg2)
7254 {
7255   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7256   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7257   return strcmp (s1->name, s2->name);
7258 }
7259
7260 static struct elf_symbuf_head *
7261 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7262 {
7263   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7264   struct elf_symbuf_symbol *ssym;
7265   struct elf_symbuf_head *ssymbuf, *ssymhead;
7266   bfd_size_type i, shndx_count, total_size;
7267
7268   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7269   if (indbuf == NULL)
7270     return NULL;
7271
7272   for (ind = indbuf, i = 0; i < symcount; i++)
7273     if (isymbuf[i].st_shndx != SHN_UNDEF)
7274       *ind++ = &isymbuf[i];
7275   indbufend = ind;
7276
7277   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7278          elf_sort_elf_symbol);
7279
7280   shndx_count = 0;
7281   if (indbufend > indbuf)
7282     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7283       if (ind[0]->st_shndx != ind[1]->st_shndx)
7284         shndx_count++;
7285
7286   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7287                 + (indbufend - indbuf) * sizeof (*ssym));
7288   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7289   if (ssymbuf == NULL)
7290     {
7291       free (indbuf);
7292       return NULL;
7293     }
7294
7295   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7296   ssymbuf->ssym = NULL;
7297   ssymbuf->count = shndx_count;
7298   ssymbuf->st_shndx = 0;
7299   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7300     {
7301       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7302         {
7303           ssymhead++;
7304           ssymhead->ssym = ssym;
7305           ssymhead->count = 0;
7306           ssymhead->st_shndx = (*ind)->st_shndx;
7307         }
7308       ssym->st_name = (*ind)->st_name;
7309       ssym->st_info = (*ind)->st_info;
7310       ssym->st_other = (*ind)->st_other;
7311       ssymhead->count++;
7312     }
7313   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7314               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7315                   == total_size));
7316
7317   free (indbuf);
7318   return ssymbuf;
7319 }
7320
7321 /* Check if 2 sections define the same set of local and global
7322    symbols.  */
7323
7324 static bfd_boolean
7325 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7326                                    struct bfd_link_info *info)
7327 {
7328   bfd *bfd1, *bfd2;
7329   const struct elf_backend_data *bed1, *bed2;
7330   Elf_Internal_Shdr *hdr1, *hdr2;
7331   bfd_size_type symcount1, symcount2;
7332   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7333   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7334   Elf_Internal_Sym *isym, *isymend;
7335   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7336   bfd_size_type count1, count2, i;
7337   unsigned int shndx1, shndx2;
7338   bfd_boolean result;
7339
7340   bfd1 = sec1->owner;
7341   bfd2 = sec2->owner;
7342
7343   /* Both sections have to be in ELF.  */
7344   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7345       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7346     return FALSE;
7347
7348   if (elf_section_type (sec1) != elf_section_type (sec2))
7349     return FALSE;
7350
7351   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7352   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7353   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7354     return FALSE;
7355
7356   bed1 = get_elf_backend_data (bfd1);
7357   bed2 = get_elf_backend_data (bfd2);
7358   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7359   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7360   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7361   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7362
7363   if (symcount1 == 0 || symcount2 == 0)
7364     return FALSE;
7365
7366   result = FALSE;
7367   isymbuf1 = NULL;
7368   isymbuf2 = NULL;
7369   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7370   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7371
7372   if (ssymbuf1 == NULL)
7373     {
7374       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7375                                        NULL, NULL, NULL);
7376       if (isymbuf1 == NULL)
7377         goto done;
7378
7379       if (!info->reduce_memory_overheads)
7380         elf_tdata (bfd1)->symbuf = ssymbuf1
7381           = elf_create_symbuf (symcount1, isymbuf1);
7382     }
7383
7384   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7385     {
7386       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7387                                        NULL, NULL, NULL);
7388       if (isymbuf2 == NULL)
7389         goto done;
7390
7391       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7392         elf_tdata (bfd2)->symbuf = ssymbuf2
7393           = elf_create_symbuf (symcount2, isymbuf2);
7394     }
7395
7396   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7397     {
7398       /* Optimized faster version.  */
7399       bfd_size_type lo, hi, mid;
7400       struct elf_symbol *symp;
7401       struct elf_symbuf_symbol *ssym, *ssymend;
7402
7403       lo = 0;
7404       hi = ssymbuf1->count;
7405       ssymbuf1++;
7406       count1 = 0;
7407       while (lo < hi)
7408         {
7409           mid = (lo + hi) / 2;
7410           if (shndx1 < ssymbuf1[mid].st_shndx)
7411             hi = mid;
7412           else if (shndx1 > ssymbuf1[mid].st_shndx)
7413             lo = mid + 1;
7414           else
7415             {
7416               count1 = ssymbuf1[mid].count;
7417               ssymbuf1 += mid;
7418               break;
7419             }
7420         }
7421
7422       lo = 0;
7423       hi = ssymbuf2->count;
7424       ssymbuf2++;
7425       count2 = 0;
7426       while (lo < hi)
7427         {
7428           mid = (lo + hi) / 2;
7429           if (shndx2 < ssymbuf2[mid].st_shndx)
7430             hi = mid;
7431           else if (shndx2 > ssymbuf2[mid].st_shndx)
7432             lo = mid + 1;
7433           else
7434             {
7435               count2 = ssymbuf2[mid].count;
7436               ssymbuf2 += mid;
7437               break;
7438             }
7439         }
7440
7441       if (count1 == 0 || count2 == 0 || count1 != count2)
7442         goto done;
7443
7444       symtable1
7445         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7446       symtable2
7447         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7448       if (symtable1 == NULL || symtable2 == NULL)
7449         goto done;
7450
7451       symp = symtable1;
7452       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7453            ssym < ssymend; ssym++, symp++)
7454         {
7455           symp->u.ssym = ssym;
7456           symp->name = bfd_elf_string_from_elf_section (bfd1,
7457                                                         hdr1->sh_link,
7458                                                         ssym->st_name);
7459         }
7460
7461       symp = symtable2;
7462       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7463            ssym < ssymend; ssym++, symp++)
7464         {
7465           symp->u.ssym = ssym;
7466           symp->name = bfd_elf_string_from_elf_section (bfd2,
7467                                                         hdr2->sh_link,
7468                                                         ssym->st_name);
7469         }
7470
7471       /* Sort symbol by name.  */
7472       qsort (symtable1, count1, sizeof (struct elf_symbol),
7473              elf_sym_name_compare);
7474       qsort (symtable2, count1, sizeof (struct elf_symbol),
7475              elf_sym_name_compare);
7476
7477       for (i = 0; i < count1; i++)
7478         /* Two symbols must have the same binding, type and name.  */
7479         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7480             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7481             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7482           goto done;
7483
7484       result = TRUE;
7485       goto done;
7486     }
7487
7488   symtable1 = (struct elf_symbol *)
7489       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7490   symtable2 = (struct elf_symbol *)
7491       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7492   if (symtable1 == NULL || symtable2 == NULL)
7493     goto done;
7494
7495   /* Count definitions in the section.  */
7496   count1 = 0;
7497   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7498     if (isym->st_shndx == shndx1)
7499       symtable1[count1++].u.isym = isym;
7500
7501   count2 = 0;
7502   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7503     if (isym->st_shndx == shndx2)
7504       symtable2[count2++].u.isym = isym;
7505
7506   if (count1 == 0 || count2 == 0 || count1 != count2)
7507     goto done;
7508
7509   for (i = 0; i < count1; i++)
7510     symtable1[i].name
7511       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7512                                          symtable1[i].u.isym->st_name);
7513
7514   for (i = 0; i < count2; i++)
7515     symtable2[i].name
7516       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7517                                          symtable2[i].u.isym->st_name);
7518
7519   /* Sort symbol by name.  */
7520   qsort (symtable1, count1, sizeof (struct elf_symbol),
7521          elf_sym_name_compare);
7522   qsort (symtable2, count1, sizeof (struct elf_symbol),
7523          elf_sym_name_compare);
7524
7525   for (i = 0; i < count1; i++)
7526     /* Two symbols must have the same binding, type and name.  */
7527     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7528         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7529         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7530       goto done;
7531
7532   result = TRUE;
7533
7534 done:
7535   if (symtable1)
7536     free (symtable1);
7537   if (symtable2)
7538     free (symtable2);
7539   if (isymbuf1)
7540     free (isymbuf1);
7541   if (isymbuf2)
7542     free (isymbuf2);
7543
7544   return result;
7545 }
7546
7547 /* Return TRUE if 2 section types are compatible.  */
7548
7549 bfd_boolean
7550 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7551                                  bfd *bbfd, const asection *bsec)
7552 {
7553   if (asec == NULL
7554       || bsec == NULL
7555       || abfd->xvec->flavour != bfd_target_elf_flavour
7556       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7557     return TRUE;
7558
7559   return elf_section_type (asec) == elf_section_type (bsec);
7560 }
7561 \f
7562 /* Final phase of ELF linker.  */
7563
7564 /* A structure we use to avoid passing large numbers of arguments.  */
7565
7566 struct elf_final_link_info
7567 {
7568   /* General link information.  */
7569   struct bfd_link_info *info;
7570   /* Output BFD.  */
7571   bfd *output_bfd;
7572   /* Symbol string table.  */
7573   struct elf_strtab_hash *symstrtab;
7574   /* .hash section.  */
7575   asection *hash_sec;
7576   /* symbol version section (.gnu.version).  */
7577   asection *symver_sec;
7578   /* Buffer large enough to hold contents of any section.  */
7579   bfd_byte *contents;
7580   /* Buffer large enough to hold external relocs of any section.  */
7581   void *external_relocs;
7582   /* Buffer large enough to hold internal relocs of any section.  */
7583   Elf_Internal_Rela *internal_relocs;
7584   /* Buffer large enough to hold external local symbols of any input
7585      BFD.  */
7586   bfd_byte *external_syms;
7587   /* And a buffer for symbol section indices.  */
7588   Elf_External_Sym_Shndx *locsym_shndx;
7589   /* Buffer large enough to hold internal local symbols of any input
7590      BFD.  */
7591   Elf_Internal_Sym *internal_syms;
7592   /* Array large enough to hold a symbol index for each local symbol
7593      of any input BFD.  */
7594   long *indices;
7595   /* Array large enough to hold a section pointer for each local
7596      symbol of any input BFD.  */
7597   asection **sections;
7598   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7599   Elf_External_Sym_Shndx *symshndxbuf;
7600   /* Number of STT_FILE syms seen.  */
7601   size_t filesym_count;
7602 };
7603
7604 /* This struct is used to pass information to elf_link_output_extsym.  */
7605
7606 struct elf_outext_info
7607 {
7608   bfd_boolean failed;
7609   bfd_boolean localsyms;
7610   bfd_boolean file_sym_done;
7611   struct elf_final_link_info *flinfo;
7612 };
7613
7614
7615 /* Support for evaluating a complex relocation.
7616
7617    Complex relocations are generalized, self-describing relocations.  The
7618    implementation of them consists of two parts: complex symbols, and the
7619    relocations themselves.
7620
7621    The relocations are use a reserved elf-wide relocation type code (R_RELC
7622    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7623    information (start bit, end bit, word width, etc) into the addend.  This
7624    information is extracted from CGEN-generated operand tables within gas.
7625
7626    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7627    internal) representing prefix-notation expressions, including but not
7628    limited to those sorts of expressions normally encoded as addends in the
7629    addend field.  The symbol mangling format is:
7630
7631    <node> := <literal>
7632           |  <unary-operator> ':' <node>
7633           |  <binary-operator> ':' <node> ':' <node>
7634           ;
7635
7636    <literal> := 's' <digits=N> ':' <N character symbol name>
7637              |  'S' <digits=N> ':' <N character section name>
7638              |  '#' <hexdigits>
7639              ;
7640
7641    <binary-operator> := as in C
7642    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7643
7644 static void
7645 set_symbol_value (bfd *bfd_with_globals,
7646                   Elf_Internal_Sym *isymbuf,
7647                   size_t locsymcount,
7648                   size_t symidx,
7649                   bfd_vma val)
7650 {
7651   struct elf_link_hash_entry **sym_hashes;
7652   struct elf_link_hash_entry *h;
7653   size_t extsymoff = locsymcount;
7654
7655   if (symidx < locsymcount)
7656     {
7657       Elf_Internal_Sym *sym;
7658
7659       sym = isymbuf + symidx;
7660       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7661         {
7662           /* It is a local symbol: move it to the
7663              "absolute" section and give it a value.  */
7664           sym->st_shndx = SHN_ABS;
7665           sym->st_value = val;
7666           return;
7667         }
7668       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7669       extsymoff = 0;
7670     }
7671
7672   /* It is a global symbol: set its link type
7673      to "defined" and give it a value.  */
7674
7675   sym_hashes = elf_sym_hashes (bfd_with_globals);
7676   h = sym_hashes [symidx - extsymoff];
7677   while (h->root.type == bfd_link_hash_indirect
7678          || h->root.type == bfd_link_hash_warning)
7679     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7680   h->root.type = bfd_link_hash_defined;
7681   h->root.u.def.value = val;
7682   h->root.u.def.section = bfd_abs_section_ptr;
7683 }
7684
7685 static bfd_boolean
7686 resolve_symbol (const char *name,
7687                 bfd *input_bfd,
7688                 struct elf_final_link_info *flinfo,
7689                 bfd_vma *result,
7690                 Elf_Internal_Sym *isymbuf,
7691                 size_t locsymcount)
7692 {
7693   Elf_Internal_Sym *sym;
7694   struct bfd_link_hash_entry *global_entry;
7695   const char *candidate = NULL;
7696   Elf_Internal_Shdr *symtab_hdr;
7697   size_t i;
7698
7699   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7700
7701   for (i = 0; i < locsymcount; ++ i)
7702     {
7703       sym = isymbuf + i;
7704
7705       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7706         continue;
7707
7708       candidate = bfd_elf_string_from_elf_section (input_bfd,
7709                                                    symtab_hdr->sh_link,
7710                                                    sym->st_name);
7711 #ifdef DEBUG
7712       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7713               name, candidate, (unsigned long) sym->st_value);
7714 #endif
7715       if (candidate && strcmp (candidate, name) == 0)
7716         {
7717           asection *sec = flinfo->sections [i];
7718
7719           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7720           *result += sec->output_offset + sec->output_section->vma;
7721 #ifdef DEBUG
7722           printf ("Found symbol with value %8.8lx\n",
7723                   (unsigned long) *result);
7724 #endif
7725           return TRUE;
7726         }
7727     }
7728
7729   /* Hmm, haven't found it yet. perhaps it is a global.  */
7730   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7731                                        FALSE, FALSE, TRUE);
7732   if (!global_entry)
7733     return FALSE;
7734
7735   if (global_entry->type == bfd_link_hash_defined
7736       || global_entry->type == bfd_link_hash_defweak)
7737     {
7738       *result = (global_entry->u.def.value
7739                  + global_entry->u.def.section->output_section->vma
7740                  + global_entry->u.def.section->output_offset);
7741 #ifdef DEBUG
7742       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7743               global_entry->root.string, (unsigned long) *result);
7744 #endif
7745       return TRUE;
7746     }
7747
7748   return FALSE;
7749 }
7750
7751 static bfd_boolean
7752 resolve_section (const char *name,
7753                  asection *sections,
7754                  bfd_vma *result)
7755 {
7756   asection *curr;
7757   unsigned int len;
7758
7759   for (curr = sections; curr; curr = curr->next)
7760     if (strcmp (curr->name, name) == 0)
7761       {
7762         *result = curr->vma;
7763         return TRUE;
7764       }
7765
7766   /* Hmm. still haven't found it. try pseudo-section names.  */
7767   for (curr = sections; curr; curr = curr->next)
7768     {
7769       len = strlen (curr->name);
7770       if (len > strlen (name))
7771         continue;
7772
7773       if (strncmp (curr->name, name, len) == 0)
7774         {
7775           if (strncmp (".end", name + len, 4) == 0)
7776             {
7777               *result = curr->vma + curr->size;
7778               return TRUE;
7779             }
7780
7781           /* Insert more pseudo-section names here, if you like.  */
7782         }
7783     }
7784
7785   return FALSE;
7786 }
7787
7788 static void
7789 undefined_reference (const char *reftype, const char *name)
7790 {
7791   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7792                       reftype, name);
7793 }
7794
7795 static bfd_boolean
7796 eval_symbol (bfd_vma *result,
7797              const char **symp,
7798              bfd *input_bfd,
7799              struct elf_final_link_info *flinfo,
7800              bfd_vma dot,
7801              Elf_Internal_Sym *isymbuf,
7802              size_t locsymcount,
7803              int signed_p)
7804 {
7805   size_t len;
7806   size_t symlen;
7807   bfd_vma a;
7808   bfd_vma b;
7809   char symbuf[4096];
7810   const char *sym = *symp;
7811   const char *symend;
7812   bfd_boolean symbol_is_section = FALSE;
7813
7814   len = strlen (sym);
7815   symend = sym + len;
7816
7817   if (len < 1 || len > sizeof (symbuf))
7818     {
7819       bfd_set_error (bfd_error_invalid_operation);
7820       return FALSE;
7821     }
7822
7823   switch (* sym)
7824     {
7825     case '.':
7826       *result = dot;
7827       *symp = sym + 1;
7828       return TRUE;
7829
7830     case '#':
7831       ++sym;
7832       *result = strtoul (sym, (char **) symp, 16);
7833       return TRUE;
7834
7835     case 'S':
7836       symbol_is_section = TRUE;
7837     case 's':
7838       ++sym;
7839       symlen = strtol (sym, (char **) symp, 10);
7840       sym = *symp + 1; /* Skip the trailing ':'.  */
7841
7842       if (symend < sym || symlen + 1 > sizeof (symbuf))
7843         {
7844           bfd_set_error (bfd_error_invalid_operation);
7845           return FALSE;
7846         }
7847
7848       memcpy (symbuf, sym, symlen);
7849       symbuf[symlen] = '\0';
7850       *symp = sym + symlen;
7851
7852       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7853          the symbol as a section, or vice-versa. so we're pretty liberal in our
7854          interpretation here; section means "try section first", not "must be a
7855          section", and likewise with symbol.  */
7856
7857       if (symbol_is_section)
7858         {
7859           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7860               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7861                                   isymbuf, locsymcount))
7862             {
7863               undefined_reference ("section", symbuf);
7864               return FALSE;
7865             }
7866         }
7867       else
7868         {
7869           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7870                                isymbuf, locsymcount)
7871               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7872                                    result))
7873             {
7874               undefined_reference ("symbol", symbuf);
7875               return FALSE;
7876             }
7877         }
7878
7879       return TRUE;
7880
7881       /* All that remains are operators.  */
7882
7883 #define UNARY_OP(op)                                            \
7884   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7885     {                                                           \
7886       sym += strlen (#op);                                      \
7887       if (*sym == ':')                                          \
7888         ++sym;                                                  \
7889       *symp = sym;                                              \
7890       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7891                         isymbuf, locsymcount, signed_p))        \
7892         return FALSE;                                           \
7893       if (signed_p)                                             \
7894         *result = op ((bfd_signed_vma) a);                      \
7895       else                                                      \
7896         *result = op a;                                         \
7897       return TRUE;                                              \
7898     }
7899
7900 #define BINARY_OP(op)                                           \
7901   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7902     {                                                           \
7903       sym += strlen (#op);                                      \
7904       if (*sym == ':')                                          \
7905         ++sym;                                                  \
7906       *symp = sym;                                              \
7907       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7908                         isymbuf, locsymcount, signed_p))        \
7909         return FALSE;                                           \
7910       ++*symp;                                                  \
7911       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7912                         isymbuf, locsymcount, signed_p))        \
7913         return FALSE;                                           \
7914       if (signed_p)                                             \
7915         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7916       else                                                      \
7917         *result = a op b;                                       \
7918       return TRUE;                                              \
7919     }
7920
7921     default:
7922       UNARY_OP  (0-);
7923       BINARY_OP (<<);
7924       BINARY_OP (>>);
7925       BINARY_OP (==);
7926       BINARY_OP (!=);
7927       BINARY_OP (<=);
7928       BINARY_OP (>=);
7929       BINARY_OP (&&);
7930       BINARY_OP (||);
7931       UNARY_OP  (~);
7932       UNARY_OP  (!);
7933       BINARY_OP (*);
7934       BINARY_OP (/);
7935       BINARY_OP (%);
7936       BINARY_OP (^);
7937       BINARY_OP (|);
7938       BINARY_OP (&);
7939       BINARY_OP (+);
7940       BINARY_OP (-);
7941       BINARY_OP (<);
7942       BINARY_OP (>);
7943 #undef UNARY_OP
7944 #undef BINARY_OP
7945       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7946       bfd_set_error (bfd_error_invalid_operation);
7947       return FALSE;
7948     }
7949 }
7950
7951 static void
7952 put_value (bfd_vma size,
7953            unsigned long chunksz,
7954            bfd *input_bfd,
7955            bfd_vma x,
7956            bfd_byte *location)
7957 {
7958   location += (size - chunksz);
7959
7960   for (; size; size -= chunksz, location -= chunksz)
7961     {
7962       switch (chunksz)
7963         {
7964         case 1:
7965           bfd_put_8 (input_bfd, x, location);
7966           x >>= 8;
7967           break;
7968         case 2:
7969           bfd_put_16 (input_bfd, x, location);
7970           x >>= 16;
7971           break;
7972         case 4:
7973           bfd_put_32 (input_bfd, x, location);
7974           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
7975           x >>= 16;
7976           x >>= 16;
7977           break;
7978 #ifdef BFD64
7979         case 8:
7980           bfd_put_64 (input_bfd, x, location);
7981           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
7982           x >>= 32;
7983           x >>= 32;
7984           break;
7985 #endif
7986         default:
7987           abort ();
7988           break;
7989         }
7990     }
7991 }
7992
7993 static bfd_vma
7994 get_value (bfd_vma size,
7995            unsigned long chunksz,
7996            bfd *input_bfd,
7997            bfd_byte *location)
7998 {
7999   int shift;
8000   bfd_vma x = 0;
8001
8002   /* Sanity checks.  */
8003   BFD_ASSERT (chunksz <= sizeof (x)
8004               && size >= chunksz
8005               && chunksz != 0
8006               && (size % chunksz) == 0
8007               && input_bfd != NULL
8008               && location != NULL);
8009
8010   if (chunksz == sizeof (x))
8011     {
8012       BFD_ASSERT (size == chunksz);
8013
8014       /* Make sure that we do not perform an undefined shift operation.
8015          We know that size == chunksz so there will only be one iteration
8016          of the loop below.  */
8017       shift = 0;
8018     }
8019   else
8020     shift = 8 * chunksz;
8021
8022   for (; size; size -= chunksz, location += chunksz)
8023     {
8024       switch (chunksz)
8025         {
8026         case 1:
8027           x = (x << shift) | bfd_get_8 (input_bfd, location);
8028           break;
8029         case 2:
8030           x = (x << shift) | bfd_get_16 (input_bfd, location);
8031           break;
8032         case 4:
8033           x = (x << shift) | bfd_get_32 (input_bfd, location);
8034           break;
8035 #ifdef BFD64
8036         case 8:
8037           x = (x << shift) | bfd_get_64 (input_bfd, location);
8038           break;
8039 #endif
8040         default:
8041           abort ();
8042         }
8043     }
8044   return x;
8045 }
8046
8047 static void
8048 decode_complex_addend (unsigned long *start,   /* in bits */
8049                        unsigned long *oplen,   /* in bits */
8050                        unsigned long *len,     /* in bits */
8051                        unsigned long *wordsz,  /* in bytes */
8052                        unsigned long *chunksz, /* in bytes */
8053                        unsigned long *lsb0_p,
8054                        unsigned long *signed_p,
8055                        unsigned long *trunc_p,
8056                        unsigned long encoded)
8057 {
8058   * start     =  encoded        & 0x3F;
8059   * len       = (encoded >>  6) & 0x3F;
8060   * oplen     = (encoded >> 12) & 0x3F;
8061   * wordsz    = (encoded >> 18) & 0xF;
8062   * chunksz   = (encoded >> 22) & 0xF;
8063   * lsb0_p    = (encoded >> 27) & 1;
8064   * signed_p  = (encoded >> 28) & 1;
8065   * trunc_p   = (encoded >> 29) & 1;
8066 }
8067
8068 bfd_reloc_status_type
8069 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8070                                     asection *input_section ATTRIBUTE_UNUSED,
8071                                     bfd_byte *contents,
8072                                     Elf_Internal_Rela *rel,
8073                                     bfd_vma relocation)
8074 {
8075   bfd_vma shift, x, mask;
8076   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8077   bfd_reloc_status_type r;
8078
8079   /*  Perform this reloc, since it is complex.
8080       (this is not to say that it necessarily refers to a complex
8081       symbol; merely that it is a self-describing CGEN based reloc.
8082       i.e. the addend has the complete reloc information (bit start, end,
8083       word size, etc) encoded within it.).  */
8084
8085   decode_complex_addend (&start, &oplen, &len, &wordsz,
8086                          &chunksz, &lsb0_p, &signed_p,
8087                          &trunc_p, rel->r_addend);
8088
8089   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8090
8091   if (lsb0_p)
8092     shift = (start + 1) - len;
8093   else
8094     shift = (8 * wordsz) - (start + len);
8095
8096   /* FIXME: octets_per_byte.  */
8097   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
8098
8099 #ifdef DEBUG
8100   printf ("Doing complex reloc: "
8101           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8102           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8103           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8104           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8105           oplen, (unsigned long) x, (unsigned long) mask,
8106           (unsigned long) relocation);
8107 #endif
8108
8109   r = bfd_reloc_ok;
8110   if (! trunc_p)
8111     /* Now do an overflow check.  */
8112     r = bfd_check_overflow ((signed_p
8113                              ? complain_overflow_signed
8114                              : complain_overflow_unsigned),
8115                             len, 0, (8 * wordsz),
8116                             relocation);
8117
8118   /* Do the deed.  */
8119   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8120
8121 #ifdef DEBUG
8122   printf ("           relocation: %8.8lx\n"
8123           "         shifted mask: %8.8lx\n"
8124           " shifted/masked reloc: %8.8lx\n"
8125           "               result: %8.8lx\n",
8126           (unsigned long) relocation, (unsigned long) (mask << shift),
8127           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8128 #endif
8129   /* FIXME: octets_per_byte.  */
8130   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
8131   return r;
8132 }
8133
8134 /* Functions to read r_offset from external (target order) reloc
8135    entry.  Faster than bfd_getl32 et al, because we let the compiler
8136    know the value is aligned.  */
8137
8138 static bfd_vma
8139 ext32l_r_offset (const void *p)
8140 {
8141   union aligned32
8142   {
8143     uint32_t v;
8144     unsigned char c[4];
8145   };
8146   const union aligned32 *a
8147     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8148
8149   uint32_t aval = (  (uint32_t) a->c[0]
8150                    | (uint32_t) a->c[1] << 8
8151                    | (uint32_t) a->c[2] << 16
8152                    | (uint32_t) a->c[3] << 24);
8153   return aval;
8154 }
8155
8156 static bfd_vma
8157 ext32b_r_offset (const void *p)
8158 {
8159   union aligned32
8160   {
8161     uint32_t v;
8162     unsigned char c[4];
8163   };
8164   const union aligned32 *a
8165     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8166
8167   uint32_t aval = (  (uint32_t) a->c[0] << 24
8168                    | (uint32_t) a->c[1] << 16
8169                    | (uint32_t) a->c[2] << 8
8170                    | (uint32_t) a->c[3]);
8171   return aval;
8172 }
8173
8174 #ifdef BFD_HOST_64_BIT
8175 static bfd_vma
8176 ext64l_r_offset (const void *p)
8177 {
8178   union aligned64
8179   {
8180     uint64_t v;
8181     unsigned char c[8];
8182   };
8183   const union aligned64 *a
8184     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8185
8186   uint64_t aval = (  (uint64_t) a->c[0]
8187                    | (uint64_t) a->c[1] << 8
8188                    | (uint64_t) a->c[2] << 16
8189                    | (uint64_t) a->c[3] << 24
8190                    | (uint64_t) a->c[4] << 32
8191                    | (uint64_t) a->c[5] << 40
8192                    | (uint64_t) a->c[6] << 48
8193                    | (uint64_t) a->c[7] << 56);
8194   return aval;
8195 }
8196
8197 static bfd_vma
8198 ext64b_r_offset (const void *p)
8199 {
8200   union aligned64
8201   {
8202     uint64_t v;
8203     unsigned char c[8];
8204   };
8205   const union aligned64 *a
8206     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8207
8208   uint64_t aval = (  (uint64_t) a->c[0] << 56
8209                    | (uint64_t) a->c[1] << 48
8210                    | (uint64_t) a->c[2] << 40
8211                    | (uint64_t) a->c[3] << 32
8212                    | (uint64_t) a->c[4] << 24
8213                    | (uint64_t) a->c[5] << 16
8214                    | (uint64_t) a->c[6] << 8
8215                    | (uint64_t) a->c[7]);
8216   return aval;
8217 }
8218 #endif
8219
8220 /* When performing a relocatable link, the input relocations are
8221    preserved.  But, if they reference global symbols, the indices
8222    referenced must be updated.  Update all the relocations found in
8223    RELDATA.  */
8224
8225 static bfd_boolean
8226 elf_link_adjust_relocs (bfd *abfd,
8227                         struct bfd_elf_section_reloc_data *reldata,
8228                         bfd_boolean sort)
8229 {
8230   unsigned int i;
8231   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8232   bfd_byte *erela;
8233   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8234   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8235   bfd_vma r_type_mask;
8236   int r_sym_shift;
8237   unsigned int count = reldata->count;
8238   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8239
8240   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8241     {
8242       swap_in = bed->s->swap_reloc_in;
8243       swap_out = bed->s->swap_reloc_out;
8244     }
8245   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8246     {
8247       swap_in = bed->s->swap_reloca_in;
8248       swap_out = bed->s->swap_reloca_out;
8249     }
8250   else
8251     abort ();
8252
8253   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8254     abort ();
8255
8256   if (bed->s->arch_size == 32)
8257     {
8258       r_type_mask = 0xff;
8259       r_sym_shift = 8;
8260     }
8261   else
8262     {
8263       r_type_mask = 0xffffffff;
8264       r_sym_shift = 32;
8265     }
8266
8267   erela = reldata->hdr->contents;
8268   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8269     {
8270       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8271       unsigned int j;
8272
8273       if (*rel_hash == NULL)
8274         continue;
8275
8276       BFD_ASSERT ((*rel_hash)->indx >= 0);
8277
8278       (*swap_in) (abfd, erela, irela);
8279       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8280         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8281                            | (irela[j].r_info & r_type_mask));
8282       (*swap_out) (abfd, irela, erela);
8283     }
8284
8285   if (sort && count != 0)
8286     {
8287       bfd_vma (*ext_r_off) (const void *);
8288       bfd_vma r_off;
8289       size_t elt_size;
8290       bfd_byte *base, *end, *p, *loc;
8291       bfd_byte *buf = NULL;
8292
8293       if (bed->s->arch_size == 32)
8294         {
8295           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8296             ext_r_off = ext32l_r_offset;
8297           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8298             ext_r_off = ext32b_r_offset;
8299           else
8300             abort ();
8301         }
8302       else
8303         {
8304 #ifdef BFD_HOST_64_BIT
8305           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8306             ext_r_off = ext64l_r_offset;
8307           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8308             ext_r_off = ext64b_r_offset;
8309           else
8310 #endif
8311             abort ();
8312         }
8313
8314       /*  Must use a stable sort here.  A modified insertion sort,
8315           since the relocs are mostly sorted already.  */
8316       elt_size = reldata->hdr->sh_entsize;
8317       base = reldata->hdr->contents;
8318       end = base + count * elt_size;
8319       if (elt_size > sizeof (Elf64_External_Rela))
8320         abort ();
8321
8322       /* Ensure the first element is lowest.  This acts as a sentinel,
8323          speeding the main loop below.  */
8324       r_off = (*ext_r_off) (base);
8325       for (p = loc = base; (p += elt_size) < end; )
8326         {
8327           bfd_vma r_off2 = (*ext_r_off) (p);
8328           if (r_off > r_off2)
8329             {
8330               r_off = r_off2;
8331               loc = p;
8332             }
8333         }
8334       if (loc != base)
8335         {
8336           /* Don't just swap *base and *loc as that changes the order
8337              of the original base[0] and base[1] if they happen to
8338              have the same r_offset.  */
8339           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8340           memcpy (onebuf, loc, elt_size);
8341           memmove (base + elt_size, base, loc - base);
8342           memcpy (base, onebuf, elt_size);
8343         }
8344
8345       for (p = base + elt_size; (p += elt_size) < end; )
8346         {
8347           /* base to p is sorted, *p is next to insert.  */
8348           r_off = (*ext_r_off) (p);
8349           /* Search the sorted region for location to insert.  */
8350           loc = p - elt_size;
8351           while (r_off < (*ext_r_off) (loc))
8352             loc -= elt_size;
8353           loc += elt_size;
8354           if (loc != p)
8355             {
8356               /* Chances are there is a run of relocs to insert here,
8357                  from one of more input files.  Files are not always
8358                  linked in order due to the way elf_link_input_bfd is
8359                  called.  See pr17666.  */
8360               size_t sortlen = p - loc;
8361               bfd_vma r_off2 = (*ext_r_off) (loc);
8362               size_t runlen = elt_size;
8363               size_t buf_size = 96 * 1024;
8364               while (p + runlen < end
8365                      && (sortlen <= buf_size
8366                          || runlen + elt_size <= buf_size)
8367                      && r_off2 > (*ext_r_off) (p + runlen))
8368                 runlen += elt_size;
8369               if (buf == NULL)
8370                 {
8371                   buf = bfd_malloc (buf_size);
8372                   if (buf == NULL)
8373                     return FALSE;
8374                 }
8375               if (runlen < sortlen)
8376                 {
8377                   memcpy (buf, p, runlen);
8378                   memmove (loc + runlen, loc, sortlen);
8379                   memcpy (loc, buf, runlen);
8380                 }
8381               else
8382                 {
8383                   memcpy (buf, loc, sortlen);
8384                   memmove (loc, p, runlen);
8385                   memcpy (loc + runlen, buf, sortlen);
8386                 }
8387               p += runlen - elt_size;
8388             }
8389         }
8390       /* Hashes are no longer valid.  */
8391       free (reldata->hashes);
8392       reldata->hashes = NULL;
8393       free (buf);
8394     }
8395   return TRUE;
8396 }
8397
8398 struct elf_link_sort_rela
8399 {
8400   union {
8401     bfd_vma offset;
8402     bfd_vma sym_mask;
8403   } u;
8404   enum elf_reloc_type_class type;
8405   /* We use this as an array of size int_rels_per_ext_rel.  */
8406   Elf_Internal_Rela rela[1];
8407 };
8408
8409 static int
8410 elf_link_sort_cmp1 (const void *A, const void *B)
8411 {
8412   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8413   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8414   int relativea, relativeb;
8415
8416   relativea = a->type == reloc_class_relative;
8417   relativeb = b->type == reloc_class_relative;
8418
8419   if (relativea < relativeb)
8420     return 1;
8421   if (relativea > relativeb)
8422     return -1;
8423   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8424     return -1;
8425   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8426     return 1;
8427   if (a->rela->r_offset < b->rela->r_offset)
8428     return -1;
8429   if (a->rela->r_offset > b->rela->r_offset)
8430     return 1;
8431   return 0;
8432 }
8433
8434 static int
8435 elf_link_sort_cmp2 (const void *A, const void *B)
8436 {
8437   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8438   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8439
8440   if (a->type < b->type)
8441     return -1;
8442   if (a->type > b->type)
8443     return 1;
8444   if (a->u.offset < b->u.offset)
8445     return -1;
8446   if (a->u.offset > b->u.offset)
8447     return 1;
8448   if (a->rela->r_offset < b->rela->r_offset)
8449     return -1;
8450   if (a->rela->r_offset > b->rela->r_offset)
8451     return 1;
8452   return 0;
8453 }
8454
8455 static size_t
8456 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8457 {
8458   asection *dynamic_relocs;
8459   asection *rela_dyn;
8460   asection *rel_dyn;
8461   bfd_size_type count, size;
8462   size_t i, ret, sort_elt, ext_size;
8463   bfd_byte *sort, *s_non_relative, *p;
8464   struct elf_link_sort_rela *sq;
8465   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8466   int i2e = bed->s->int_rels_per_ext_rel;
8467   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8468   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8469   struct bfd_link_order *lo;
8470   bfd_vma r_sym_mask;
8471   bfd_boolean use_rela;
8472
8473   /* Find a dynamic reloc section.  */
8474   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8475   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8476   if (rela_dyn != NULL && rela_dyn->size > 0
8477       && rel_dyn != NULL && rel_dyn->size > 0)
8478     {
8479       bfd_boolean use_rela_initialised = FALSE;
8480
8481       /* This is just here to stop gcc from complaining.
8482          It's initialization checking code is not perfect.  */
8483       use_rela = TRUE;
8484
8485       /* Both sections are present.  Examine the sizes
8486          of the indirect sections to help us choose.  */
8487       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8488         if (lo->type == bfd_indirect_link_order)
8489           {
8490             asection *o = lo->u.indirect.section;
8491
8492             if ((o->size % bed->s->sizeof_rela) == 0)
8493               {
8494                 if ((o->size % bed->s->sizeof_rel) == 0)
8495                   /* Section size is divisible by both rel and rela sizes.
8496                      It is of no help to us.  */
8497                   ;
8498                 else
8499                   {
8500                     /* Section size is only divisible by rela.  */
8501                     if (use_rela_initialised && (use_rela == FALSE))
8502                       {
8503                         _bfd_error_handler
8504                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8505                         bfd_set_error (bfd_error_invalid_operation);
8506                         return 0;
8507                       }
8508                     else
8509                       {
8510                         use_rela = TRUE;
8511                         use_rela_initialised = TRUE;
8512                       }
8513                   }
8514               }
8515             else if ((o->size % bed->s->sizeof_rel) == 0)
8516               {
8517                 /* Section size is only divisible by rel.  */
8518                 if (use_rela_initialised && (use_rela == TRUE))
8519                   {
8520                     _bfd_error_handler
8521                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8522                     bfd_set_error (bfd_error_invalid_operation);
8523                     return 0;
8524                   }
8525                 else
8526                   {
8527                     use_rela = FALSE;
8528                     use_rela_initialised = TRUE;
8529                   }
8530               }
8531             else
8532               {
8533                 /* The section size is not divisible by either - something is wrong.  */
8534                 _bfd_error_handler
8535                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8536                 bfd_set_error (bfd_error_invalid_operation);
8537                 return 0;
8538               }
8539           }
8540
8541       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8542         if (lo->type == bfd_indirect_link_order)
8543           {
8544             asection *o = lo->u.indirect.section;
8545
8546             if ((o->size % bed->s->sizeof_rela) == 0)
8547               {
8548                 if ((o->size % bed->s->sizeof_rel) == 0)
8549                   /* Section size is divisible by both rel and rela sizes.
8550                      It is of no help to us.  */
8551                   ;
8552                 else
8553                   {
8554                     /* Section size is only divisible by rela.  */
8555                     if (use_rela_initialised && (use_rela == FALSE))
8556                       {
8557                         _bfd_error_handler
8558                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8559                         bfd_set_error (bfd_error_invalid_operation);
8560                         return 0;
8561                       }
8562                     else
8563                       {
8564                         use_rela = TRUE;
8565                         use_rela_initialised = TRUE;
8566                       }
8567                   }
8568               }
8569             else if ((o->size % bed->s->sizeof_rel) == 0)
8570               {
8571                 /* Section size is only divisible by rel.  */
8572                 if (use_rela_initialised && (use_rela == TRUE))
8573                   {
8574                     _bfd_error_handler
8575                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8576                     bfd_set_error (bfd_error_invalid_operation);
8577                     return 0;
8578                   }
8579                 else
8580                   {
8581                     use_rela = FALSE;
8582                     use_rela_initialised = TRUE;
8583                   }
8584               }
8585             else
8586               {
8587                 /* The section size is not divisible by either - something is wrong.  */
8588                 _bfd_error_handler
8589                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8590                 bfd_set_error (bfd_error_invalid_operation);
8591                 return 0;
8592               }
8593           }
8594
8595       if (! use_rela_initialised)
8596         /* Make a guess.  */
8597         use_rela = TRUE;
8598     }
8599   else if (rela_dyn != NULL && rela_dyn->size > 0)
8600     use_rela = TRUE;
8601   else if (rel_dyn != NULL && rel_dyn->size > 0)
8602     use_rela = FALSE;
8603   else
8604     return 0;
8605
8606   if (use_rela)
8607     {
8608       dynamic_relocs = rela_dyn;
8609       ext_size = bed->s->sizeof_rela;
8610       swap_in = bed->s->swap_reloca_in;
8611       swap_out = bed->s->swap_reloca_out;
8612     }
8613   else
8614     {
8615       dynamic_relocs = rel_dyn;
8616       ext_size = bed->s->sizeof_rel;
8617       swap_in = bed->s->swap_reloc_in;
8618       swap_out = bed->s->swap_reloc_out;
8619     }
8620
8621   size = 0;
8622   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8623     if (lo->type == bfd_indirect_link_order)
8624       size += lo->u.indirect.section->size;
8625
8626   if (size != dynamic_relocs->size)
8627     return 0;
8628
8629   sort_elt = (sizeof (struct elf_link_sort_rela)
8630               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8631
8632   count = dynamic_relocs->size / ext_size;
8633   if (count == 0)
8634     return 0;
8635   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8636
8637   if (sort == NULL)
8638     {
8639       (*info->callbacks->warning)
8640         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8641       return 0;
8642     }
8643
8644   if (bed->s->arch_size == 32)
8645     r_sym_mask = ~(bfd_vma) 0xff;
8646   else
8647     r_sym_mask = ~(bfd_vma) 0xffffffff;
8648
8649   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8650     if (lo->type == bfd_indirect_link_order)
8651       {
8652         bfd_byte *erel, *erelend;
8653         asection *o = lo->u.indirect.section;
8654
8655         if (o->contents == NULL && o->size != 0)
8656           {
8657             /* This is a reloc section that is being handled as a normal
8658                section.  See bfd_section_from_shdr.  We can't combine
8659                relocs in this case.  */
8660             free (sort);
8661             return 0;
8662           }
8663         erel = o->contents;
8664         erelend = o->contents + o->size;
8665         /* FIXME: octets_per_byte.  */
8666         p = sort + o->output_offset / ext_size * sort_elt;
8667
8668         while (erel < erelend)
8669           {
8670             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8671
8672             (*swap_in) (abfd, erel, s->rela);
8673             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8674             s->u.sym_mask = r_sym_mask;
8675             p += sort_elt;
8676             erel += ext_size;
8677           }
8678       }
8679
8680   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8681
8682   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8683     {
8684       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8685       if (s->type != reloc_class_relative)
8686         break;
8687     }
8688   ret = i;
8689   s_non_relative = p;
8690
8691   sq = (struct elf_link_sort_rela *) s_non_relative;
8692   for (; i < count; i++, p += sort_elt)
8693     {
8694       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8695       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8696         sq = sp;
8697       sp->u.offset = sq->rela->r_offset;
8698     }
8699
8700   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8701
8702   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8703     if (lo->type == bfd_indirect_link_order)
8704       {
8705         bfd_byte *erel, *erelend;
8706         asection *o = lo->u.indirect.section;
8707
8708         erel = o->contents;
8709         erelend = o->contents + o->size;
8710         /* FIXME: octets_per_byte.  */
8711         p = sort + o->output_offset / ext_size * sort_elt;
8712         while (erel < erelend)
8713           {
8714             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8715             (*swap_out) (abfd, s->rela, erel);
8716             p += sort_elt;
8717             erel += ext_size;
8718           }
8719       }
8720
8721   free (sort);
8722   *psec = dynamic_relocs;
8723   return ret;
8724 }
8725
8726 /* Add a symbol to the output symbol string table.  */
8727
8728 static int
8729 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8730                            const char *name,
8731                            Elf_Internal_Sym *elfsym,
8732                            asection *input_sec,
8733                            struct elf_link_hash_entry *h)
8734 {
8735   int (*output_symbol_hook)
8736     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8737      struct elf_link_hash_entry *);
8738   struct elf_link_hash_table *hash_table;
8739   const struct elf_backend_data *bed;
8740   bfd_size_type strtabsize;
8741
8742   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8743
8744   bed = get_elf_backend_data (flinfo->output_bfd);
8745   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8746   if (output_symbol_hook != NULL)
8747     {
8748       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8749       if (ret != 1)
8750         return ret;
8751     }
8752
8753   if (name == NULL
8754       || *name == '\0'
8755       || (input_sec->flags & SEC_EXCLUDE))
8756     elfsym->st_name = (unsigned long) -1;
8757   else
8758     {
8759       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8760          to get the final offset for st_name.  */
8761       elfsym->st_name
8762         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8763                                                name, FALSE);
8764       if (elfsym->st_name == (unsigned long) -1)
8765         return 0;
8766     }
8767
8768   hash_table = elf_hash_table (flinfo->info);
8769   strtabsize = hash_table->strtabsize;
8770   if (strtabsize <= hash_table->strtabcount)
8771     {
8772       strtabsize += strtabsize;
8773       hash_table->strtabsize = strtabsize;
8774       strtabsize *= sizeof (*hash_table->strtab);
8775       hash_table->strtab
8776         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8777                                                  strtabsize);
8778       if (hash_table->strtab == NULL)
8779         return 0;
8780     }
8781   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8782   hash_table->strtab[hash_table->strtabcount].dest_index
8783     = hash_table->strtabcount;
8784   hash_table->strtab[hash_table->strtabcount].destshndx_index
8785     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8786
8787   bfd_get_symcount (flinfo->output_bfd) += 1;
8788   hash_table->strtabcount += 1;
8789
8790   return 1;
8791 }
8792
8793 /* Swap symbols out to the symbol table and flush the output symbols to
8794    the file.  */
8795
8796 static bfd_boolean
8797 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8798 {
8799   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8800   bfd_size_type amt, i;
8801   const struct elf_backend_data *bed;
8802   bfd_byte *symbuf;
8803   Elf_Internal_Shdr *hdr;
8804   file_ptr pos;
8805   bfd_boolean ret;
8806
8807   if (!hash_table->strtabcount)
8808     return TRUE;
8809
8810   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8811
8812   bed = get_elf_backend_data (flinfo->output_bfd);
8813
8814   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8815   symbuf = (bfd_byte *) bfd_malloc (amt);
8816   if (symbuf == NULL)
8817     return FALSE;
8818
8819   if (flinfo->symshndxbuf)
8820     {
8821       amt = (sizeof (Elf_External_Sym_Shndx)
8822              * (bfd_get_symcount (flinfo->output_bfd)));
8823       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8824       if (flinfo->symshndxbuf == NULL)
8825         {
8826           free (symbuf);
8827           return FALSE;
8828         }
8829     }
8830
8831   for (i = 0; i < hash_table->strtabcount; i++)
8832     {
8833       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8834       if (elfsym->sym.st_name == (unsigned long) -1)
8835         elfsym->sym.st_name = 0;
8836       else
8837         elfsym->sym.st_name
8838           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8839                                                     elfsym->sym.st_name);
8840       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8841                                ((bfd_byte *) symbuf
8842                                 + (elfsym->dest_index
8843                                    * bed->s->sizeof_sym)),
8844                                (flinfo->symshndxbuf
8845                                 + elfsym->destshndx_index));
8846     }
8847
8848   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8849   pos = hdr->sh_offset + hdr->sh_size;
8850   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8851   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8852       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8853     {
8854       hdr->sh_size += amt;
8855       ret = TRUE;
8856     }
8857   else
8858     ret = FALSE;
8859
8860   free (symbuf);
8861
8862   free (hash_table->strtab);
8863   hash_table->strtab = NULL;
8864
8865   return ret;
8866 }
8867
8868 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8869
8870 static bfd_boolean
8871 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8872 {
8873   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8874       && sym->st_shndx < SHN_LORESERVE)
8875     {
8876       /* The gABI doesn't support dynamic symbols in output sections
8877          beyond 64k.  */
8878       (*_bfd_error_handler)
8879         (_("%B: Too many sections: %d (>= %d)"),
8880          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8881       bfd_set_error (bfd_error_nonrepresentable_section);
8882       return FALSE;
8883     }
8884   return TRUE;
8885 }
8886
8887 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8888    allowing an unsatisfied unversioned symbol in the DSO to match a
8889    versioned symbol that would normally require an explicit version.
8890    We also handle the case that a DSO references a hidden symbol
8891    which may be satisfied by a versioned symbol in another DSO.  */
8892
8893 static bfd_boolean
8894 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8895                                  const struct elf_backend_data *bed,
8896                                  struct elf_link_hash_entry *h)
8897 {
8898   bfd *abfd;
8899   struct elf_link_loaded_list *loaded;
8900
8901   if (!is_elf_hash_table (info->hash))
8902     return FALSE;
8903
8904   /* Check indirect symbol.  */
8905   while (h->root.type == bfd_link_hash_indirect)
8906     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8907
8908   switch (h->root.type)
8909     {
8910     default:
8911       abfd = NULL;
8912       break;
8913
8914     case bfd_link_hash_undefined:
8915     case bfd_link_hash_undefweak:
8916       abfd = h->root.u.undef.abfd;
8917       if ((abfd->flags & DYNAMIC) == 0
8918           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8919         return FALSE;
8920       break;
8921
8922     case bfd_link_hash_defined:
8923     case bfd_link_hash_defweak:
8924       abfd = h->root.u.def.section->owner;
8925       break;
8926
8927     case bfd_link_hash_common:
8928       abfd = h->root.u.c.p->section->owner;
8929       break;
8930     }
8931   BFD_ASSERT (abfd != NULL);
8932
8933   for (loaded = elf_hash_table (info)->loaded;
8934        loaded != NULL;
8935        loaded = loaded->next)
8936     {
8937       bfd *input;
8938       Elf_Internal_Shdr *hdr;
8939       bfd_size_type symcount;
8940       bfd_size_type extsymcount;
8941       bfd_size_type extsymoff;
8942       Elf_Internal_Shdr *versymhdr;
8943       Elf_Internal_Sym *isym;
8944       Elf_Internal_Sym *isymend;
8945       Elf_Internal_Sym *isymbuf;
8946       Elf_External_Versym *ever;
8947       Elf_External_Versym *extversym;
8948
8949       input = loaded->abfd;
8950
8951       /* We check each DSO for a possible hidden versioned definition.  */
8952       if (input == abfd
8953           || (input->flags & DYNAMIC) == 0
8954           || elf_dynversym (input) == 0)
8955         continue;
8956
8957       hdr = &elf_tdata (input)->dynsymtab_hdr;
8958
8959       symcount = hdr->sh_size / bed->s->sizeof_sym;
8960       if (elf_bad_symtab (input))
8961         {
8962           extsymcount = symcount;
8963           extsymoff = 0;
8964         }
8965       else
8966         {
8967           extsymcount = symcount - hdr->sh_info;
8968           extsymoff = hdr->sh_info;
8969         }
8970
8971       if (extsymcount == 0)
8972         continue;
8973
8974       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8975                                       NULL, NULL, NULL);
8976       if (isymbuf == NULL)
8977         return FALSE;
8978
8979       /* Read in any version definitions.  */
8980       versymhdr = &elf_tdata (input)->dynversym_hdr;
8981       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8982       if (extversym == NULL)
8983         goto error_ret;
8984
8985       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8986           || (bfd_bread (extversym, versymhdr->sh_size, input)
8987               != versymhdr->sh_size))
8988         {
8989           free (extversym);
8990         error_ret:
8991           free (isymbuf);
8992           return FALSE;
8993         }
8994
8995       ever = extversym + extsymoff;
8996       isymend = isymbuf + extsymcount;
8997       for (isym = isymbuf; isym < isymend; isym++, ever++)
8998         {
8999           const char *name;
9000           Elf_Internal_Versym iver;
9001           unsigned short version_index;
9002
9003           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9004               || isym->st_shndx == SHN_UNDEF)
9005             continue;
9006
9007           name = bfd_elf_string_from_elf_section (input,
9008                                                   hdr->sh_link,
9009                                                   isym->st_name);
9010           if (strcmp (name, h->root.root.string) != 0)
9011             continue;
9012
9013           _bfd_elf_swap_versym_in (input, ever, &iver);
9014
9015           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9016               && !(h->def_regular
9017                    && h->forced_local))
9018             {
9019               /* If we have a non-hidden versioned sym, then it should
9020                  have provided a definition for the undefined sym unless
9021                  it is defined in a non-shared object and forced local.
9022                */
9023               abort ();
9024             }
9025
9026           version_index = iver.vs_vers & VERSYM_VERSION;
9027           if (version_index == 1 || version_index == 2)
9028             {
9029               /* This is the base or first version.  We can use it.  */
9030               free (extversym);
9031               free (isymbuf);
9032               return TRUE;
9033             }
9034         }
9035
9036       free (extversym);
9037       free (isymbuf);
9038     }
9039
9040   return FALSE;
9041 }
9042
9043 /* Convert ELF common symbol TYPE.  */
9044
9045 static int
9046 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9047 {
9048   /* Commom symbol can only appear in relocatable link.  */
9049   if (!bfd_link_relocatable (info))
9050     abort ();
9051   switch (info->elf_stt_common)
9052     {
9053     case unchanged:
9054       break;
9055     case elf_stt_common:
9056       type = STT_COMMON;
9057       break;
9058     case no_elf_stt_common:
9059       type = STT_OBJECT;
9060       break;
9061     }
9062   return type;
9063 }
9064
9065 /* Add an external symbol to the symbol table.  This is called from
9066    the hash table traversal routine.  When generating a shared object,
9067    we go through the symbol table twice.  The first time we output
9068    anything that might have been forced to local scope in a version
9069    script.  The second time we output the symbols that are still
9070    global symbols.  */
9071
9072 static bfd_boolean
9073 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9074 {
9075   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9076   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9077   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9078   bfd_boolean strip;
9079   Elf_Internal_Sym sym;
9080   asection *input_sec;
9081   const struct elf_backend_data *bed;
9082   long indx;
9083   int ret;
9084   unsigned int type;
9085   /* A symbol is bound locally if it is forced local or it is locally
9086      defined, hidden versioned, not referenced by shared library and
9087      not exported when linking executable.  */
9088   bfd_boolean local_bind = (h->forced_local
9089                             || (bfd_link_executable (flinfo->info)
9090                                 && !flinfo->info->export_dynamic
9091                                 && !h->dynamic
9092                                 && !h->ref_dynamic
9093                                 && h->def_regular
9094                                 && h->versioned == versioned_hidden));
9095
9096   if (h->root.type == bfd_link_hash_warning)
9097     {
9098       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9099       if (h->root.type == bfd_link_hash_new)
9100         return TRUE;
9101     }
9102
9103   /* Decide whether to output this symbol in this pass.  */
9104   if (eoinfo->localsyms)
9105     {
9106       if (!local_bind)
9107         return TRUE;
9108     }
9109   else
9110     {
9111       if (local_bind)
9112         return TRUE;
9113     }
9114
9115   bed = get_elf_backend_data (flinfo->output_bfd);
9116
9117   if (h->root.type == bfd_link_hash_undefined)
9118     {
9119       /* If we have an undefined symbol reference here then it must have
9120          come from a shared library that is being linked in.  (Undefined
9121          references in regular files have already been handled unless
9122          they are in unreferenced sections which are removed by garbage
9123          collection).  */
9124       bfd_boolean ignore_undef = FALSE;
9125
9126       /* Some symbols may be special in that the fact that they're
9127          undefined can be safely ignored - let backend determine that.  */
9128       if (bed->elf_backend_ignore_undef_symbol)
9129         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9130
9131       /* If we are reporting errors for this situation then do so now.  */
9132       if (!ignore_undef
9133           && h->ref_dynamic
9134           && (!h->ref_regular || flinfo->info->gc_sections)
9135           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9136           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9137         {
9138           if (!(flinfo->info->callbacks->undefined_symbol
9139                 (flinfo->info, h->root.root.string,
9140                  h->ref_regular ? NULL : h->root.u.undef.abfd,
9141                  NULL, 0,
9142                  (flinfo->info->unresolved_syms_in_shared_libs
9143                   == RM_GENERATE_ERROR))))
9144             {
9145               bfd_set_error (bfd_error_bad_value);
9146               eoinfo->failed = TRUE;
9147               return FALSE;
9148             }
9149         }
9150     }
9151
9152   /* We should also warn if a forced local symbol is referenced from
9153      shared libraries.  */
9154   if (bfd_link_executable (flinfo->info)
9155       && h->forced_local
9156       && h->ref_dynamic
9157       && h->def_regular
9158       && !h->dynamic_def
9159       && h->ref_dynamic_nonweak
9160       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9161     {
9162       bfd *def_bfd;
9163       const char *msg;
9164       struct elf_link_hash_entry *hi = h;
9165
9166       /* Check indirect symbol.  */
9167       while (hi->root.type == bfd_link_hash_indirect)
9168         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9169
9170       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9171         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9172       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9173         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9174       else
9175         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9176       def_bfd = flinfo->output_bfd;
9177       if (hi->root.u.def.section != bfd_abs_section_ptr)
9178         def_bfd = hi->root.u.def.section->owner;
9179       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9180                              h->root.root.string);
9181       bfd_set_error (bfd_error_bad_value);
9182       eoinfo->failed = TRUE;
9183       return FALSE;
9184     }
9185
9186   /* We don't want to output symbols that have never been mentioned by
9187      a regular file, or that we have been told to strip.  However, if
9188      h->indx is set to -2, the symbol is used by a reloc and we must
9189      output it.  */
9190   strip = FALSE;
9191   if (h->indx == -2)
9192     ;
9193   else if ((h->def_dynamic
9194             || h->ref_dynamic
9195             || h->root.type == bfd_link_hash_new)
9196            && !h->def_regular
9197            && !h->ref_regular)
9198     strip = TRUE;
9199   else if (flinfo->info->strip == strip_all)
9200     strip = TRUE;
9201   else if (flinfo->info->strip == strip_some
9202            && bfd_hash_lookup (flinfo->info->keep_hash,
9203                                h->root.root.string, FALSE, FALSE) == NULL)
9204     strip = TRUE;
9205   else if ((h->root.type == bfd_link_hash_defined
9206             || h->root.type == bfd_link_hash_defweak)
9207            && ((flinfo->info->strip_discarded
9208                 && discarded_section (h->root.u.def.section))
9209                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9210                    && h->root.u.def.section->owner != NULL
9211                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9212     strip = TRUE;
9213   else if ((h->root.type == bfd_link_hash_undefined
9214             || h->root.type == bfd_link_hash_undefweak)
9215            && h->root.u.undef.abfd != NULL
9216            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9217     strip = TRUE;
9218
9219   type = h->type;
9220
9221   /* If we're stripping it, and it's not a dynamic symbol, there's
9222      nothing else to do.   However, if it is a forced local symbol or
9223      an ifunc symbol we need to give the backend finish_dynamic_symbol
9224      function a chance to make it dynamic.  */
9225   if (strip
9226       && h->dynindx == -1
9227       && type != STT_GNU_IFUNC
9228       && !h->forced_local)
9229     return TRUE;
9230
9231   sym.st_value = 0;
9232   sym.st_size = h->size;
9233   sym.st_other = h->other;
9234   switch (h->root.type)
9235     {
9236     default:
9237     case bfd_link_hash_new:
9238     case bfd_link_hash_warning:
9239       abort ();
9240       return FALSE;
9241
9242     case bfd_link_hash_undefined:
9243     case bfd_link_hash_undefweak:
9244       input_sec = bfd_und_section_ptr;
9245       sym.st_shndx = SHN_UNDEF;
9246       break;
9247
9248     case bfd_link_hash_defined:
9249     case bfd_link_hash_defweak:
9250       {
9251         input_sec = h->root.u.def.section;
9252         if (input_sec->output_section != NULL)
9253           {
9254             sym.st_shndx =
9255               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9256                                                  input_sec->output_section);
9257             if (sym.st_shndx == SHN_BAD)
9258               {
9259                 (*_bfd_error_handler)
9260                   (_("%B: could not find output section %A for input section %A"),
9261                    flinfo->output_bfd, input_sec->output_section, input_sec);
9262                 bfd_set_error (bfd_error_nonrepresentable_section);
9263                 eoinfo->failed = TRUE;
9264                 return FALSE;
9265               }
9266
9267             /* ELF symbols in relocatable files are section relative,
9268                but in nonrelocatable files they are virtual
9269                addresses.  */
9270             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9271             if (!bfd_link_relocatable (flinfo->info))
9272               {
9273                 sym.st_value += input_sec->output_section->vma;
9274                 if (h->type == STT_TLS)
9275                   {
9276                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9277                     if (tls_sec != NULL)
9278                       sym.st_value -= tls_sec->vma;
9279                   }
9280               }
9281           }
9282         else
9283           {
9284             BFD_ASSERT (input_sec->owner == NULL
9285                         || (input_sec->owner->flags & DYNAMIC) != 0);
9286             sym.st_shndx = SHN_UNDEF;
9287             input_sec = bfd_und_section_ptr;
9288           }
9289       }
9290       break;
9291
9292     case bfd_link_hash_common:
9293       input_sec = h->root.u.c.p->section;
9294       sym.st_shndx = bed->common_section_index (input_sec);
9295       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9296       break;
9297
9298     case bfd_link_hash_indirect:
9299       /* These symbols are created by symbol versioning.  They point
9300          to the decorated version of the name.  For example, if the
9301          symbol foo@@GNU_1.2 is the default, which should be used when
9302          foo is used with no version, then we add an indirect symbol
9303          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9304          since the indirected symbol is already in the hash table.  */
9305       return TRUE;
9306     }
9307
9308   if (type == STT_COMMON || type == STT_OBJECT)
9309     switch (h->root.type)
9310       {
9311       case bfd_link_hash_common:
9312         type = elf_link_convert_common_type (flinfo->info, type);
9313         break;
9314       case bfd_link_hash_defined:
9315       case bfd_link_hash_defweak:
9316         if (bed->common_definition (&sym))
9317           type = elf_link_convert_common_type (flinfo->info, type);
9318         else
9319           type = STT_OBJECT;
9320         break;
9321       case bfd_link_hash_undefined:
9322       case bfd_link_hash_undefweak:
9323         break;
9324       default:
9325         abort ();
9326       }
9327
9328   if (local_bind)
9329     {
9330       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9331       /* Turn off visibility on local symbol.  */
9332       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9333     }
9334   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9335   else if (h->unique_global && h->def_regular)
9336     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9337   else if (h->root.type == bfd_link_hash_undefweak
9338            || h->root.type == bfd_link_hash_defweak)
9339     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9340   else
9341     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9342   sym.st_target_internal = h->target_internal;
9343
9344   /* Give the processor backend a chance to tweak the symbol value,
9345      and also to finish up anything that needs to be done for this
9346      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9347      forced local syms when non-shared is due to a historical quirk.
9348      STT_GNU_IFUNC symbol must go through PLT.  */
9349   if ((h->type == STT_GNU_IFUNC
9350        && h->def_regular
9351        && !bfd_link_relocatable (flinfo->info))
9352       || ((h->dynindx != -1
9353            || h->forced_local)
9354           && ((bfd_link_pic (flinfo->info)
9355                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9356                    || h->root.type != bfd_link_hash_undefweak))
9357               || !h->forced_local)
9358           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9359     {
9360       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9361              (flinfo->output_bfd, flinfo->info, h, &sym)))
9362         {
9363           eoinfo->failed = TRUE;
9364           return FALSE;
9365         }
9366     }
9367
9368   /* If we are marking the symbol as undefined, and there are no
9369      non-weak references to this symbol from a regular object, then
9370      mark the symbol as weak undefined; if there are non-weak
9371      references, mark the symbol as strong.  We can't do this earlier,
9372      because it might not be marked as undefined until the
9373      finish_dynamic_symbol routine gets through with it.  */
9374   if (sym.st_shndx == SHN_UNDEF
9375       && h->ref_regular
9376       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9377           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9378     {
9379       int bindtype;
9380       type = ELF_ST_TYPE (sym.st_info);
9381
9382       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9383       if (type == STT_GNU_IFUNC)
9384         type = STT_FUNC;
9385
9386       if (h->ref_regular_nonweak)
9387         bindtype = STB_GLOBAL;
9388       else
9389         bindtype = STB_WEAK;
9390       sym.st_info = ELF_ST_INFO (bindtype, type);
9391     }
9392
9393   /* If this is a symbol defined in a dynamic library, don't use the
9394      symbol size from the dynamic library.  Relinking an executable
9395      against a new library may introduce gratuitous changes in the
9396      executable's symbols if we keep the size.  */
9397   if (sym.st_shndx == SHN_UNDEF
9398       && !h->def_regular
9399       && h->def_dynamic)
9400     sym.st_size = 0;
9401
9402   /* If a non-weak symbol with non-default visibility is not defined
9403      locally, it is a fatal error.  */
9404   if (!bfd_link_relocatable (flinfo->info)
9405       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9406       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9407       && h->root.type == bfd_link_hash_undefined
9408       && !h->def_regular)
9409     {
9410       const char *msg;
9411
9412       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9413         msg = _("%B: protected symbol `%s' isn't defined");
9414       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9415         msg = _("%B: internal symbol `%s' isn't defined");
9416       else
9417         msg = _("%B: hidden symbol `%s' isn't defined");
9418       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9419       bfd_set_error (bfd_error_bad_value);
9420       eoinfo->failed = TRUE;
9421       return FALSE;
9422     }
9423
9424   /* If this symbol should be put in the .dynsym section, then put it
9425      there now.  We already know the symbol index.  We also fill in
9426      the entry in the .hash section.  */
9427   if (elf_hash_table (flinfo->info)->dynsym != NULL
9428       && h->dynindx != -1
9429       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9430     {
9431       bfd_byte *esym;
9432
9433       /* Since there is no version information in the dynamic string,
9434          if there is no version info in symbol version section, we will
9435          have a run-time problem if not linking executable, referenced
9436          by shared library, not locally defined, or not bound locally.
9437       */
9438       if (h->verinfo.verdef == NULL
9439           && !local_bind
9440           && (!bfd_link_executable (flinfo->info)
9441               || h->ref_dynamic
9442               || !h->def_regular))
9443         {
9444           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9445
9446           if (p && p [1] != '\0')
9447             {
9448               (*_bfd_error_handler)
9449                 (_("%B: No symbol version section for versioned symbol `%s'"),
9450                  flinfo->output_bfd, h->root.root.string);
9451               eoinfo->failed = TRUE;
9452               return FALSE;
9453             }
9454         }
9455
9456       sym.st_name = h->dynstr_index;
9457       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9458               + h->dynindx * bed->s->sizeof_sym);
9459       if (!check_dynsym (flinfo->output_bfd, &sym))
9460         {
9461           eoinfo->failed = TRUE;
9462           return FALSE;
9463         }
9464       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9465
9466       if (flinfo->hash_sec != NULL)
9467         {
9468           size_t hash_entry_size;
9469           bfd_byte *bucketpos;
9470           bfd_vma chain;
9471           size_t bucketcount;
9472           size_t bucket;
9473
9474           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9475           bucket = h->u.elf_hash_value % bucketcount;
9476
9477           hash_entry_size
9478             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9479           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9480                        + (bucket + 2) * hash_entry_size);
9481           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9482           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9483                    bucketpos);
9484           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9485                    ((bfd_byte *) flinfo->hash_sec->contents
9486                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9487         }
9488
9489       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9490         {
9491           Elf_Internal_Versym iversym;
9492           Elf_External_Versym *eversym;
9493
9494           if (!h->def_regular)
9495             {
9496               if (h->verinfo.verdef == NULL
9497                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9498                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9499                 iversym.vs_vers = 0;
9500               else
9501                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9502             }
9503           else
9504             {
9505               if (h->verinfo.vertree == NULL)
9506                 iversym.vs_vers = 1;
9507               else
9508                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9509               if (flinfo->info->create_default_symver)
9510                 iversym.vs_vers++;
9511             }
9512
9513           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9514              defined locally.  */
9515           if (h->versioned == versioned_hidden && h->def_regular)
9516             iversym.vs_vers |= VERSYM_HIDDEN;
9517
9518           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9519           eversym += h->dynindx;
9520           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9521         }
9522     }
9523
9524   /* If the symbol is undefined, and we didn't output it to .dynsym,
9525      strip it from .symtab too.  Obviously we can't do this for
9526      relocatable output or when needed for --emit-relocs.  */
9527   else if (input_sec == bfd_und_section_ptr
9528            && h->indx != -2
9529            && !bfd_link_relocatable (flinfo->info))
9530     return TRUE;
9531   /* Also strip others that we couldn't earlier due to dynamic symbol
9532      processing.  */
9533   if (strip)
9534     return TRUE;
9535   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9536     return TRUE;
9537
9538   /* Output a FILE symbol so that following locals are not associated
9539      with the wrong input file.  We need one for forced local symbols
9540      if we've seen more than one FILE symbol or when we have exactly
9541      one FILE symbol but global symbols are present in a file other
9542      than the one with the FILE symbol.  We also need one if linker
9543      defined symbols are present.  In practice these conditions are
9544      always met, so just emit the FILE symbol unconditionally.  */
9545   if (eoinfo->localsyms
9546       && !eoinfo->file_sym_done
9547       && eoinfo->flinfo->filesym_count != 0)
9548     {
9549       Elf_Internal_Sym fsym;
9550
9551       memset (&fsym, 0, sizeof (fsym));
9552       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9553       fsym.st_shndx = SHN_ABS;
9554       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9555                                       bfd_und_section_ptr, NULL))
9556         return FALSE;
9557
9558       eoinfo->file_sym_done = TRUE;
9559     }
9560
9561   indx = bfd_get_symcount (flinfo->output_bfd);
9562   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9563                                    input_sec, h);
9564   if (ret == 0)
9565     {
9566       eoinfo->failed = TRUE;
9567       return FALSE;
9568     }
9569   else if (ret == 1)
9570     h->indx = indx;
9571   else if (h->indx == -2)
9572     abort();
9573
9574   return TRUE;
9575 }
9576
9577 /* Return TRUE if special handling is done for relocs in SEC against
9578    symbols defined in discarded sections.  */
9579
9580 static bfd_boolean
9581 elf_section_ignore_discarded_relocs (asection *sec)
9582 {
9583   const struct elf_backend_data *bed;
9584
9585   switch (sec->sec_info_type)
9586     {
9587     case SEC_INFO_TYPE_STABS:
9588     case SEC_INFO_TYPE_EH_FRAME:
9589     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9590       return TRUE;
9591     default:
9592       break;
9593     }
9594
9595   bed = get_elf_backend_data (sec->owner);
9596   if (bed->elf_backend_ignore_discarded_relocs != NULL
9597       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9598     return TRUE;
9599
9600   return FALSE;
9601 }
9602
9603 /* Return a mask saying how ld should treat relocations in SEC against
9604    symbols defined in discarded sections.  If this function returns
9605    COMPLAIN set, ld will issue a warning message.  If this function
9606    returns PRETEND set, and the discarded section was link-once and the
9607    same size as the kept link-once section, ld will pretend that the
9608    symbol was actually defined in the kept section.  Otherwise ld will
9609    zero the reloc (at least that is the intent, but some cooperation by
9610    the target dependent code is needed, particularly for REL targets).  */
9611
9612 unsigned int
9613 _bfd_elf_default_action_discarded (asection *sec)
9614 {
9615   if (sec->flags & SEC_DEBUGGING)
9616     return PRETEND;
9617
9618   if (strcmp (".eh_frame", sec->name) == 0)
9619     return 0;
9620
9621   if (strcmp (".gcc_except_table", sec->name) == 0)
9622     return 0;
9623
9624   return COMPLAIN | PRETEND;
9625 }
9626
9627 /* Find a match between a section and a member of a section group.  */
9628
9629 static asection *
9630 match_group_member (asection *sec, asection *group,
9631                     struct bfd_link_info *info)
9632 {
9633   asection *first = elf_next_in_group (group);
9634   asection *s = first;
9635
9636   while (s != NULL)
9637     {
9638       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9639         return s;
9640
9641       s = elf_next_in_group (s);
9642       if (s == first)
9643         break;
9644     }
9645
9646   return NULL;
9647 }
9648
9649 /* Check if the kept section of a discarded section SEC can be used
9650    to replace it.  Return the replacement if it is OK.  Otherwise return
9651    NULL.  */
9652
9653 asection *
9654 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9655 {
9656   asection *kept;
9657
9658   kept = sec->kept_section;
9659   if (kept != NULL)
9660     {
9661       if ((kept->flags & SEC_GROUP) != 0)
9662         kept = match_group_member (sec, kept, info);
9663       if (kept != NULL
9664           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9665               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9666         kept = NULL;
9667       sec->kept_section = kept;
9668     }
9669   return kept;
9670 }
9671
9672 /* Link an input file into the linker output file.  This function
9673    handles all the sections and relocations of the input file at once.
9674    This is so that we only have to read the local symbols once, and
9675    don't have to keep them in memory.  */
9676
9677 static bfd_boolean
9678 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9679 {
9680   int (*relocate_section)
9681     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9682      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9683   bfd *output_bfd;
9684   Elf_Internal_Shdr *symtab_hdr;
9685   size_t locsymcount;
9686   size_t extsymoff;
9687   Elf_Internal_Sym *isymbuf;
9688   Elf_Internal_Sym *isym;
9689   Elf_Internal_Sym *isymend;
9690   long *pindex;
9691   asection **ppsection;
9692   asection *o;
9693   const struct elf_backend_data *bed;
9694   struct elf_link_hash_entry **sym_hashes;
9695   bfd_size_type address_size;
9696   bfd_vma r_type_mask;
9697   int r_sym_shift;
9698   bfd_boolean have_file_sym = FALSE;
9699
9700   output_bfd = flinfo->output_bfd;
9701   bed = get_elf_backend_data (output_bfd);
9702   relocate_section = bed->elf_backend_relocate_section;
9703
9704   /* If this is a dynamic object, we don't want to do anything here:
9705      we don't want the local symbols, and we don't want the section
9706      contents.  */
9707   if ((input_bfd->flags & DYNAMIC) != 0)
9708     return TRUE;
9709
9710   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9711   if (elf_bad_symtab (input_bfd))
9712     {
9713       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9714       extsymoff = 0;
9715     }
9716   else
9717     {
9718       locsymcount = symtab_hdr->sh_info;
9719       extsymoff = symtab_hdr->sh_info;
9720     }
9721
9722   /* Read the local symbols.  */
9723   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9724   if (isymbuf == NULL && locsymcount != 0)
9725     {
9726       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9727                                       flinfo->internal_syms,
9728                                       flinfo->external_syms,
9729                                       flinfo->locsym_shndx);
9730       if (isymbuf == NULL)
9731         return FALSE;
9732     }
9733
9734   /* Find local symbol sections and adjust values of symbols in
9735      SEC_MERGE sections.  Write out those local symbols we know are
9736      going into the output file.  */
9737   isymend = isymbuf + locsymcount;
9738   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9739        isym < isymend;
9740        isym++, pindex++, ppsection++)
9741     {
9742       asection *isec;
9743       const char *name;
9744       Elf_Internal_Sym osym;
9745       long indx;
9746       int ret;
9747
9748       *pindex = -1;
9749
9750       if (elf_bad_symtab (input_bfd))
9751         {
9752           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9753             {
9754               *ppsection = NULL;
9755               continue;
9756             }
9757         }
9758
9759       if (isym->st_shndx == SHN_UNDEF)
9760         isec = bfd_und_section_ptr;
9761       else if (isym->st_shndx == SHN_ABS)
9762         isec = bfd_abs_section_ptr;
9763       else if (isym->st_shndx == SHN_COMMON)
9764         isec = bfd_com_section_ptr;
9765       else
9766         {
9767           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9768           if (isec == NULL)
9769             {
9770               /* Don't attempt to output symbols with st_shnx in the
9771                  reserved range other than SHN_ABS and SHN_COMMON.  */
9772               *ppsection = NULL;
9773               continue;
9774             }
9775           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9776                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9777             isym->st_value =
9778               _bfd_merged_section_offset (output_bfd, &isec,
9779                                           elf_section_data (isec)->sec_info,
9780                                           isym->st_value);
9781         }
9782
9783       *ppsection = isec;
9784
9785       /* Don't output the first, undefined, symbol.  In fact, don't
9786          output any undefined local symbol.  */
9787       if (isec == bfd_und_section_ptr)
9788         continue;
9789
9790       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9791         {
9792           /* We never output section symbols.  Instead, we use the
9793              section symbol of the corresponding section in the output
9794              file.  */
9795           continue;
9796         }
9797
9798       /* If we are stripping all symbols, we don't want to output this
9799          one.  */
9800       if (flinfo->info->strip == strip_all)
9801         continue;
9802
9803       /* If we are discarding all local symbols, we don't want to
9804          output this one.  If we are generating a relocatable output
9805          file, then some of the local symbols may be required by
9806          relocs; we output them below as we discover that they are
9807          needed.  */
9808       if (flinfo->info->discard == discard_all)
9809         continue;
9810
9811       /* If this symbol is defined in a section which we are
9812          discarding, we don't need to keep it.  */
9813       if (isym->st_shndx != SHN_UNDEF
9814           && isym->st_shndx < SHN_LORESERVE
9815           && bfd_section_removed_from_list (output_bfd,
9816                                             isec->output_section))
9817         continue;
9818
9819       /* Get the name of the symbol.  */
9820       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9821                                               isym->st_name);
9822       if (name == NULL)
9823         return FALSE;
9824
9825       /* See if we are discarding symbols with this name.  */
9826       if ((flinfo->info->strip == strip_some
9827            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9828                == NULL))
9829           || (((flinfo->info->discard == discard_sec_merge
9830                 && (isec->flags & SEC_MERGE)
9831                 && !bfd_link_relocatable (flinfo->info))
9832                || flinfo->info->discard == discard_l)
9833               && bfd_is_local_label_name (input_bfd, name)))
9834         continue;
9835
9836       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9837         {
9838           if (input_bfd->lto_output)
9839             /* -flto puts a temp file name here.  This means builds
9840                are not reproducible.  Discard the symbol.  */
9841             continue;
9842           have_file_sym = TRUE;
9843           flinfo->filesym_count += 1;
9844         }
9845       if (!have_file_sym)
9846         {
9847           /* In the absence of debug info, bfd_find_nearest_line uses
9848              FILE symbols to determine the source file for local
9849              function symbols.  Provide a FILE symbol here if input
9850              files lack such, so that their symbols won't be
9851              associated with a previous input file.  It's not the
9852              source file, but the best we can do.  */
9853           have_file_sym = TRUE;
9854           flinfo->filesym_count += 1;
9855           memset (&osym, 0, sizeof (osym));
9856           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9857           osym.st_shndx = SHN_ABS;
9858           if (!elf_link_output_symstrtab (flinfo,
9859                                           (input_bfd->lto_output ? NULL
9860                                            : input_bfd->filename),
9861                                           &osym, bfd_abs_section_ptr,
9862                                           NULL))
9863             return FALSE;
9864         }
9865
9866       osym = *isym;
9867
9868       /* Adjust the section index for the output file.  */
9869       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9870                                                          isec->output_section);
9871       if (osym.st_shndx == SHN_BAD)
9872         return FALSE;
9873
9874       /* ELF symbols in relocatable files are section relative, but
9875          in executable files they are virtual addresses.  Note that
9876          this code assumes that all ELF sections have an associated
9877          BFD section with a reasonable value for output_offset; below
9878          we assume that they also have a reasonable value for
9879          output_section.  Any special sections must be set up to meet
9880          these requirements.  */
9881       osym.st_value += isec->output_offset;
9882       if (!bfd_link_relocatable (flinfo->info))
9883         {
9884           osym.st_value += isec->output_section->vma;
9885           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9886             {
9887               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9888               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9889               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9890             }
9891         }
9892
9893       indx = bfd_get_symcount (output_bfd);
9894       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
9895       if (ret == 0)
9896         return FALSE;
9897       else if (ret == 1)
9898         *pindex = indx;
9899     }
9900
9901   if (bed->s->arch_size == 32)
9902     {
9903       r_type_mask = 0xff;
9904       r_sym_shift = 8;
9905       address_size = 4;
9906     }
9907   else
9908     {
9909       r_type_mask = 0xffffffff;
9910       r_sym_shift = 32;
9911       address_size = 8;
9912     }
9913
9914   /* Relocate the contents of each section.  */
9915   sym_hashes = elf_sym_hashes (input_bfd);
9916   for (o = input_bfd->sections; o != NULL; o = o->next)
9917     {
9918       bfd_byte *contents;
9919
9920       if (! o->linker_mark)
9921         {
9922           /* This section was omitted from the link.  */
9923           continue;
9924         }
9925
9926       if (bfd_link_relocatable (flinfo->info)
9927           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9928         {
9929           /* Deal with the group signature symbol.  */
9930           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9931           unsigned long symndx = sec_data->this_hdr.sh_info;
9932           asection *osec = o->output_section;
9933
9934           if (symndx >= locsymcount
9935               || (elf_bad_symtab (input_bfd)
9936                   && flinfo->sections[symndx] == NULL))
9937             {
9938               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9939               while (h->root.type == bfd_link_hash_indirect
9940                      || h->root.type == bfd_link_hash_warning)
9941                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9942               /* Arrange for symbol to be output.  */
9943               h->indx = -2;
9944               elf_section_data (osec)->this_hdr.sh_info = -2;
9945             }
9946           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9947             {
9948               /* We'll use the output section target_index.  */
9949               asection *sec = flinfo->sections[symndx]->output_section;
9950               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9951             }
9952           else
9953             {
9954               if (flinfo->indices[symndx] == -1)
9955                 {
9956                   /* Otherwise output the local symbol now.  */
9957                   Elf_Internal_Sym sym = isymbuf[symndx];
9958                   asection *sec = flinfo->sections[symndx]->output_section;
9959                   const char *name;
9960                   long indx;
9961                   int ret;
9962
9963                   name = bfd_elf_string_from_elf_section (input_bfd,
9964                                                           symtab_hdr->sh_link,
9965                                                           sym.st_name);
9966                   if (name == NULL)
9967                     return FALSE;
9968
9969                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9970                                                                     sec);
9971                   if (sym.st_shndx == SHN_BAD)
9972                     return FALSE;
9973
9974                   sym.st_value += o->output_offset;
9975
9976                   indx = bfd_get_symcount (output_bfd);
9977                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
9978                                                    NULL);
9979                   if (ret == 0)
9980                     return FALSE;
9981                   else if (ret == 1)
9982                     flinfo->indices[symndx] = indx;
9983                   else
9984                     abort ();
9985                 }
9986               elf_section_data (osec)->this_hdr.sh_info
9987                 = flinfo->indices[symndx];
9988             }
9989         }
9990
9991       if ((o->flags & SEC_HAS_CONTENTS) == 0
9992           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9993         continue;
9994
9995       if ((o->flags & SEC_LINKER_CREATED) != 0)
9996         {
9997           /* Section was created by _bfd_elf_link_create_dynamic_sections
9998              or somesuch.  */
9999           continue;
10000         }
10001
10002       /* Get the contents of the section.  They have been cached by a
10003          relaxation routine.  Note that o is a section in an input
10004          file, so the contents field will not have been set by any of
10005          the routines which work on output files.  */
10006       if (elf_section_data (o)->this_hdr.contents != NULL)
10007         {
10008           contents = elf_section_data (o)->this_hdr.contents;
10009           if (bed->caches_rawsize
10010               && o->rawsize != 0
10011               && o->rawsize < o->size)
10012             {
10013               memcpy (flinfo->contents, contents, o->rawsize);
10014               contents = flinfo->contents;
10015             }
10016         }
10017       else
10018         {
10019           contents = flinfo->contents;
10020           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10021             return FALSE;
10022         }
10023
10024       if ((o->flags & SEC_RELOC) != 0)
10025         {
10026           Elf_Internal_Rela *internal_relocs;
10027           Elf_Internal_Rela *rel, *relend;
10028           int action_discarded;
10029           int ret;
10030
10031           /* Get the swapped relocs.  */
10032           internal_relocs
10033             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10034                                          flinfo->internal_relocs, FALSE);
10035           if (internal_relocs == NULL
10036               && o->reloc_count > 0)
10037             return FALSE;
10038
10039           /* We need to reverse-copy input .ctors/.dtors sections if
10040              they are placed in .init_array/.finit_array for output.  */
10041           if (o->size > address_size
10042               && ((strncmp (o->name, ".ctors", 6) == 0
10043                    && strcmp (o->output_section->name,
10044                               ".init_array") == 0)
10045                   || (strncmp (o->name, ".dtors", 6) == 0
10046                       && strcmp (o->output_section->name,
10047                                  ".fini_array") == 0))
10048               && (o->name[6] == 0 || o->name[6] == '.'))
10049             {
10050               if (o->size != o->reloc_count * address_size)
10051                 {
10052                   (*_bfd_error_handler)
10053                     (_("error: %B: size of section %A is not "
10054                        "multiple of address size"),
10055                      input_bfd, o);
10056                   bfd_set_error (bfd_error_on_input);
10057                   return FALSE;
10058                 }
10059               o->flags |= SEC_ELF_REVERSE_COPY;
10060             }
10061
10062           action_discarded = -1;
10063           if (!elf_section_ignore_discarded_relocs (o))
10064             action_discarded = (*bed->action_discarded) (o);
10065
10066           /* Run through the relocs evaluating complex reloc symbols and
10067              looking for relocs against symbols from discarded sections
10068              or section symbols from removed link-once sections.
10069              Complain about relocs against discarded sections.  Zero
10070              relocs against removed link-once sections.  */
10071
10072           rel = internal_relocs;
10073           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10074           for ( ; rel < relend; rel++)
10075             {
10076               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10077               unsigned int s_type;
10078               asection **ps, *sec;
10079               struct elf_link_hash_entry *h = NULL;
10080               const char *sym_name;
10081
10082               if (r_symndx == STN_UNDEF)
10083                 continue;
10084
10085               if (r_symndx >= locsymcount
10086                   || (elf_bad_symtab (input_bfd)
10087                       && flinfo->sections[r_symndx] == NULL))
10088                 {
10089                   h = sym_hashes[r_symndx - extsymoff];
10090
10091                   /* Badly formatted input files can contain relocs that
10092                      reference non-existant symbols.  Check here so that
10093                      we do not seg fault.  */
10094                   if (h == NULL)
10095                     {
10096                       char buffer [32];
10097
10098                       sprintf_vma (buffer, rel->r_info);
10099                       (*_bfd_error_handler)
10100                         (_("error: %B contains a reloc (0x%s) for section %A "
10101                            "that references a non-existent global symbol"),
10102                          input_bfd, o, buffer);
10103                       bfd_set_error (bfd_error_bad_value);
10104                       return FALSE;
10105                     }
10106
10107                   while (h->root.type == bfd_link_hash_indirect
10108                          || h->root.type == bfd_link_hash_warning)
10109                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10110
10111                   s_type = h->type;
10112
10113                   /* If a plugin symbol is referenced from a non-IR file,
10114                      mark the symbol as undefined.  Note that the
10115                      linker may attach linker created dynamic sections
10116                      to the plugin bfd.  Symbols defined in linker
10117                      created sections are not plugin symbols.  */
10118                   if (h->root.non_ir_ref
10119                       && (h->root.type == bfd_link_hash_defined
10120                           || h->root.type == bfd_link_hash_defweak)
10121                       && (h->root.u.def.section->flags
10122                           & SEC_LINKER_CREATED) == 0
10123                       && h->root.u.def.section->owner != NULL
10124                       && (h->root.u.def.section->owner->flags
10125                           & BFD_PLUGIN) != 0)
10126                     {
10127                       h->root.type = bfd_link_hash_undefined;
10128                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10129                     }
10130
10131                   ps = NULL;
10132                   if (h->root.type == bfd_link_hash_defined
10133                       || h->root.type == bfd_link_hash_defweak)
10134                     ps = &h->root.u.def.section;
10135
10136                   sym_name = h->root.root.string;
10137                 }
10138               else
10139                 {
10140                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10141
10142                   s_type = ELF_ST_TYPE (sym->st_info);
10143                   ps = &flinfo->sections[r_symndx];
10144                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10145                                                sym, *ps);
10146                 }
10147
10148               if ((s_type == STT_RELC || s_type == STT_SRELC)
10149                   && !bfd_link_relocatable (flinfo->info))
10150                 {
10151                   bfd_vma val;
10152                   bfd_vma dot = (rel->r_offset
10153                                  + o->output_offset + o->output_section->vma);
10154 #ifdef DEBUG
10155                   printf ("Encountered a complex symbol!");
10156                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10157                           input_bfd->filename, o->name,
10158                           (long) (rel - internal_relocs));
10159                   printf (" symbol: idx  %8.8lx, name %s\n",
10160                           r_symndx, sym_name);
10161                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10162                           (unsigned long) rel->r_info,
10163                           (unsigned long) rel->r_offset);
10164 #endif
10165                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10166                                     isymbuf, locsymcount, s_type == STT_SRELC))
10167                     return FALSE;
10168
10169                   /* Symbol evaluated OK.  Update to absolute value.  */
10170                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10171                                     r_symndx, val);
10172                   continue;
10173                 }
10174
10175               if (action_discarded != -1 && ps != NULL)
10176                 {
10177                   /* Complain if the definition comes from a
10178                      discarded section.  */
10179                   if ((sec = *ps) != NULL && discarded_section (sec))
10180                     {
10181                       BFD_ASSERT (r_symndx != STN_UNDEF);
10182                       if (action_discarded & COMPLAIN)
10183                         (*flinfo->info->callbacks->einfo)
10184                           (_("%X`%s' referenced in section `%A' of %B: "
10185                              "defined in discarded section `%A' of %B\n"),
10186                            sym_name, o, input_bfd, sec, sec->owner);
10187
10188                       /* Try to do the best we can to support buggy old
10189                          versions of gcc.  Pretend that the symbol is
10190                          really defined in the kept linkonce section.
10191                          FIXME: This is quite broken.  Modifying the
10192                          symbol here means we will be changing all later
10193                          uses of the symbol, not just in this section.  */
10194                       if (action_discarded & PRETEND)
10195                         {
10196                           asection *kept;
10197
10198                           kept = _bfd_elf_check_kept_section (sec,
10199                                                               flinfo->info);
10200                           if (kept != NULL)
10201                             {
10202                               *ps = kept;
10203                               continue;
10204                             }
10205                         }
10206                     }
10207                 }
10208             }
10209
10210           /* Relocate the section by invoking a back end routine.
10211
10212              The back end routine is responsible for adjusting the
10213              section contents as necessary, and (if using Rela relocs
10214              and generating a relocatable output file) adjusting the
10215              reloc addend as necessary.
10216
10217              The back end routine does not have to worry about setting
10218              the reloc address or the reloc symbol index.
10219
10220              The back end routine is given a pointer to the swapped in
10221              internal symbols, and can access the hash table entries
10222              for the external symbols via elf_sym_hashes (input_bfd).
10223
10224              When generating relocatable output, the back end routine
10225              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10226              output symbol is going to be a section symbol
10227              corresponding to the output section, which will require
10228              the addend to be adjusted.  */
10229
10230           ret = (*relocate_section) (output_bfd, flinfo->info,
10231                                      input_bfd, o, contents,
10232                                      internal_relocs,
10233                                      isymbuf,
10234                                      flinfo->sections);
10235           if (!ret)
10236             return FALSE;
10237
10238           if (ret == 2
10239               || bfd_link_relocatable (flinfo->info)
10240               || flinfo->info->emitrelocations)
10241             {
10242               Elf_Internal_Rela *irela;
10243               Elf_Internal_Rela *irelaend, *irelamid;
10244               bfd_vma last_offset;
10245               struct elf_link_hash_entry **rel_hash;
10246               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10247               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10248               unsigned int next_erel;
10249               bfd_boolean rela_normal;
10250               struct bfd_elf_section_data *esdi, *esdo;
10251
10252               esdi = elf_section_data (o);
10253               esdo = elf_section_data (o->output_section);
10254               rela_normal = FALSE;
10255
10256               /* Adjust the reloc addresses and symbol indices.  */
10257
10258               irela = internal_relocs;
10259               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10260               rel_hash = esdo->rel.hashes + esdo->rel.count;
10261               /* We start processing the REL relocs, if any.  When we reach
10262                  IRELAMID in the loop, we switch to the RELA relocs.  */
10263               irelamid = irela;
10264               if (esdi->rel.hdr != NULL)
10265                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10266                              * bed->s->int_rels_per_ext_rel);
10267               rel_hash_list = rel_hash;
10268               rela_hash_list = NULL;
10269               last_offset = o->output_offset;
10270               if (!bfd_link_relocatable (flinfo->info))
10271                 last_offset += o->output_section->vma;
10272               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10273                 {
10274                   unsigned long r_symndx;
10275                   asection *sec;
10276                   Elf_Internal_Sym sym;
10277
10278                   if (next_erel == bed->s->int_rels_per_ext_rel)
10279                     {
10280                       rel_hash++;
10281                       next_erel = 0;
10282                     }
10283
10284                   if (irela == irelamid)
10285                     {
10286                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10287                       rela_hash_list = rel_hash;
10288                       rela_normal = bed->rela_normal;
10289                     }
10290
10291                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10292                                                              flinfo->info, o,
10293                                                              irela->r_offset);
10294                   if (irela->r_offset >= (bfd_vma) -2)
10295                     {
10296                       /* This is a reloc for a deleted entry or somesuch.
10297                          Turn it into an R_*_NONE reloc, at the same
10298                          offset as the last reloc.  elf_eh_frame.c and
10299                          bfd_elf_discard_info rely on reloc offsets
10300                          being ordered.  */
10301                       irela->r_offset = last_offset;
10302                       irela->r_info = 0;
10303                       irela->r_addend = 0;
10304                       continue;
10305                     }
10306
10307                   irela->r_offset += o->output_offset;
10308
10309                   /* Relocs in an executable have to be virtual addresses.  */
10310                   if (!bfd_link_relocatable (flinfo->info))
10311                     irela->r_offset += o->output_section->vma;
10312
10313                   last_offset = irela->r_offset;
10314
10315                   r_symndx = irela->r_info >> r_sym_shift;
10316                   if (r_symndx == STN_UNDEF)
10317                     continue;
10318
10319                   if (r_symndx >= locsymcount
10320                       || (elf_bad_symtab (input_bfd)
10321                           && flinfo->sections[r_symndx] == NULL))
10322                     {
10323                       struct elf_link_hash_entry *rh;
10324                       unsigned long indx;
10325
10326                       /* This is a reloc against a global symbol.  We
10327                          have not yet output all the local symbols, so
10328                          we do not know the symbol index of any global
10329                          symbol.  We set the rel_hash entry for this
10330                          reloc to point to the global hash table entry
10331                          for this symbol.  The symbol index is then
10332                          set at the end of bfd_elf_final_link.  */
10333                       indx = r_symndx - extsymoff;
10334                       rh = elf_sym_hashes (input_bfd)[indx];
10335                       while (rh->root.type == bfd_link_hash_indirect
10336                              || rh->root.type == bfd_link_hash_warning)
10337                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10338
10339                       /* Setting the index to -2 tells
10340                          elf_link_output_extsym that this symbol is
10341                          used by a reloc.  */
10342                       BFD_ASSERT (rh->indx < 0);
10343                       rh->indx = -2;
10344
10345                       *rel_hash = rh;
10346
10347                       continue;
10348                     }
10349
10350                   /* This is a reloc against a local symbol.  */
10351
10352                   *rel_hash = NULL;
10353                   sym = isymbuf[r_symndx];
10354                   sec = flinfo->sections[r_symndx];
10355                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10356                     {
10357                       /* I suppose the backend ought to fill in the
10358                          section of any STT_SECTION symbol against a
10359                          processor specific section.  */
10360                       r_symndx = STN_UNDEF;
10361                       if (bfd_is_abs_section (sec))
10362                         ;
10363                       else if (sec == NULL || sec->owner == NULL)
10364                         {
10365                           bfd_set_error (bfd_error_bad_value);
10366                           return FALSE;
10367                         }
10368                       else
10369                         {
10370                           asection *osec = sec->output_section;
10371
10372                           /* If we have discarded a section, the output
10373                              section will be the absolute section.  In
10374                              case of discarded SEC_MERGE sections, use
10375                              the kept section.  relocate_section should
10376                              have already handled discarded linkonce
10377                              sections.  */
10378                           if (bfd_is_abs_section (osec)
10379                               && sec->kept_section != NULL
10380                               && sec->kept_section->output_section != NULL)
10381                             {
10382                               osec = sec->kept_section->output_section;
10383                               irela->r_addend -= osec->vma;
10384                             }
10385
10386                           if (!bfd_is_abs_section (osec))
10387                             {
10388                               r_symndx = osec->target_index;
10389                               if (r_symndx == STN_UNDEF)
10390                                 {
10391                                   irela->r_addend += osec->vma;
10392                                   osec = _bfd_nearby_section (output_bfd, osec,
10393                                                               osec->vma);
10394                                   irela->r_addend -= osec->vma;
10395                                   r_symndx = osec->target_index;
10396                                 }
10397                             }
10398                         }
10399
10400                       /* Adjust the addend according to where the
10401                          section winds up in the output section.  */
10402                       if (rela_normal)
10403                         irela->r_addend += sec->output_offset;
10404                     }
10405                   else
10406                     {
10407                       if (flinfo->indices[r_symndx] == -1)
10408                         {
10409                           unsigned long shlink;
10410                           const char *name;
10411                           asection *osec;
10412                           long indx;
10413
10414                           if (flinfo->info->strip == strip_all)
10415                             {
10416                               /* You can't do ld -r -s.  */
10417                               bfd_set_error (bfd_error_invalid_operation);
10418                               return FALSE;
10419                             }
10420
10421                           /* This symbol was skipped earlier, but
10422                              since it is needed by a reloc, we
10423                              must output it now.  */
10424                           shlink = symtab_hdr->sh_link;
10425                           name = (bfd_elf_string_from_elf_section
10426                                   (input_bfd, shlink, sym.st_name));
10427                           if (name == NULL)
10428                             return FALSE;
10429
10430                           osec = sec->output_section;
10431                           sym.st_shndx =
10432                             _bfd_elf_section_from_bfd_section (output_bfd,
10433                                                                osec);
10434                           if (sym.st_shndx == SHN_BAD)
10435                             return FALSE;
10436
10437                           sym.st_value += sec->output_offset;
10438                           if (!bfd_link_relocatable (flinfo->info))
10439                             {
10440                               sym.st_value += osec->vma;
10441                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10442                                 {
10443                                   /* STT_TLS symbols are relative to PT_TLS
10444                                      segment base.  */
10445                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10446                                               ->tls_sec != NULL);
10447                                   sym.st_value -= (elf_hash_table (flinfo->info)
10448                                                    ->tls_sec->vma);
10449                                 }
10450                             }
10451
10452                           indx = bfd_get_symcount (output_bfd);
10453                           ret = elf_link_output_symstrtab (flinfo, name,
10454                                                            &sym, sec,
10455                                                            NULL);
10456                           if (ret == 0)
10457                             return FALSE;
10458                           else if (ret == 1)
10459                             flinfo->indices[r_symndx] = indx;
10460                           else
10461                             abort ();
10462                         }
10463
10464                       r_symndx = flinfo->indices[r_symndx];
10465                     }
10466
10467                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10468                                    | (irela->r_info & r_type_mask));
10469                 }
10470
10471               /* Swap out the relocs.  */
10472               input_rel_hdr = esdi->rel.hdr;
10473               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10474                 {
10475                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10476                                                      input_rel_hdr,
10477                                                      internal_relocs,
10478                                                      rel_hash_list))
10479                     return FALSE;
10480                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10481                                       * bed->s->int_rels_per_ext_rel);
10482                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10483                 }
10484
10485               input_rela_hdr = esdi->rela.hdr;
10486               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10487                 {
10488                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10489                                                      input_rela_hdr,
10490                                                      internal_relocs,
10491                                                      rela_hash_list))
10492                     return FALSE;
10493                 }
10494             }
10495         }
10496
10497       /* Write out the modified section contents.  */
10498       if (bed->elf_backend_write_section
10499           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10500                                                 contents))
10501         {
10502           /* Section written out.  */
10503         }
10504       else switch (o->sec_info_type)
10505         {
10506         case SEC_INFO_TYPE_STABS:
10507           if (! (_bfd_write_section_stabs
10508                  (output_bfd,
10509                   &elf_hash_table (flinfo->info)->stab_info,
10510                   o, &elf_section_data (o)->sec_info, contents)))
10511             return FALSE;
10512           break;
10513         case SEC_INFO_TYPE_MERGE:
10514           if (! _bfd_write_merged_section (output_bfd, o,
10515                                            elf_section_data (o)->sec_info))
10516             return FALSE;
10517           break;
10518         case SEC_INFO_TYPE_EH_FRAME:
10519           {
10520             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10521                                                    o, contents))
10522               return FALSE;
10523           }
10524           break;
10525         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10526           {
10527             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10528                                                          flinfo->info,
10529                                                          o, contents))
10530               return FALSE;
10531           }
10532           break;
10533         default:
10534           {
10535             /* FIXME: octets_per_byte.  */
10536             if (! (o->flags & SEC_EXCLUDE))
10537               {
10538                 file_ptr offset = (file_ptr) o->output_offset;
10539                 bfd_size_type todo = o->size;
10540                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10541                   {
10542                     /* Reverse-copy input section to output.  */
10543                     do
10544                       {
10545                         todo -= address_size;
10546                         if (! bfd_set_section_contents (output_bfd,
10547                                                         o->output_section,
10548                                                         contents + todo,
10549                                                         offset,
10550                                                         address_size))
10551                           return FALSE;
10552                         if (todo == 0)
10553                           break;
10554                         offset += address_size;
10555                       }
10556                     while (1);
10557                   }
10558                 else if (! bfd_set_section_contents (output_bfd,
10559                                                      o->output_section,
10560                                                      contents,
10561                                                      offset, todo))
10562                   return FALSE;
10563               }
10564           }
10565           break;
10566         }
10567     }
10568
10569   return TRUE;
10570 }
10571
10572 /* Generate a reloc when linking an ELF file.  This is a reloc
10573    requested by the linker, and does not come from any input file.  This
10574    is used to build constructor and destructor tables when linking
10575    with -Ur.  */
10576
10577 static bfd_boolean
10578 elf_reloc_link_order (bfd *output_bfd,
10579                       struct bfd_link_info *info,
10580                       asection *output_section,
10581                       struct bfd_link_order *link_order)
10582 {
10583   reloc_howto_type *howto;
10584   long indx;
10585   bfd_vma offset;
10586   bfd_vma addend;
10587   struct bfd_elf_section_reloc_data *reldata;
10588   struct elf_link_hash_entry **rel_hash_ptr;
10589   Elf_Internal_Shdr *rel_hdr;
10590   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10591   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10592   bfd_byte *erel;
10593   unsigned int i;
10594   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10595
10596   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10597   if (howto == NULL)
10598     {
10599       bfd_set_error (bfd_error_bad_value);
10600       return FALSE;
10601     }
10602
10603   addend = link_order->u.reloc.p->addend;
10604
10605   if (esdo->rel.hdr)
10606     reldata = &esdo->rel;
10607   else if (esdo->rela.hdr)
10608     reldata = &esdo->rela;
10609   else
10610     {
10611       reldata = NULL;
10612       BFD_ASSERT (0);
10613     }
10614
10615   /* Figure out the symbol index.  */
10616   rel_hash_ptr = reldata->hashes + reldata->count;
10617   if (link_order->type == bfd_section_reloc_link_order)
10618     {
10619       indx = link_order->u.reloc.p->u.section->target_index;
10620       BFD_ASSERT (indx != 0);
10621       *rel_hash_ptr = NULL;
10622     }
10623   else
10624     {
10625       struct elf_link_hash_entry *h;
10626
10627       /* Treat a reloc against a defined symbol as though it were
10628          actually against the section.  */
10629       h = ((struct elf_link_hash_entry *)
10630            bfd_wrapped_link_hash_lookup (output_bfd, info,
10631                                          link_order->u.reloc.p->u.name,
10632                                          FALSE, FALSE, TRUE));
10633       if (h != NULL
10634           && (h->root.type == bfd_link_hash_defined
10635               || h->root.type == bfd_link_hash_defweak))
10636         {
10637           asection *section;
10638
10639           section = h->root.u.def.section;
10640           indx = section->output_section->target_index;
10641           *rel_hash_ptr = NULL;
10642           /* It seems that we ought to add the symbol value to the
10643              addend here, but in practice it has already been added
10644              because it was passed to constructor_callback.  */
10645           addend += section->output_section->vma + section->output_offset;
10646         }
10647       else if (h != NULL)
10648         {
10649           /* Setting the index to -2 tells elf_link_output_extsym that
10650              this symbol is used by a reloc.  */
10651           h->indx = -2;
10652           *rel_hash_ptr = h;
10653           indx = 0;
10654         }
10655       else
10656         {
10657           if (! ((*info->callbacks->unattached_reloc)
10658                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10659             return FALSE;
10660           indx = 0;
10661         }
10662     }
10663
10664   /* If this is an inplace reloc, we must write the addend into the
10665      object file.  */
10666   if (howto->partial_inplace && addend != 0)
10667     {
10668       bfd_size_type size;
10669       bfd_reloc_status_type rstat;
10670       bfd_byte *buf;
10671       bfd_boolean ok;
10672       const char *sym_name;
10673
10674       size = (bfd_size_type) bfd_get_reloc_size (howto);
10675       buf = (bfd_byte *) bfd_zmalloc (size);
10676       if (buf == NULL && size != 0)
10677         return FALSE;
10678       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10679       switch (rstat)
10680         {
10681         case bfd_reloc_ok:
10682           break;
10683
10684         default:
10685         case bfd_reloc_outofrange:
10686           abort ();
10687
10688         case bfd_reloc_overflow:
10689           if (link_order->type == bfd_section_reloc_link_order)
10690             sym_name = bfd_section_name (output_bfd,
10691                                          link_order->u.reloc.p->u.section);
10692           else
10693             sym_name = link_order->u.reloc.p->u.name;
10694           if (! ((*info->callbacks->reloc_overflow)
10695                  (info, NULL, sym_name, howto->name, addend, NULL,
10696                   NULL, (bfd_vma) 0)))
10697             {
10698               free (buf);
10699               return FALSE;
10700             }
10701           break;
10702         }
10703       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10704                                      link_order->offset, size);
10705       free (buf);
10706       if (! ok)
10707         return FALSE;
10708     }
10709
10710   /* The address of a reloc is relative to the section in a
10711      relocatable file, and is a virtual address in an executable
10712      file.  */
10713   offset = link_order->offset;
10714   if (! bfd_link_relocatable (info))
10715     offset += output_section->vma;
10716
10717   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10718     {
10719       irel[i].r_offset = offset;
10720       irel[i].r_info = 0;
10721       irel[i].r_addend = 0;
10722     }
10723   if (bed->s->arch_size == 32)
10724     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10725   else
10726     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10727
10728   rel_hdr = reldata->hdr;
10729   erel = rel_hdr->contents;
10730   if (rel_hdr->sh_type == SHT_REL)
10731     {
10732       erel += reldata->count * bed->s->sizeof_rel;
10733       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10734     }
10735   else
10736     {
10737       irel[0].r_addend = addend;
10738       erel += reldata->count * bed->s->sizeof_rela;
10739       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10740     }
10741
10742   ++reldata->count;
10743
10744   return TRUE;
10745 }
10746
10747
10748 /* Get the output vma of the section pointed to by the sh_link field.  */
10749
10750 static bfd_vma
10751 elf_get_linked_section_vma (struct bfd_link_order *p)
10752 {
10753   Elf_Internal_Shdr **elf_shdrp;
10754   asection *s;
10755   int elfsec;
10756
10757   s = p->u.indirect.section;
10758   elf_shdrp = elf_elfsections (s->owner);
10759   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10760   elfsec = elf_shdrp[elfsec]->sh_link;
10761   /* PR 290:
10762      The Intel C compiler generates SHT_IA_64_UNWIND with
10763      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10764      sh_info fields.  Hence we could get the situation
10765      where elfsec is 0.  */
10766   if (elfsec == 0)
10767     {
10768       const struct elf_backend_data *bed
10769         = get_elf_backend_data (s->owner);
10770       if (bed->link_order_error_handler)
10771         bed->link_order_error_handler
10772           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10773       return 0;
10774     }
10775   else
10776     {
10777       s = elf_shdrp[elfsec]->bfd_section;
10778       return s->output_section->vma + s->output_offset;
10779     }
10780 }
10781
10782
10783 /* Compare two sections based on the locations of the sections they are
10784    linked to.  Used by elf_fixup_link_order.  */
10785
10786 static int
10787 compare_link_order (const void * a, const void * b)
10788 {
10789   bfd_vma apos;
10790   bfd_vma bpos;
10791
10792   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10793   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10794   if (apos < bpos)
10795     return -1;
10796   return apos > bpos;
10797 }
10798
10799
10800 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10801    order as their linked sections.  Returns false if this could not be done
10802    because an output section includes both ordered and unordered
10803    sections.  Ideally we'd do this in the linker proper.  */
10804
10805 static bfd_boolean
10806 elf_fixup_link_order (bfd *abfd, asection *o)
10807 {
10808   int seen_linkorder;
10809   int seen_other;
10810   int n;
10811   struct bfd_link_order *p;
10812   bfd *sub;
10813   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10814   unsigned elfsec;
10815   struct bfd_link_order **sections;
10816   asection *s, *other_sec, *linkorder_sec;
10817   bfd_vma offset;
10818
10819   other_sec = NULL;
10820   linkorder_sec = NULL;
10821   seen_other = 0;
10822   seen_linkorder = 0;
10823   for (p = o->map_head.link_order; p != NULL; p = p->next)
10824     {
10825       if (p->type == bfd_indirect_link_order)
10826         {
10827           s = p->u.indirect.section;
10828           sub = s->owner;
10829           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10830               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10831               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10832               && elfsec < elf_numsections (sub)
10833               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10834               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10835             {
10836               seen_linkorder++;
10837               linkorder_sec = s;
10838             }
10839           else
10840             {
10841               seen_other++;
10842               other_sec = s;
10843             }
10844         }
10845       else
10846         seen_other++;
10847
10848       if (seen_other && seen_linkorder)
10849         {
10850           if (other_sec && linkorder_sec)
10851             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10852                                    o, linkorder_sec,
10853                                    linkorder_sec->owner, other_sec,
10854                                    other_sec->owner);
10855           else
10856             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10857                                    o);
10858           bfd_set_error (bfd_error_bad_value);
10859           return FALSE;
10860         }
10861     }
10862
10863   if (!seen_linkorder)
10864     return TRUE;
10865
10866   sections = (struct bfd_link_order **)
10867     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10868   if (sections == NULL)
10869     return FALSE;
10870   seen_linkorder = 0;
10871
10872   for (p = o->map_head.link_order; p != NULL; p = p->next)
10873     {
10874       sections[seen_linkorder++] = p;
10875     }
10876   /* Sort the input sections in the order of their linked section.  */
10877   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10878          compare_link_order);
10879
10880   /* Change the offsets of the sections.  */
10881   offset = 0;
10882   for (n = 0; n < seen_linkorder; n++)
10883     {
10884       s = sections[n]->u.indirect.section;
10885       offset &= ~(bfd_vma) 0 << s->alignment_power;
10886       s->output_offset = offset;
10887       sections[n]->offset = offset;
10888       /* FIXME: octets_per_byte.  */
10889       offset += sections[n]->size;
10890     }
10891
10892   free (sections);
10893   return TRUE;
10894 }
10895
10896 static void
10897 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10898 {
10899   asection *o;
10900
10901   if (flinfo->symstrtab != NULL)
10902     _bfd_elf_strtab_free (flinfo->symstrtab);
10903   if (flinfo->contents != NULL)
10904     free (flinfo->contents);
10905   if (flinfo->external_relocs != NULL)
10906     free (flinfo->external_relocs);
10907   if (flinfo->internal_relocs != NULL)
10908     free (flinfo->internal_relocs);
10909   if (flinfo->external_syms != NULL)
10910     free (flinfo->external_syms);
10911   if (flinfo->locsym_shndx != NULL)
10912     free (flinfo->locsym_shndx);
10913   if (flinfo->internal_syms != NULL)
10914     free (flinfo->internal_syms);
10915   if (flinfo->indices != NULL)
10916     free (flinfo->indices);
10917   if (flinfo->sections != NULL)
10918     free (flinfo->sections);
10919   if (flinfo->symshndxbuf != NULL)
10920     free (flinfo->symshndxbuf);
10921   for (o = obfd->sections; o != NULL; o = o->next)
10922     {
10923       struct bfd_elf_section_data *esdo = elf_section_data (o);
10924       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10925         free (esdo->rel.hashes);
10926       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10927         free (esdo->rela.hashes);
10928     }
10929 }
10930
10931 /* Do the final step of an ELF link.  */
10932
10933 bfd_boolean
10934 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10935 {
10936   bfd_boolean dynamic;
10937   bfd_boolean emit_relocs;
10938   bfd *dynobj;
10939   struct elf_final_link_info flinfo;
10940   asection *o;
10941   struct bfd_link_order *p;
10942   bfd *sub;
10943   bfd_size_type max_contents_size;
10944   bfd_size_type max_external_reloc_size;
10945   bfd_size_type max_internal_reloc_count;
10946   bfd_size_type max_sym_count;
10947   bfd_size_type max_sym_shndx_count;
10948   Elf_Internal_Sym elfsym;
10949   unsigned int i;
10950   Elf_Internal_Shdr *symtab_hdr;
10951   Elf_Internal_Shdr *symtab_shndx_hdr;
10952   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10953   struct elf_outext_info eoinfo;
10954   bfd_boolean merged;
10955   size_t relativecount = 0;
10956   asection *reldyn = 0;
10957   bfd_size_type amt;
10958   asection *attr_section = NULL;
10959   bfd_vma attr_size = 0;
10960   const char *std_attrs_section;
10961
10962   if (! is_elf_hash_table (info->hash))
10963     return FALSE;
10964
10965   if (bfd_link_pic (info))
10966     abfd->flags |= DYNAMIC;
10967
10968   dynamic = elf_hash_table (info)->dynamic_sections_created;
10969   dynobj = elf_hash_table (info)->dynobj;
10970
10971   emit_relocs = (bfd_link_relocatable (info)
10972                  || info->emitrelocations);
10973
10974   flinfo.info = info;
10975   flinfo.output_bfd = abfd;
10976   flinfo.symstrtab = _bfd_elf_strtab_init ();
10977   if (flinfo.symstrtab == NULL)
10978     return FALSE;
10979
10980   if (! dynamic)
10981     {
10982       flinfo.hash_sec = NULL;
10983       flinfo.symver_sec = NULL;
10984     }
10985   else
10986     {
10987       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
10988       /* Note that dynsym_sec can be NULL (on VMS).  */
10989       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
10990       /* Note that it is OK if symver_sec is NULL.  */
10991     }
10992
10993   flinfo.contents = NULL;
10994   flinfo.external_relocs = NULL;
10995   flinfo.internal_relocs = NULL;
10996   flinfo.external_syms = NULL;
10997   flinfo.locsym_shndx = NULL;
10998   flinfo.internal_syms = NULL;
10999   flinfo.indices = NULL;
11000   flinfo.sections = NULL;
11001   flinfo.symshndxbuf = NULL;
11002   flinfo.filesym_count = 0;
11003
11004   /* The object attributes have been merged.  Remove the input
11005      sections from the link, and set the contents of the output
11006      secton.  */
11007   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11008   for (o = abfd->sections; o != NULL; o = o->next)
11009     {
11010       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11011           || strcmp (o->name, ".gnu.attributes") == 0)
11012         {
11013           for (p = o->map_head.link_order; p != NULL; p = p->next)
11014             {
11015               asection *input_section;
11016
11017               if (p->type != bfd_indirect_link_order)
11018                 continue;
11019               input_section = p->u.indirect.section;
11020               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11021                  elf_link_input_bfd ignores this section.  */
11022               input_section->flags &= ~SEC_HAS_CONTENTS;
11023             }
11024
11025           attr_size = bfd_elf_obj_attr_size (abfd);
11026           if (attr_size)
11027             {
11028               bfd_set_section_size (abfd, o, attr_size);
11029               attr_section = o;
11030               /* Skip this section later on.  */
11031               o->map_head.link_order = NULL;
11032             }
11033           else
11034             o->flags |= SEC_EXCLUDE;
11035         }
11036     }
11037
11038   /* Count up the number of relocations we will output for each output
11039      section, so that we know the sizes of the reloc sections.  We
11040      also figure out some maximum sizes.  */
11041   max_contents_size = 0;
11042   max_external_reloc_size = 0;
11043   max_internal_reloc_count = 0;
11044   max_sym_count = 0;
11045   max_sym_shndx_count = 0;
11046   merged = FALSE;
11047   for (o = abfd->sections; o != NULL; o = o->next)
11048     {
11049       struct bfd_elf_section_data *esdo = elf_section_data (o);
11050       o->reloc_count = 0;
11051
11052       for (p = o->map_head.link_order; p != NULL; p = p->next)
11053         {
11054           unsigned int reloc_count = 0;
11055           unsigned int additional_reloc_count = 0;
11056           struct bfd_elf_section_data *esdi = NULL;
11057
11058           if (p->type == bfd_section_reloc_link_order
11059               || p->type == bfd_symbol_reloc_link_order)
11060             reloc_count = 1;
11061           else if (p->type == bfd_indirect_link_order)
11062             {
11063               asection *sec;
11064
11065               sec = p->u.indirect.section;
11066               esdi = elf_section_data (sec);
11067
11068               /* Mark all sections which are to be included in the
11069                  link.  This will normally be every section.  We need
11070                  to do this so that we can identify any sections which
11071                  the linker has decided to not include.  */
11072               sec->linker_mark = TRUE;
11073
11074               if (sec->flags & SEC_MERGE)
11075                 merged = TRUE;
11076
11077               if (esdo->this_hdr.sh_type == SHT_REL
11078                   || esdo->this_hdr.sh_type == SHT_RELA)
11079                 /* Some backends use reloc_count in relocation sections
11080                    to count particular types of relocs.  Of course,
11081                    reloc sections themselves can't have relocations.  */
11082                 reloc_count = 0;
11083               else if (emit_relocs)
11084                 {
11085                   reloc_count = sec->reloc_count;
11086                   if (bed->elf_backend_count_additional_relocs)
11087                     {
11088                       int c;
11089                       c = (*bed->elf_backend_count_additional_relocs) (sec);
11090                       additional_reloc_count += c;
11091                     }
11092                 }
11093               else if (bed->elf_backend_count_relocs)
11094                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11095
11096               if (sec->rawsize > max_contents_size)
11097                 max_contents_size = sec->rawsize;
11098               if (sec->size > max_contents_size)
11099                 max_contents_size = sec->size;
11100
11101               /* We are interested in just local symbols, not all
11102                  symbols.  */
11103               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11104                   && (sec->owner->flags & DYNAMIC) == 0)
11105                 {
11106                   size_t sym_count;
11107
11108                   if (elf_bad_symtab (sec->owner))
11109                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11110                                  / bed->s->sizeof_sym);
11111                   else
11112                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11113
11114                   if (sym_count > max_sym_count)
11115                     max_sym_count = sym_count;
11116
11117                   if (sym_count > max_sym_shndx_count
11118                       && elf_symtab_shndx_list (sec->owner) != NULL)
11119                     max_sym_shndx_count = sym_count;
11120
11121                   if ((sec->flags & SEC_RELOC) != 0)
11122                     {
11123                       size_t ext_size = 0;
11124
11125                       if (esdi->rel.hdr != NULL)
11126                         ext_size = esdi->rel.hdr->sh_size;
11127                       if (esdi->rela.hdr != NULL)
11128                         ext_size += esdi->rela.hdr->sh_size;
11129
11130                       if (ext_size > max_external_reloc_size)
11131                         max_external_reloc_size = ext_size;
11132                       if (sec->reloc_count > max_internal_reloc_count)
11133                         max_internal_reloc_count = sec->reloc_count;
11134                     }
11135                 }
11136             }
11137
11138           if (reloc_count == 0)
11139             continue;
11140
11141           reloc_count += additional_reloc_count;
11142           o->reloc_count += reloc_count;
11143
11144           if (p->type == bfd_indirect_link_order && emit_relocs)
11145             {
11146               if (esdi->rel.hdr)
11147                 {
11148                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11149                   esdo->rel.count += additional_reloc_count;
11150                 }
11151               if (esdi->rela.hdr)
11152                 {
11153                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11154                   esdo->rela.count += additional_reloc_count;
11155                 }
11156             }
11157           else
11158             {
11159               if (o->use_rela_p)
11160                 esdo->rela.count += reloc_count;
11161               else
11162                 esdo->rel.count += reloc_count;
11163             }
11164         }
11165
11166       if (o->reloc_count > 0)
11167         o->flags |= SEC_RELOC;
11168       else
11169         {
11170           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11171              set it (this is probably a bug) and if it is set
11172              assign_section_numbers will create a reloc section.  */
11173           o->flags &=~ SEC_RELOC;
11174         }
11175
11176       /* If the SEC_ALLOC flag is not set, force the section VMA to
11177          zero.  This is done in elf_fake_sections as well, but forcing
11178          the VMA to 0 here will ensure that relocs against these
11179          sections are handled correctly.  */
11180       if ((o->flags & SEC_ALLOC) == 0
11181           && ! o->user_set_vma)
11182         o->vma = 0;
11183     }
11184
11185   if (! bfd_link_relocatable (info) && merged)
11186     elf_link_hash_traverse (elf_hash_table (info),
11187                             _bfd_elf_link_sec_merge_syms, abfd);
11188
11189   /* Figure out the file positions for everything but the symbol table
11190      and the relocs.  We set symcount to force assign_section_numbers
11191      to create a symbol table.  */
11192   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11193   BFD_ASSERT (! abfd->output_has_begun);
11194   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11195     goto error_return;
11196
11197   /* Set sizes, and assign file positions for reloc sections.  */
11198   for (o = abfd->sections; o != NULL; o = o->next)
11199     {
11200       struct bfd_elf_section_data *esdo = elf_section_data (o);
11201       if ((o->flags & SEC_RELOC) != 0)
11202         {
11203           if (esdo->rel.hdr
11204               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11205             goto error_return;
11206
11207           if (esdo->rela.hdr
11208               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11209             goto error_return;
11210         }
11211
11212       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11213          to count upwards while actually outputting the relocations.  */
11214       esdo->rel.count = 0;
11215       esdo->rela.count = 0;
11216
11217       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11218         {
11219           /* Cache the section contents so that they can be compressed
11220              later.  Use bfd_malloc since it will be freed by
11221              bfd_compress_section_contents.  */
11222           unsigned char *contents = esdo->this_hdr.contents;
11223           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11224             abort ();
11225           contents
11226             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11227           if (contents == NULL)
11228             goto error_return;
11229           esdo->this_hdr.contents = contents;
11230         }
11231     }
11232
11233   /* We have now assigned file positions for all the sections except
11234      .symtab, .strtab, and non-loaded reloc sections.  We start the
11235      .symtab section at the current file position, and write directly
11236      to it.  We build the .strtab section in memory.  */
11237   bfd_get_symcount (abfd) = 0;
11238   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11239   /* sh_name is set in prep_headers.  */
11240   symtab_hdr->sh_type = SHT_SYMTAB;
11241   /* sh_flags, sh_addr and sh_size all start off zero.  */
11242   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11243   /* sh_link is set in assign_section_numbers.  */
11244   /* sh_info is set below.  */
11245   /* sh_offset is set just below.  */
11246   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11247
11248   if (max_sym_count < 20)
11249     max_sym_count = 20;
11250   elf_hash_table (info)->strtabsize = max_sym_count;
11251   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11252   elf_hash_table (info)->strtab
11253     = (struct elf_sym_strtab *) bfd_malloc (amt);
11254   if (elf_hash_table (info)->strtab == NULL)
11255     goto error_return;
11256   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11257   flinfo.symshndxbuf
11258     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11259        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11260
11261   if (info->strip != strip_all || emit_relocs)
11262     {
11263       file_ptr off = elf_next_file_pos (abfd);
11264
11265       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11266
11267       /* Note that at this point elf_next_file_pos (abfd) is
11268          incorrect.  We do not yet know the size of the .symtab section.
11269          We correct next_file_pos below, after we do know the size.  */
11270
11271       /* Start writing out the symbol table.  The first symbol is always a
11272          dummy symbol.  */
11273       elfsym.st_value = 0;
11274       elfsym.st_size = 0;
11275       elfsym.st_info = 0;
11276       elfsym.st_other = 0;
11277       elfsym.st_shndx = SHN_UNDEF;
11278       elfsym.st_target_internal = 0;
11279       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11280                                      bfd_und_section_ptr, NULL) != 1)
11281         goto error_return;
11282
11283       /* Output a symbol for each section.  We output these even if we are
11284          discarding local symbols, since they are used for relocs.  These
11285          symbols have no names.  We store the index of each one in the
11286          index field of the section, so that we can find it again when
11287          outputting relocs.  */
11288
11289       elfsym.st_size = 0;
11290       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11291       elfsym.st_other = 0;
11292       elfsym.st_value = 0;
11293       elfsym.st_target_internal = 0;
11294       for (i = 1; i < elf_numsections (abfd); i++)
11295         {
11296           o = bfd_section_from_elf_index (abfd, i);
11297           if (o != NULL)
11298             {
11299               o->target_index = bfd_get_symcount (abfd);
11300               elfsym.st_shndx = i;
11301               if (!bfd_link_relocatable (info))
11302                 elfsym.st_value = o->vma;
11303               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11304                                              NULL) != 1)
11305                 goto error_return;
11306             }
11307         }
11308     }
11309
11310   /* Allocate some memory to hold information read in from the input
11311      files.  */
11312   if (max_contents_size != 0)
11313     {
11314       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11315       if (flinfo.contents == NULL)
11316         goto error_return;
11317     }
11318
11319   if (max_external_reloc_size != 0)
11320     {
11321       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11322       if (flinfo.external_relocs == NULL)
11323         goto error_return;
11324     }
11325
11326   if (max_internal_reloc_count != 0)
11327     {
11328       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11329       amt *= sizeof (Elf_Internal_Rela);
11330       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11331       if (flinfo.internal_relocs == NULL)
11332         goto error_return;
11333     }
11334
11335   if (max_sym_count != 0)
11336     {
11337       amt = max_sym_count * bed->s->sizeof_sym;
11338       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11339       if (flinfo.external_syms == NULL)
11340         goto error_return;
11341
11342       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11343       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11344       if (flinfo.internal_syms == NULL)
11345         goto error_return;
11346
11347       amt = max_sym_count * sizeof (long);
11348       flinfo.indices = (long int *) bfd_malloc (amt);
11349       if (flinfo.indices == NULL)
11350         goto error_return;
11351
11352       amt = max_sym_count * sizeof (asection *);
11353       flinfo.sections = (asection **) bfd_malloc (amt);
11354       if (flinfo.sections == NULL)
11355         goto error_return;
11356     }
11357
11358   if (max_sym_shndx_count != 0)
11359     {
11360       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11361       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11362       if (flinfo.locsym_shndx == NULL)
11363         goto error_return;
11364     }
11365
11366   if (elf_hash_table (info)->tls_sec)
11367     {
11368       bfd_vma base, end = 0;
11369       asection *sec;
11370
11371       for (sec = elf_hash_table (info)->tls_sec;
11372            sec && (sec->flags & SEC_THREAD_LOCAL);
11373            sec = sec->next)
11374         {
11375           bfd_size_type size = sec->size;
11376
11377           if (size == 0
11378               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11379             {
11380               struct bfd_link_order *ord = sec->map_tail.link_order;
11381
11382               if (ord != NULL)
11383                 size = ord->offset + ord->size;
11384             }
11385           end = sec->vma + size;
11386         }
11387       base = elf_hash_table (info)->tls_sec->vma;
11388       /* Only align end of TLS section if static TLS doesn't have special
11389          alignment requirements.  */
11390       if (bed->static_tls_alignment == 1)
11391         end = align_power (end,
11392                            elf_hash_table (info)->tls_sec->alignment_power);
11393       elf_hash_table (info)->tls_size = end - base;
11394     }
11395
11396   /* Reorder SHF_LINK_ORDER sections.  */
11397   for (o = abfd->sections; o != NULL; o = o->next)
11398     {
11399       if (!elf_fixup_link_order (abfd, o))
11400         return FALSE;
11401     }
11402
11403   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11404     return FALSE;
11405
11406   /* Since ELF permits relocations to be against local symbols, we
11407      must have the local symbols available when we do the relocations.
11408      Since we would rather only read the local symbols once, and we
11409      would rather not keep them in memory, we handle all the
11410      relocations for a single input file at the same time.
11411
11412      Unfortunately, there is no way to know the total number of local
11413      symbols until we have seen all of them, and the local symbol
11414      indices precede the global symbol indices.  This means that when
11415      we are generating relocatable output, and we see a reloc against
11416      a global symbol, we can not know the symbol index until we have
11417      finished examining all the local symbols to see which ones we are
11418      going to output.  To deal with this, we keep the relocations in
11419      memory, and don't output them until the end of the link.  This is
11420      an unfortunate waste of memory, but I don't see a good way around
11421      it.  Fortunately, it only happens when performing a relocatable
11422      link, which is not the common case.  FIXME: If keep_memory is set
11423      we could write the relocs out and then read them again; I don't
11424      know how bad the memory loss will be.  */
11425
11426   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11427     sub->output_has_begun = FALSE;
11428   for (o = abfd->sections; o != NULL; o = o->next)
11429     {
11430       for (p = o->map_head.link_order; p != NULL; p = p->next)
11431         {
11432           if (p->type == bfd_indirect_link_order
11433               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11434                   == bfd_target_elf_flavour)
11435               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11436             {
11437               if (! sub->output_has_begun)
11438                 {
11439                   if (! elf_link_input_bfd (&flinfo, sub))
11440                     goto error_return;
11441                   sub->output_has_begun = TRUE;
11442                 }
11443             }
11444           else if (p->type == bfd_section_reloc_link_order
11445                    || p->type == bfd_symbol_reloc_link_order)
11446             {
11447               if (! elf_reloc_link_order (abfd, info, o, p))
11448                 goto error_return;
11449             }
11450           else
11451             {
11452               if (! _bfd_default_link_order (abfd, info, o, p))
11453                 {
11454                   if (p->type == bfd_indirect_link_order
11455                       && (bfd_get_flavour (sub)
11456                           == bfd_target_elf_flavour)
11457                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11458                           != bed->s->elfclass))
11459                     {
11460                       const char *iclass, *oclass;
11461
11462                       switch (bed->s->elfclass)
11463                         {
11464                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11465                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11466                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11467                         default: abort ();
11468                         }
11469
11470                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11471                         {
11472                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11473                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11474                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11475                         default: abort ();
11476                         }
11477
11478                       bfd_set_error (bfd_error_wrong_format);
11479                       (*_bfd_error_handler)
11480                         (_("%B: file class %s incompatible with %s"),
11481                          sub, iclass, oclass);
11482                     }
11483
11484                   goto error_return;
11485                 }
11486             }
11487         }
11488     }
11489
11490   /* Free symbol buffer if needed.  */
11491   if (!info->reduce_memory_overheads)
11492     {
11493       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11494         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11495             && elf_tdata (sub)->symbuf)
11496           {
11497             free (elf_tdata (sub)->symbuf);
11498             elf_tdata (sub)->symbuf = NULL;
11499           }
11500     }
11501
11502   /* Output any global symbols that got converted to local in a
11503      version script or due to symbol visibility.  We do this in a
11504      separate step since ELF requires all local symbols to appear
11505      prior to any global symbols.  FIXME: We should only do this if
11506      some global symbols were, in fact, converted to become local.
11507      FIXME: Will this work correctly with the Irix 5 linker?  */
11508   eoinfo.failed = FALSE;
11509   eoinfo.flinfo = &flinfo;
11510   eoinfo.localsyms = TRUE;
11511   eoinfo.file_sym_done = FALSE;
11512   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11513   if (eoinfo.failed)
11514     return FALSE;
11515
11516   /* If backend needs to output some local symbols not present in the hash
11517      table, do it now.  */
11518   if (bed->elf_backend_output_arch_local_syms
11519       && (info->strip != strip_all || emit_relocs))
11520     {
11521       typedef int (*out_sym_func)
11522         (void *, const char *, Elf_Internal_Sym *, asection *,
11523          struct elf_link_hash_entry *);
11524
11525       if (! ((*bed->elf_backend_output_arch_local_syms)
11526              (abfd, info, &flinfo,
11527               (out_sym_func) elf_link_output_symstrtab)))
11528         return FALSE;
11529     }
11530
11531   /* That wrote out all the local symbols.  Finish up the symbol table
11532      with the global symbols. Even if we want to strip everything we
11533      can, we still need to deal with those global symbols that got
11534      converted to local in a version script.  */
11535
11536   /* The sh_info field records the index of the first non local symbol.  */
11537   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11538
11539   if (dynamic
11540       && elf_hash_table (info)->dynsym != NULL
11541       && (elf_hash_table (info)->dynsym->output_section
11542           != bfd_abs_section_ptr))
11543     {
11544       Elf_Internal_Sym sym;
11545       bfd_byte *dynsym = elf_hash_table (info)->dynsym->contents;
11546       long last_local = 0;
11547
11548       /* Write out the section symbols for the output sections.  */
11549       if (bfd_link_pic (info)
11550           || elf_hash_table (info)->is_relocatable_executable)
11551         {
11552           asection *s;
11553
11554           sym.st_size = 0;
11555           sym.st_name = 0;
11556           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11557           sym.st_other = 0;
11558           sym.st_target_internal = 0;
11559
11560           for (s = abfd->sections; s != NULL; s = s->next)
11561             {
11562               int indx;
11563               bfd_byte *dest;
11564               long dynindx;
11565
11566               dynindx = elf_section_data (s)->dynindx;
11567               if (dynindx <= 0)
11568                 continue;
11569               indx = elf_section_data (s)->this_idx;
11570               BFD_ASSERT (indx > 0);
11571               sym.st_shndx = indx;
11572               if (! check_dynsym (abfd, &sym))
11573                 return FALSE;
11574               sym.st_value = s->vma;
11575               dest = dynsym + dynindx * bed->s->sizeof_sym;
11576               if (last_local < dynindx)
11577                 last_local = dynindx;
11578               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11579             }
11580         }
11581
11582       /* Write out the local dynsyms.  */
11583       if (elf_hash_table (info)->dynlocal)
11584         {
11585           struct elf_link_local_dynamic_entry *e;
11586           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11587             {
11588               asection *s;
11589               bfd_byte *dest;
11590
11591               /* Copy the internal symbol and turn off visibility.
11592                  Note that we saved a word of storage and overwrote
11593                  the original st_name with the dynstr_index.  */
11594               sym = e->isym;
11595               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11596
11597               s = bfd_section_from_elf_index (e->input_bfd,
11598                                               e->isym.st_shndx);
11599               if (s != NULL)
11600                 {
11601                   sym.st_shndx =
11602                     elf_section_data (s->output_section)->this_idx;
11603                   if (! check_dynsym (abfd, &sym))
11604                     return FALSE;
11605                   sym.st_value = (s->output_section->vma
11606                                   + s->output_offset
11607                                   + e->isym.st_value);
11608                 }
11609
11610               if (last_local < e->dynindx)
11611                 last_local = e->dynindx;
11612
11613               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11614               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11615             }
11616         }
11617
11618       elf_section_data (elf_hash_table (info)->dynsym->output_section)->this_hdr.sh_info =
11619         last_local + 1;
11620     }
11621
11622   /* We get the global symbols from the hash table.  */
11623   eoinfo.failed = FALSE;
11624   eoinfo.localsyms = FALSE;
11625   eoinfo.flinfo = &flinfo;
11626   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11627   if (eoinfo.failed)
11628     return FALSE;
11629
11630   /* If backend needs to output some symbols not present in the hash
11631      table, do it now.  */
11632   if (bed->elf_backend_output_arch_syms
11633       && (info->strip != strip_all || emit_relocs))
11634     {
11635       typedef int (*out_sym_func)
11636         (void *, const char *, Elf_Internal_Sym *, asection *,
11637          struct elf_link_hash_entry *);
11638
11639       if (! ((*bed->elf_backend_output_arch_syms)
11640              (abfd, info, &flinfo,
11641               (out_sym_func) elf_link_output_symstrtab)))
11642         return FALSE;
11643     }
11644
11645   /* Finalize the .strtab section.  */
11646   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11647
11648   /* Swap out the .strtab section. */
11649   if (!elf_link_swap_symbols_out (&flinfo))
11650     return FALSE;
11651
11652   /* Now we know the size of the symtab section.  */
11653   if (bfd_get_symcount (abfd) > 0)
11654     {
11655       /* Finish up and write out the symbol string table (.strtab)
11656          section.  */
11657       Elf_Internal_Shdr *symstrtab_hdr;
11658       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11659
11660       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
11661       if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
11662         {
11663           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11664           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11665           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11666           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11667           symtab_shndx_hdr->sh_size = amt;
11668
11669           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11670                                                            off, TRUE);
11671
11672           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11673               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11674             return FALSE;
11675         }
11676
11677       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11678       /* sh_name was set in prep_headers.  */
11679       symstrtab_hdr->sh_type = SHT_STRTAB;
11680       symstrtab_hdr->sh_flags = 0;
11681       symstrtab_hdr->sh_addr = 0;
11682       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11683       symstrtab_hdr->sh_entsize = 0;
11684       symstrtab_hdr->sh_link = 0;
11685       symstrtab_hdr->sh_info = 0;
11686       /* sh_offset is set just below.  */
11687       symstrtab_hdr->sh_addralign = 1;
11688
11689       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11690                                                        off, TRUE);
11691       elf_next_file_pos (abfd) = off;
11692
11693       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11694           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11695         return FALSE;
11696     }
11697
11698   /* Adjust the relocs to have the correct symbol indices.  */
11699   for (o = abfd->sections; o != NULL; o = o->next)
11700     {
11701       struct bfd_elf_section_data *esdo = elf_section_data (o);
11702       bfd_boolean sort;
11703       if ((o->flags & SEC_RELOC) == 0)
11704         continue;
11705
11706       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11707       if (esdo->rel.hdr != NULL
11708           && !elf_link_adjust_relocs (abfd, &esdo->rel, sort))
11709         return FALSE;
11710       if (esdo->rela.hdr != NULL
11711           && !elf_link_adjust_relocs (abfd, &esdo->rela, sort))
11712         return FALSE;
11713
11714       /* Set the reloc_count field to 0 to prevent write_relocs from
11715          trying to swap the relocs out itself.  */
11716       o->reloc_count = 0;
11717     }
11718
11719   if (dynamic && info->combreloc && dynobj != NULL)
11720     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11721
11722   /* If we are linking against a dynamic object, or generating a
11723      shared library, finish up the dynamic linking information.  */
11724   if (dynamic)
11725     {
11726       bfd_byte *dyncon, *dynconend;
11727
11728       /* Fix up .dynamic entries.  */
11729       o = bfd_get_linker_section (dynobj, ".dynamic");
11730       BFD_ASSERT (o != NULL);
11731
11732       dyncon = o->contents;
11733       dynconend = o->contents + o->size;
11734       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11735         {
11736           Elf_Internal_Dyn dyn;
11737           const char *name;
11738           unsigned int type;
11739
11740           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11741
11742           switch (dyn.d_tag)
11743             {
11744             default:
11745               continue;
11746             case DT_NULL:
11747               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11748                 {
11749                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11750                     {
11751                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11752                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11753                     default: continue;
11754                     }
11755                   dyn.d_un.d_val = relativecount;
11756                   relativecount = 0;
11757                   break;
11758                 }
11759               continue;
11760
11761             case DT_INIT:
11762               name = info->init_function;
11763               goto get_sym;
11764             case DT_FINI:
11765               name = info->fini_function;
11766             get_sym:
11767               {
11768                 struct elf_link_hash_entry *h;
11769
11770                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11771                                           FALSE, FALSE, TRUE);
11772                 if (h != NULL
11773                     && (h->root.type == bfd_link_hash_defined
11774                         || h->root.type == bfd_link_hash_defweak))
11775                   {
11776                     dyn.d_un.d_ptr = h->root.u.def.value;
11777                     o = h->root.u.def.section;
11778                     if (o->output_section != NULL)
11779                       dyn.d_un.d_ptr += (o->output_section->vma
11780                                          + o->output_offset);
11781                     else
11782                       {
11783                         /* The symbol is imported from another shared
11784                            library and does not apply to this one.  */
11785                         dyn.d_un.d_ptr = 0;
11786                       }
11787                     break;
11788                   }
11789               }
11790               continue;
11791
11792             case DT_PREINIT_ARRAYSZ:
11793               name = ".preinit_array";
11794               goto get_size;
11795             case DT_INIT_ARRAYSZ:
11796               name = ".init_array";
11797               goto get_size;
11798             case DT_FINI_ARRAYSZ:
11799               name = ".fini_array";
11800             get_size:
11801               o = bfd_get_section_by_name (abfd, name);
11802               if (o == NULL)
11803                 {
11804                   (*_bfd_error_handler)
11805                     (_("%B: could not find output section %s"), abfd, name);
11806                   goto error_return;
11807                 }
11808               if (o->size == 0)
11809                 (*_bfd_error_handler)
11810                   (_("warning: %s section has zero size"), name);
11811               dyn.d_un.d_val = o->size;
11812               break;
11813
11814             case DT_PREINIT_ARRAY:
11815               name = ".preinit_array";
11816               goto get_vma;
11817             case DT_INIT_ARRAY:
11818               name = ".init_array";
11819               goto get_vma;
11820             case DT_FINI_ARRAY:
11821               name = ".fini_array";
11822               goto get_vma;
11823
11824             case DT_HASH:
11825               name = ".hash";
11826               goto get_vma;
11827             case DT_GNU_HASH:
11828               name = ".gnu.hash";
11829               goto get_vma;
11830             case DT_STRTAB:
11831               name = ".dynstr";
11832               goto get_vma;
11833             case DT_SYMTAB:
11834               name = ".dynsym";
11835               goto get_vma;
11836             case DT_VERDEF:
11837               name = ".gnu.version_d";
11838               goto get_vma;
11839             case DT_VERNEED:
11840               name = ".gnu.version_r";
11841               goto get_vma;
11842             case DT_VERSYM:
11843               name = ".gnu.version";
11844             get_vma:
11845               o = bfd_get_section_by_name (abfd, name);
11846               if (o == NULL)
11847                 {
11848                   (*_bfd_error_handler)
11849                     (_("%B: could not find output section %s"), abfd, name);
11850                   goto error_return;
11851                 }
11852               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11853                 {
11854                   (*_bfd_error_handler)
11855                     (_("warning: section '%s' is being made into a note"), name);
11856                   bfd_set_error (bfd_error_nonrepresentable_section);
11857                   goto error_return;
11858                 }
11859               dyn.d_un.d_ptr = o->vma;
11860               break;
11861
11862             case DT_REL:
11863             case DT_RELA:
11864             case DT_RELSZ:
11865             case DT_RELASZ:
11866               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11867                 type = SHT_REL;
11868               else
11869                 type = SHT_RELA;
11870               dyn.d_un.d_val = 0;
11871               dyn.d_un.d_ptr = 0;
11872               for (i = 1; i < elf_numsections (abfd); i++)
11873                 {
11874                   Elf_Internal_Shdr *hdr;
11875
11876                   hdr = elf_elfsections (abfd)[i];
11877                   if (hdr->sh_type == type
11878                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11879                     {
11880                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11881                         dyn.d_un.d_val += hdr->sh_size;
11882                       else
11883                         {
11884                           if (dyn.d_un.d_ptr == 0
11885                               || hdr->sh_addr < dyn.d_un.d_ptr)
11886                             dyn.d_un.d_ptr = hdr->sh_addr;
11887                         }
11888                     }
11889                 }
11890               break;
11891             }
11892           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11893         }
11894     }
11895
11896   /* If we have created any dynamic sections, then output them.  */
11897   if (dynobj != NULL)
11898     {
11899       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11900         goto error_return;
11901
11902       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11903       if (((info->warn_shared_textrel && bfd_link_pic (info))
11904            || info->error_textrel)
11905           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11906         {
11907           bfd_byte *dyncon, *dynconend;
11908
11909           dyncon = o->contents;
11910           dynconend = o->contents + o->size;
11911           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11912             {
11913               Elf_Internal_Dyn dyn;
11914
11915               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11916
11917               if (dyn.d_tag == DT_TEXTREL)
11918                 {
11919                   if (info->error_textrel)
11920                     info->callbacks->einfo
11921                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11922                   else
11923                     info->callbacks->einfo
11924                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11925                   break;
11926                 }
11927             }
11928         }
11929
11930       for (o = dynobj->sections; o != NULL; o = o->next)
11931         {
11932           if ((o->flags & SEC_HAS_CONTENTS) == 0
11933               || o->size == 0
11934               || o->output_section == bfd_abs_section_ptr)
11935             continue;
11936           if ((o->flags & SEC_LINKER_CREATED) == 0)
11937             {
11938               /* At this point, we are only interested in sections
11939                  created by _bfd_elf_link_create_dynamic_sections.  */
11940               continue;
11941             }
11942           if (elf_hash_table (info)->stab_info.stabstr == o)
11943             continue;
11944           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11945             continue;
11946           if (strcmp (o->name, ".dynstr") != 0)
11947             {
11948               /* FIXME: octets_per_byte.  */
11949               if (! bfd_set_section_contents (abfd, o->output_section,
11950                                               o->contents,
11951                                               (file_ptr) o->output_offset,
11952                                               o->size))
11953                 goto error_return;
11954             }
11955           else
11956             {
11957               /* The contents of the .dynstr section are actually in a
11958                  stringtab.  */
11959               file_ptr off;
11960
11961               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11962               if (bfd_seek (abfd, off, SEEK_SET) != 0
11963                   || ! _bfd_elf_strtab_emit (abfd,
11964                                              elf_hash_table (info)->dynstr))
11965                 goto error_return;
11966             }
11967         }
11968     }
11969
11970   if (bfd_link_relocatable (info))
11971     {
11972       bfd_boolean failed = FALSE;
11973
11974       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11975       if (failed)
11976         goto error_return;
11977     }
11978
11979   /* If we have optimized stabs strings, output them.  */
11980   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11981     {
11982       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11983         goto error_return;
11984     }
11985
11986   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11987     goto error_return;
11988
11989   elf_final_link_free (abfd, &flinfo);
11990
11991   elf_linker (abfd) = TRUE;
11992
11993   if (attr_section)
11994     {
11995       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11996       if (contents == NULL)
11997         return FALSE;   /* Bail out and fail.  */
11998       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11999       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12000       free (contents);
12001     }
12002
12003   return TRUE;
12004
12005  error_return:
12006   elf_final_link_free (abfd, &flinfo);
12007   return FALSE;
12008 }
12009 \f
12010 /* Initialize COOKIE for input bfd ABFD.  */
12011
12012 static bfd_boolean
12013 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12014                    struct bfd_link_info *info, bfd *abfd)
12015 {
12016   Elf_Internal_Shdr *symtab_hdr;
12017   const struct elf_backend_data *bed;
12018
12019   bed = get_elf_backend_data (abfd);
12020   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12021
12022   cookie->abfd = abfd;
12023   cookie->sym_hashes = elf_sym_hashes (abfd);
12024   cookie->bad_symtab = elf_bad_symtab (abfd);
12025   if (cookie->bad_symtab)
12026     {
12027       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12028       cookie->extsymoff = 0;
12029     }
12030   else
12031     {
12032       cookie->locsymcount = symtab_hdr->sh_info;
12033       cookie->extsymoff = symtab_hdr->sh_info;
12034     }
12035
12036   if (bed->s->arch_size == 32)
12037     cookie->r_sym_shift = 8;
12038   else
12039     cookie->r_sym_shift = 32;
12040
12041   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12042   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12043     {
12044       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12045                                               cookie->locsymcount, 0,
12046                                               NULL, NULL, NULL);
12047       if (cookie->locsyms == NULL)
12048         {
12049           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12050           return FALSE;
12051         }
12052       if (info->keep_memory)
12053         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12054     }
12055   return TRUE;
12056 }
12057
12058 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12059
12060 static void
12061 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12062 {
12063   Elf_Internal_Shdr *symtab_hdr;
12064
12065   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12066   if (cookie->locsyms != NULL
12067       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12068     free (cookie->locsyms);
12069 }
12070
12071 /* Initialize the relocation information in COOKIE for input section SEC
12072    of input bfd ABFD.  */
12073
12074 static bfd_boolean
12075 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12076                         struct bfd_link_info *info, bfd *abfd,
12077                         asection *sec)
12078 {
12079   const struct elf_backend_data *bed;
12080
12081   if (sec->reloc_count == 0)
12082     {
12083       cookie->rels = NULL;
12084       cookie->relend = NULL;
12085     }
12086   else
12087     {
12088       bed = get_elf_backend_data (abfd);
12089
12090       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12091                                                 info->keep_memory);
12092       if (cookie->rels == NULL)
12093         return FALSE;
12094       cookie->rel = cookie->rels;
12095       cookie->relend = (cookie->rels
12096                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12097     }
12098   cookie->rel = cookie->rels;
12099   return TRUE;
12100 }
12101
12102 /* Free the memory allocated by init_reloc_cookie_rels,
12103    if appropriate.  */
12104
12105 static void
12106 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12107                         asection *sec)
12108 {
12109   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12110     free (cookie->rels);
12111 }
12112
12113 /* Initialize the whole of COOKIE for input section SEC.  */
12114
12115 static bfd_boolean
12116 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12117                                struct bfd_link_info *info,
12118                                asection *sec)
12119 {
12120   if (!init_reloc_cookie (cookie, info, sec->owner))
12121     goto error1;
12122   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12123     goto error2;
12124   return TRUE;
12125
12126  error2:
12127   fini_reloc_cookie (cookie, sec->owner);
12128  error1:
12129   return FALSE;
12130 }
12131
12132 /* Free the memory allocated by init_reloc_cookie_for_section,
12133    if appropriate.  */
12134
12135 static void
12136 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12137                                asection *sec)
12138 {
12139   fini_reloc_cookie_rels (cookie, sec);
12140   fini_reloc_cookie (cookie, sec->owner);
12141 }
12142 \f
12143 /* Garbage collect unused sections.  */
12144
12145 /* Default gc_mark_hook.  */
12146
12147 asection *
12148 _bfd_elf_gc_mark_hook (asection *sec,
12149                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12150                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12151                        struct elf_link_hash_entry *h,
12152                        Elf_Internal_Sym *sym)
12153 {
12154   if (h != NULL)
12155     {
12156       switch (h->root.type)
12157         {
12158         case bfd_link_hash_defined:
12159         case bfd_link_hash_defweak:
12160           return h->root.u.def.section;
12161
12162         case bfd_link_hash_common:
12163           return h->root.u.c.p->section;
12164
12165         default:
12166           break;
12167         }
12168     }
12169   else
12170     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12171
12172   return NULL;
12173 }
12174
12175 /* COOKIE->rel describes a relocation against section SEC, which is
12176    a section we've decided to keep.  Return the section that contains
12177    the relocation symbol, or NULL if no section contains it.  */
12178
12179 asection *
12180 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12181                        elf_gc_mark_hook_fn gc_mark_hook,
12182                        struct elf_reloc_cookie *cookie,
12183                        bfd_boolean *start_stop)
12184 {
12185   unsigned long r_symndx;
12186   struct elf_link_hash_entry *h;
12187
12188   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12189   if (r_symndx == STN_UNDEF)
12190     return NULL;
12191
12192   if (r_symndx >= cookie->locsymcount
12193       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12194     {
12195       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12196       if (h == NULL)
12197         {
12198           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12199                                   sec->owner);
12200           return NULL;
12201         }
12202       while (h->root.type == bfd_link_hash_indirect
12203              || h->root.type == bfd_link_hash_warning)
12204         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12205       h->mark = 1;
12206       /* If this symbol is weak and there is a non-weak definition, we
12207          keep the non-weak definition because many backends put
12208          dynamic reloc info on the non-weak definition for code
12209          handling copy relocs.  */
12210       if (h->u.weakdef != NULL)
12211         h->u.weakdef->mark = 1;
12212
12213       if (start_stop != NULL
12214           && (h->root.type == bfd_link_hash_undefined
12215               || h->root.type == bfd_link_hash_undefweak))
12216         {
12217           /* To work around a glibc bug, mark all XXX input sections
12218              when there is an as yet undefined reference to __start_XXX
12219              or __stop_XXX symbols.  The linker will later define such
12220              symbols for orphan input sections that have a name
12221              representable as a C identifier.  */
12222           const char *sec_name = NULL;
12223           if (strncmp (h->root.root.string, "__start_", 8) == 0)
12224             sec_name = h->root.root.string + 8;
12225           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12226             sec_name = h->root.root.string + 7;
12227
12228           if (sec_name != NULL && *sec_name != '\0')
12229             {
12230               bfd *i;
12231
12232               for (i = info->input_bfds; i != NULL; i = i->link.next)
12233                 {
12234                   asection *s = bfd_get_section_by_name (i, sec_name);
12235                   if (s != NULL && !s->gc_mark)
12236                     {
12237                       *start_stop = TRUE;
12238                       return s;
12239                     }
12240                 }
12241             }
12242         }
12243
12244       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12245     }
12246
12247   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12248                           &cookie->locsyms[r_symndx]);
12249 }
12250
12251 /* COOKIE->rel describes a relocation against section SEC, which is
12252    a section we've decided to keep.  Mark the section that contains
12253    the relocation symbol.  */
12254
12255 bfd_boolean
12256 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12257                         asection *sec,
12258                         elf_gc_mark_hook_fn gc_mark_hook,
12259                         struct elf_reloc_cookie *cookie)
12260 {
12261   asection *rsec;
12262   bfd_boolean start_stop = FALSE;
12263
12264   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12265   while (rsec != NULL)
12266     {
12267       if (!rsec->gc_mark)
12268         {
12269           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12270               || (rsec->owner->flags & DYNAMIC) != 0)
12271             rsec->gc_mark = 1;
12272           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12273             return FALSE;
12274         }
12275       if (!start_stop)
12276         break;
12277       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12278     }
12279   return TRUE;
12280 }
12281
12282 /* The mark phase of garbage collection.  For a given section, mark
12283    it and any sections in this section's group, and all the sections
12284    which define symbols to which it refers.  */
12285
12286 bfd_boolean
12287 _bfd_elf_gc_mark (struct bfd_link_info *info,
12288                   asection *sec,
12289                   elf_gc_mark_hook_fn gc_mark_hook)
12290 {
12291   bfd_boolean ret;
12292   asection *group_sec, *eh_frame;
12293
12294   sec->gc_mark = 1;
12295
12296   /* Mark all the sections in the group.  */
12297   group_sec = elf_section_data (sec)->next_in_group;
12298   if (group_sec && !group_sec->gc_mark)
12299     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12300       return FALSE;
12301
12302   /* Look through the section relocs.  */
12303   ret = TRUE;
12304   eh_frame = elf_eh_frame_section (sec->owner);
12305   if ((sec->flags & SEC_RELOC) != 0
12306       && sec->reloc_count > 0
12307       && sec != eh_frame)
12308     {
12309       struct elf_reloc_cookie cookie;
12310
12311       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12312         ret = FALSE;
12313       else
12314         {
12315           for (; cookie.rel < cookie.relend; cookie.rel++)
12316             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12317               {
12318                 ret = FALSE;
12319                 break;
12320               }
12321           fini_reloc_cookie_for_section (&cookie, sec);
12322         }
12323     }
12324
12325   if (ret && eh_frame && elf_fde_list (sec))
12326     {
12327       struct elf_reloc_cookie cookie;
12328
12329       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12330         ret = FALSE;
12331       else
12332         {
12333           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12334                                       gc_mark_hook, &cookie))
12335             ret = FALSE;
12336           fini_reloc_cookie_for_section (&cookie, eh_frame);
12337         }
12338     }
12339
12340   eh_frame = elf_section_eh_frame_entry (sec);
12341   if (ret && eh_frame && !eh_frame->gc_mark)
12342     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12343       ret = FALSE;
12344
12345   return ret;
12346 }
12347
12348 /* Scan and mark sections in a special or debug section group.  */
12349
12350 static void
12351 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12352 {
12353   /* Point to first section of section group.  */
12354   asection *ssec;
12355   /* Used to iterate the section group.  */
12356   asection *msec;
12357
12358   bfd_boolean is_special_grp = TRUE;
12359   bfd_boolean is_debug_grp = TRUE;
12360
12361   /* First scan to see if group contains any section other than debug
12362      and special section.  */
12363   ssec = msec = elf_next_in_group (grp);
12364   do
12365     {
12366       if ((msec->flags & SEC_DEBUGGING) == 0)
12367         is_debug_grp = FALSE;
12368
12369       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12370         is_special_grp = FALSE;
12371
12372       msec = elf_next_in_group (msec);
12373     }
12374   while (msec != ssec);
12375
12376   /* If this is a pure debug section group or pure special section group,
12377      keep all sections in this group.  */
12378   if (is_debug_grp || is_special_grp)
12379     {
12380       do
12381         {
12382           msec->gc_mark = 1;
12383           msec = elf_next_in_group (msec);
12384         }
12385       while (msec != ssec);
12386     }
12387 }
12388
12389 /* Keep debug and special sections.  */
12390
12391 bfd_boolean
12392 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12393                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12394 {
12395   bfd *ibfd;
12396
12397   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12398     {
12399       asection *isec;
12400       bfd_boolean some_kept;
12401       bfd_boolean debug_frag_seen;
12402
12403       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12404         continue;
12405
12406       /* Ensure all linker created sections are kept,
12407          see if any other section is already marked,
12408          and note if we have any fragmented debug sections.  */
12409       debug_frag_seen = some_kept = FALSE;
12410       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12411         {
12412           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12413             isec->gc_mark = 1;
12414           else if (isec->gc_mark)
12415             some_kept = TRUE;
12416
12417           if (debug_frag_seen == FALSE
12418               && (isec->flags & SEC_DEBUGGING)
12419               && CONST_STRNEQ (isec->name, ".debug_line."))
12420             debug_frag_seen = TRUE;
12421         }
12422
12423       /* If no section in this file will be kept, then we can
12424          toss out the debug and special sections.  */
12425       if (!some_kept)
12426         continue;
12427
12428       /* Keep debug and special sections like .comment when they are
12429          not part of a group.  Also keep section groups that contain
12430          just debug sections or special sections.  */
12431       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12432         {
12433           if ((isec->flags & SEC_GROUP) != 0)
12434             _bfd_elf_gc_mark_debug_special_section_group (isec);
12435           else if (((isec->flags & SEC_DEBUGGING) != 0
12436                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12437                    && elf_next_in_group (isec) == NULL)
12438             isec->gc_mark = 1;
12439         }
12440
12441       if (! debug_frag_seen)
12442         continue;
12443
12444       /* Look for CODE sections which are going to be discarded,
12445          and find and discard any fragmented debug sections which
12446          are associated with that code section.  */
12447       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12448         if ((isec->flags & SEC_CODE) != 0
12449             && isec->gc_mark == 0)
12450           {
12451             unsigned int ilen;
12452             asection *dsec;
12453
12454             ilen = strlen (isec->name);
12455
12456             /* Association is determined by the name of the debug section
12457                containing the name of the code section as a suffix.  For
12458                example .debug_line.text.foo is a debug section associated
12459                with .text.foo.  */
12460             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12461               {
12462                 unsigned int dlen;
12463
12464                 if (dsec->gc_mark == 0
12465                     || (dsec->flags & SEC_DEBUGGING) == 0)
12466                   continue;
12467
12468                 dlen = strlen (dsec->name);
12469
12470                 if (dlen > ilen
12471                     && strncmp (dsec->name + (dlen - ilen),
12472                                 isec->name, ilen) == 0)
12473                   {
12474                     dsec->gc_mark = 0;
12475                   }
12476               }
12477           }
12478     }
12479   return TRUE;
12480 }
12481
12482 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12483
12484 struct elf_gc_sweep_symbol_info
12485 {
12486   struct bfd_link_info *info;
12487   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12488                        bfd_boolean);
12489 };
12490
12491 static bfd_boolean
12492 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12493 {
12494   if (!h->mark
12495       && (((h->root.type == bfd_link_hash_defined
12496             || h->root.type == bfd_link_hash_defweak)
12497            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12498                 && h->root.u.def.section->gc_mark))
12499           || h->root.type == bfd_link_hash_undefined
12500           || h->root.type == bfd_link_hash_undefweak))
12501     {
12502       struct elf_gc_sweep_symbol_info *inf;
12503
12504       inf = (struct elf_gc_sweep_symbol_info *) data;
12505       (*inf->hide_symbol) (inf->info, h, TRUE);
12506       h->def_regular = 0;
12507       h->ref_regular = 0;
12508       h->ref_regular_nonweak = 0;
12509     }
12510
12511   return TRUE;
12512 }
12513
12514 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12515
12516 typedef bfd_boolean (*gc_sweep_hook_fn)
12517   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12518
12519 static bfd_boolean
12520 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12521 {
12522   bfd *sub;
12523   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12524   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12525   unsigned long section_sym_count;
12526   struct elf_gc_sweep_symbol_info sweep_info;
12527
12528   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12529     {
12530       asection *o;
12531
12532       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12533           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12534         continue;
12535
12536       for (o = sub->sections; o != NULL; o = o->next)
12537         {
12538           /* When any section in a section group is kept, we keep all
12539              sections in the section group.  If the first member of
12540              the section group is excluded, we will also exclude the
12541              group section.  */
12542           if (o->flags & SEC_GROUP)
12543             {
12544               asection *first = elf_next_in_group (o);
12545               o->gc_mark = first->gc_mark;
12546             }
12547
12548           if (o->gc_mark)
12549             continue;
12550
12551           /* Skip sweeping sections already excluded.  */
12552           if (o->flags & SEC_EXCLUDE)
12553             continue;
12554
12555           /* Since this is early in the link process, it is simple
12556              to remove a section from the output.  */
12557           o->flags |= SEC_EXCLUDE;
12558
12559           if (info->print_gc_sections && o->size != 0)
12560             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12561
12562           /* But we also have to update some of the relocation
12563              info we collected before.  */
12564           if (gc_sweep_hook
12565               && (o->flags & SEC_RELOC) != 0
12566               && o->reloc_count != 0
12567               && !((info->strip == strip_all || info->strip == strip_debugger)
12568                    && (o->flags & SEC_DEBUGGING) != 0)
12569               && !bfd_is_abs_section (o->output_section))
12570             {
12571               Elf_Internal_Rela *internal_relocs;
12572               bfd_boolean r;
12573
12574               internal_relocs
12575                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12576                                              info->keep_memory);
12577               if (internal_relocs == NULL)
12578                 return FALSE;
12579
12580               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12581
12582               if (elf_section_data (o)->relocs != internal_relocs)
12583                 free (internal_relocs);
12584
12585               if (!r)
12586                 return FALSE;
12587             }
12588         }
12589     }
12590
12591   /* Remove the symbols that were in the swept sections from the dynamic
12592      symbol table.  GCFIXME: Anyone know how to get them out of the
12593      static symbol table as well?  */
12594   sweep_info.info = info;
12595   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12596   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12597                           &sweep_info);
12598
12599   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12600   return TRUE;
12601 }
12602
12603 /* Propagate collected vtable information.  This is called through
12604    elf_link_hash_traverse.  */
12605
12606 static bfd_boolean
12607 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12608 {
12609   /* Those that are not vtables.  */
12610   if (h->vtable == NULL || h->vtable->parent == NULL)
12611     return TRUE;
12612
12613   /* Those vtables that do not have parents, we cannot merge.  */
12614   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12615     return TRUE;
12616
12617   /* If we've already been done, exit.  */
12618   if (h->vtable->used && h->vtable->used[-1])
12619     return TRUE;
12620
12621   /* Make sure the parent's table is up to date.  */
12622   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12623
12624   if (h->vtable->used == NULL)
12625     {
12626       /* None of this table's entries were referenced.  Re-use the
12627          parent's table.  */
12628       h->vtable->used = h->vtable->parent->vtable->used;
12629       h->vtable->size = h->vtable->parent->vtable->size;
12630     }
12631   else
12632     {
12633       size_t n;
12634       bfd_boolean *cu, *pu;
12635
12636       /* Or the parent's entries into ours.  */
12637       cu = h->vtable->used;
12638       cu[-1] = TRUE;
12639       pu = h->vtable->parent->vtable->used;
12640       if (pu != NULL)
12641         {
12642           const struct elf_backend_data *bed;
12643           unsigned int log_file_align;
12644
12645           bed = get_elf_backend_data (h->root.u.def.section->owner);
12646           log_file_align = bed->s->log_file_align;
12647           n = h->vtable->parent->vtable->size >> log_file_align;
12648           while (n--)
12649             {
12650               if (*pu)
12651                 *cu = TRUE;
12652               pu++;
12653               cu++;
12654             }
12655         }
12656     }
12657
12658   return TRUE;
12659 }
12660
12661 static bfd_boolean
12662 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12663 {
12664   asection *sec;
12665   bfd_vma hstart, hend;
12666   Elf_Internal_Rela *relstart, *relend, *rel;
12667   const struct elf_backend_data *bed;
12668   unsigned int log_file_align;
12669
12670   /* Take care of both those symbols that do not describe vtables as
12671      well as those that are not loaded.  */
12672   if (h->vtable == NULL || h->vtable->parent == NULL)
12673     return TRUE;
12674
12675   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12676               || h->root.type == bfd_link_hash_defweak);
12677
12678   sec = h->root.u.def.section;
12679   hstart = h->root.u.def.value;
12680   hend = hstart + h->size;
12681
12682   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12683   if (!relstart)
12684     return *(bfd_boolean *) okp = FALSE;
12685   bed = get_elf_backend_data (sec->owner);
12686   log_file_align = bed->s->log_file_align;
12687
12688   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12689
12690   for (rel = relstart; rel < relend; ++rel)
12691     if (rel->r_offset >= hstart && rel->r_offset < hend)
12692       {
12693         /* If the entry is in use, do nothing.  */
12694         if (h->vtable->used
12695             && (rel->r_offset - hstart) < h->vtable->size)
12696           {
12697             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12698             if (h->vtable->used[entry])
12699               continue;
12700           }
12701         /* Otherwise, kill it.  */
12702         rel->r_offset = rel->r_info = rel->r_addend = 0;
12703       }
12704
12705   return TRUE;
12706 }
12707
12708 /* Mark sections containing dynamically referenced symbols.  When
12709    building shared libraries, we must assume that any visible symbol is
12710    referenced.  */
12711
12712 bfd_boolean
12713 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12714 {
12715   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12716   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12717
12718   if ((h->root.type == bfd_link_hash_defined
12719        || h->root.type == bfd_link_hash_defweak)
12720       && (h->ref_dynamic
12721           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12722               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12723               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12724               && (!bfd_link_executable (info)
12725                   || info->export_dynamic
12726                   || (h->dynamic
12727                       && d != NULL
12728                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12729               && (h->versioned >= versioned
12730                   || !bfd_hide_sym_by_version (info->version_info,
12731                                                h->root.root.string)))))
12732     h->root.u.def.section->flags |= SEC_KEEP;
12733
12734   return TRUE;
12735 }
12736
12737 /* Keep all sections containing symbols undefined on the command-line,
12738    and the section containing the entry symbol.  */
12739
12740 void
12741 _bfd_elf_gc_keep (struct bfd_link_info *info)
12742 {
12743   struct bfd_sym_chain *sym;
12744
12745   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12746     {
12747       struct elf_link_hash_entry *h;
12748
12749       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12750                                 FALSE, FALSE, FALSE);
12751
12752       if (h != NULL
12753           && (h->root.type == bfd_link_hash_defined
12754               || h->root.type == bfd_link_hash_defweak)
12755           && !bfd_is_abs_section (h->root.u.def.section))
12756         h->root.u.def.section->flags |= SEC_KEEP;
12757     }
12758 }
12759
12760 bfd_boolean
12761 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
12762                                 struct bfd_link_info *info)
12763 {
12764   bfd *ibfd = info->input_bfds;
12765
12766   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12767     {
12768       asection *sec;
12769       struct elf_reloc_cookie cookie;
12770
12771       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12772         continue;
12773
12774       if (!init_reloc_cookie (&cookie, info, ibfd))
12775         return FALSE;
12776
12777       for (sec = ibfd->sections; sec; sec = sec->next)
12778         {
12779           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
12780               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
12781             {
12782               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
12783               fini_reloc_cookie_rels (&cookie, sec);
12784             }
12785         }
12786     }
12787   return TRUE;
12788 }
12789
12790 /* Do mark and sweep of unused sections.  */
12791
12792 bfd_boolean
12793 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12794 {
12795   bfd_boolean ok = TRUE;
12796   bfd *sub;
12797   elf_gc_mark_hook_fn gc_mark_hook;
12798   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12799   struct elf_link_hash_table *htab;
12800
12801   if (!bed->can_gc_sections
12802       || !is_elf_hash_table (info->hash))
12803     {
12804       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12805       return TRUE;
12806     }
12807
12808   bed->gc_keep (info);
12809   htab = elf_hash_table (info);
12810
12811   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12812      at the .eh_frame section if we can mark the FDEs individually.  */
12813   for (sub = info->input_bfds;
12814        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
12815        sub = sub->link.next)
12816     {
12817       asection *sec;
12818       struct elf_reloc_cookie cookie;
12819
12820       sec = bfd_get_section_by_name (sub, ".eh_frame");
12821       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12822         {
12823           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12824           if (elf_section_data (sec)->sec_info
12825               && (sec->flags & SEC_LINKER_CREATED) == 0)
12826             elf_eh_frame_section (sub) = sec;
12827           fini_reloc_cookie_for_section (&cookie, sec);
12828           sec = bfd_get_next_section_by_name (NULL, sec);
12829         }
12830     }
12831
12832   /* Apply transitive closure to the vtable entry usage info.  */
12833   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12834   if (!ok)
12835     return FALSE;
12836
12837   /* Kill the vtable relocations that were not used.  */
12838   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12839   if (!ok)
12840     return FALSE;
12841
12842   /* Mark dynamically referenced symbols.  */
12843   if (htab->dynamic_sections_created)
12844     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12845
12846   /* Grovel through relocs to find out who stays ...  */
12847   gc_mark_hook = bed->gc_mark_hook;
12848   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12849     {
12850       asection *o;
12851
12852       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12853           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12854         continue;
12855
12856       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12857          Also treat note sections as a root, if the section is not part
12858          of a group.  */
12859       for (o = sub->sections; o != NULL; o = o->next)
12860         if (!o->gc_mark
12861             && (o->flags & SEC_EXCLUDE) == 0
12862             && ((o->flags & SEC_KEEP) != 0
12863                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12864                     && elf_next_in_group (o) == NULL )))
12865           {
12866             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12867               return FALSE;
12868           }
12869     }
12870
12871   /* Allow the backend to mark additional target specific sections.  */
12872   bed->gc_mark_extra_sections (info, gc_mark_hook);
12873
12874   /* ... and mark SEC_EXCLUDE for those that go.  */
12875   return elf_gc_sweep (abfd, info);
12876 }
12877 \f
12878 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12879
12880 bfd_boolean
12881 bfd_elf_gc_record_vtinherit (bfd *abfd,
12882                              asection *sec,
12883                              struct elf_link_hash_entry *h,
12884                              bfd_vma offset)
12885 {
12886   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12887   struct elf_link_hash_entry **search, *child;
12888   bfd_size_type extsymcount;
12889   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12890
12891   /* The sh_info field of the symtab header tells us where the
12892      external symbols start.  We don't care about the local symbols at
12893      this point.  */
12894   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12895   if (!elf_bad_symtab (abfd))
12896     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12897
12898   sym_hashes = elf_sym_hashes (abfd);
12899   sym_hashes_end = sym_hashes + extsymcount;
12900
12901   /* Hunt down the child symbol, which is in this section at the same
12902      offset as the relocation.  */
12903   for (search = sym_hashes; search != sym_hashes_end; ++search)
12904     {
12905       if ((child = *search) != NULL
12906           && (child->root.type == bfd_link_hash_defined
12907               || child->root.type == bfd_link_hash_defweak)
12908           && child->root.u.def.section == sec
12909           && child->root.u.def.value == offset)
12910         goto win;
12911     }
12912
12913   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12914                          abfd, sec, (unsigned long) offset);
12915   bfd_set_error (bfd_error_invalid_operation);
12916   return FALSE;
12917
12918  win:
12919   if (!child->vtable)
12920     {
12921       child->vtable = ((struct elf_link_virtual_table_entry *)
12922                        bfd_zalloc (abfd, sizeof (*child->vtable)));
12923       if (!child->vtable)
12924         return FALSE;
12925     }
12926   if (!h)
12927     {
12928       /* This *should* only be the absolute section.  It could potentially
12929          be that someone has defined a non-global vtable though, which
12930          would be bad.  It isn't worth paging in the local symbols to be
12931          sure though; that case should simply be handled by the assembler.  */
12932
12933       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12934     }
12935   else
12936     child->vtable->parent = h;
12937
12938   return TRUE;
12939 }
12940
12941 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12942
12943 bfd_boolean
12944 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12945                            asection *sec ATTRIBUTE_UNUSED,
12946                            struct elf_link_hash_entry *h,
12947                            bfd_vma addend)
12948 {
12949   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12950   unsigned int log_file_align = bed->s->log_file_align;
12951
12952   if (!h->vtable)
12953     {
12954       h->vtable = ((struct elf_link_virtual_table_entry *)
12955                    bfd_zalloc (abfd, sizeof (*h->vtable)));
12956       if (!h->vtable)
12957         return FALSE;
12958     }
12959
12960   if (addend >= h->vtable->size)
12961     {
12962       size_t size, bytes, file_align;
12963       bfd_boolean *ptr = h->vtable->used;
12964
12965       /* While the symbol is undefined, we have to be prepared to handle
12966          a zero size.  */
12967       file_align = 1 << log_file_align;
12968       if (h->root.type == bfd_link_hash_undefined)
12969         size = addend + file_align;
12970       else
12971         {
12972           size = h->size;
12973           if (addend >= size)
12974             {
12975               /* Oops!  We've got a reference past the defined end of
12976                  the table.  This is probably a bug -- shall we warn?  */
12977               size = addend + file_align;
12978             }
12979         }
12980       size = (size + file_align - 1) & -file_align;
12981
12982       /* Allocate one extra entry for use as a "done" flag for the
12983          consolidation pass.  */
12984       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12985
12986       if (ptr)
12987         {
12988           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12989
12990           if (ptr != NULL)
12991             {
12992               size_t oldbytes;
12993
12994               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12995                           * sizeof (bfd_boolean));
12996               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12997             }
12998         }
12999       else
13000         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13001
13002       if (ptr == NULL)
13003         return FALSE;
13004
13005       /* And arrange for that done flag to be at index -1.  */
13006       h->vtable->used = ptr + 1;
13007       h->vtable->size = size;
13008     }
13009
13010   h->vtable->used[addend >> log_file_align] = TRUE;
13011
13012   return TRUE;
13013 }
13014
13015 /* Map an ELF section header flag to its corresponding string.  */
13016 typedef struct
13017 {
13018   char *flag_name;
13019   flagword flag_value;
13020 } elf_flags_to_name_table;
13021
13022 static elf_flags_to_name_table elf_flags_to_names [] =
13023 {
13024   { "SHF_WRITE", SHF_WRITE },
13025   { "SHF_ALLOC", SHF_ALLOC },
13026   { "SHF_EXECINSTR", SHF_EXECINSTR },
13027   { "SHF_MERGE", SHF_MERGE },
13028   { "SHF_STRINGS", SHF_STRINGS },
13029   { "SHF_INFO_LINK", SHF_INFO_LINK},
13030   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13031   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13032   { "SHF_GROUP", SHF_GROUP },
13033   { "SHF_TLS", SHF_TLS },
13034   { "SHF_MASKOS", SHF_MASKOS },
13035   { "SHF_EXCLUDE", SHF_EXCLUDE },
13036 };
13037
13038 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13039 bfd_boolean
13040 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13041                               struct flag_info *flaginfo,
13042                               asection *section)
13043 {
13044   const bfd_vma sh_flags = elf_section_flags (section);
13045
13046   if (!flaginfo->flags_initialized)
13047     {
13048       bfd *obfd = info->output_bfd;
13049       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13050       struct flag_info_list *tf = flaginfo->flag_list;
13051       int with_hex = 0;
13052       int without_hex = 0;
13053
13054       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13055         {
13056           unsigned i;
13057           flagword (*lookup) (char *);
13058
13059           lookup = bed->elf_backend_lookup_section_flags_hook;
13060           if (lookup != NULL)
13061             {
13062               flagword hexval = (*lookup) ((char *) tf->name);
13063
13064               if (hexval != 0)
13065                 {
13066                   if (tf->with == with_flags)
13067                     with_hex |= hexval;
13068                   else if (tf->with == without_flags)
13069                     without_hex |= hexval;
13070                   tf->valid = TRUE;
13071                   continue;
13072                 }
13073             }
13074           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13075             {
13076               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13077                 {
13078                   if (tf->with == with_flags)
13079                     with_hex |= elf_flags_to_names[i].flag_value;
13080                   else if (tf->with == without_flags)
13081                     without_hex |= elf_flags_to_names[i].flag_value;
13082                   tf->valid = TRUE;
13083                   break;
13084                 }
13085             }
13086           if (!tf->valid)
13087             {
13088               info->callbacks->einfo
13089                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13090               return FALSE;
13091             }
13092         }
13093       flaginfo->flags_initialized = TRUE;
13094       flaginfo->only_with_flags |= with_hex;
13095       flaginfo->not_with_flags |= without_hex;
13096     }
13097
13098   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13099     return FALSE;
13100
13101   if ((flaginfo->not_with_flags & sh_flags) != 0)
13102     return FALSE;
13103
13104   return TRUE;
13105 }
13106
13107 struct alloc_got_off_arg {
13108   bfd_vma gotoff;
13109   struct bfd_link_info *info;
13110 };
13111
13112 /* We need a special top-level link routine to convert got reference counts
13113    to real got offsets.  */
13114
13115 static bfd_boolean
13116 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13117 {
13118   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13119   bfd *obfd = gofarg->info->output_bfd;
13120   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13121
13122   if (h->got.refcount > 0)
13123     {
13124       h->got.offset = gofarg->gotoff;
13125       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13126     }
13127   else
13128     h->got.offset = (bfd_vma) -1;
13129
13130   return TRUE;
13131 }
13132
13133 /* And an accompanying bit to work out final got entry offsets once
13134    we're done.  Should be called from final_link.  */
13135
13136 bfd_boolean
13137 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13138                                         struct bfd_link_info *info)
13139 {
13140   bfd *i;
13141   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13142   bfd_vma gotoff;
13143   struct alloc_got_off_arg gofarg;
13144
13145   BFD_ASSERT (abfd == info->output_bfd);
13146
13147   if (! is_elf_hash_table (info->hash))
13148     return FALSE;
13149
13150   /* The GOT offset is relative to the .got section, but the GOT header is
13151      put into the .got.plt section, if the backend uses it.  */
13152   if (bed->want_got_plt)
13153     gotoff = 0;
13154   else
13155     gotoff = bed->got_header_size;
13156
13157   /* Do the local .got entries first.  */
13158   for (i = info->input_bfds; i; i = i->link.next)
13159     {
13160       bfd_signed_vma *local_got;
13161       bfd_size_type j, locsymcount;
13162       Elf_Internal_Shdr *symtab_hdr;
13163
13164       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13165         continue;
13166
13167       local_got = elf_local_got_refcounts (i);
13168       if (!local_got)
13169         continue;
13170
13171       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13172       if (elf_bad_symtab (i))
13173         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13174       else
13175         locsymcount = symtab_hdr->sh_info;
13176
13177       for (j = 0; j < locsymcount; ++j)
13178         {
13179           if (local_got[j] > 0)
13180             {
13181               local_got[j] = gotoff;
13182               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13183             }
13184           else
13185             local_got[j] = (bfd_vma) -1;
13186         }
13187     }
13188
13189   /* Then the global .got entries.  .plt refcounts are handled by
13190      adjust_dynamic_symbol  */
13191   gofarg.gotoff = gotoff;
13192   gofarg.info = info;
13193   elf_link_hash_traverse (elf_hash_table (info),
13194                           elf_gc_allocate_got_offsets,
13195                           &gofarg);
13196   return TRUE;
13197 }
13198
13199 /* Many folk need no more in the way of final link than this, once
13200    got entry reference counting is enabled.  */
13201
13202 bfd_boolean
13203 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13204 {
13205   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13206     return FALSE;
13207
13208   /* Invoke the regular ELF backend linker to do all the work.  */
13209   return bfd_elf_final_link (abfd, info);
13210 }
13211
13212 bfd_boolean
13213 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13214 {
13215   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13216
13217   if (rcookie->bad_symtab)
13218     rcookie->rel = rcookie->rels;
13219
13220   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13221     {
13222       unsigned long r_symndx;
13223
13224       if (! rcookie->bad_symtab)
13225         if (rcookie->rel->r_offset > offset)
13226           return FALSE;
13227       if (rcookie->rel->r_offset != offset)
13228         continue;
13229
13230       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13231       if (r_symndx == STN_UNDEF)
13232         return TRUE;
13233
13234       if (r_symndx >= rcookie->locsymcount
13235           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13236         {
13237           struct elf_link_hash_entry *h;
13238
13239           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13240
13241           while (h->root.type == bfd_link_hash_indirect
13242                  || h->root.type == bfd_link_hash_warning)
13243             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13244
13245           if ((h->root.type == bfd_link_hash_defined
13246                || h->root.type == bfd_link_hash_defweak)
13247               && (h->root.u.def.section->owner != rcookie->abfd
13248                   || h->root.u.def.section->kept_section != NULL
13249                   || discarded_section (h->root.u.def.section)))
13250             return TRUE;
13251         }
13252       else
13253         {
13254           /* It's not a relocation against a global symbol,
13255              but it could be a relocation against a local
13256              symbol for a discarded section.  */
13257           asection *isec;
13258           Elf_Internal_Sym *isym;
13259
13260           /* Need to: get the symbol; get the section.  */
13261           isym = &rcookie->locsyms[r_symndx];
13262           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13263           if (isec != NULL
13264               && (isec->kept_section != NULL
13265                   || discarded_section (isec)))
13266             return TRUE;
13267         }
13268       return FALSE;
13269     }
13270   return FALSE;
13271 }
13272
13273 /* Discard unneeded references to discarded sections.
13274    Returns -1 on error, 1 if any section's size was changed, 0 if
13275    nothing changed.  This function assumes that the relocations are in
13276    sorted order, which is true for all known assemblers.  */
13277
13278 int
13279 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13280 {
13281   struct elf_reloc_cookie cookie;
13282   asection *o;
13283   bfd *abfd;
13284   int changed = 0;
13285
13286   if (info->traditional_format
13287       || !is_elf_hash_table (info->hash))
13288     return 0;
13289
13290   o = bfd_get_section_by_name (output_bfd, ".stab");
13291   if (o != NULL)
13292     {
13293       asection *i;
13294
13295       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13296         {
13297           if (i->size == 0
13298               || i->reloc_count == 0
13299               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13300             continue;
13301
13302           abfd = i->owner;
13303           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13304             continue;
13305
13306           if (!init_reloc_cookie_for_section (&cookie, info, i))
13307             return -1;
13308
13309           if (_bfd_discard_section_stabs (abfd, i,
13310                                           elf_section_data (i)->sec_info,
13311                                           bfd_elf_reloc_symbol_deleted_p,
13312                                           &cookie))
13313             changed = 1;
13314
13315           fini_reloc_cookie_for_section (&cookie, i);
13316         }
13317     }
13318
13319   o = NULL;
13320   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13321     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13322   if (o != NULL)
13323     {
13324       asection *i;
13325
13326       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13327         {
13328           if (i->size == 0)
13329             continue;
13330
13331           abfd = i->owner;
13332           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13333             continue;
13334
13335           if (!init_reloc_cookie_for_section (&cookie, info, i))
13336             return -1;
13337
13338           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13339           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13340                                                  bfd_elf_reloc_symbol_deleted_p,
13341                                                  &cookie))
13342             changed = 1;
13343
13344           fini_reloc_cookie_for_section (&cookie, i);
13345         }
13346     }
13347
13348   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13349     {
13350       const struct elf_backend_data *bed;
13351
13352       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13353         continue;
13354
13355       bed = get_elf_backend_data (abfd);
13356
13357       if (bed->elf_backend_discard_info != NULL)
13358         {
13359           if (!init_reloc_cookie (&cookie, info, abfd))
13360             return -1;
13361
13362           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13363             changed = 1;
13364
13365           fini_reloc_cookie (&cookie, abfd);
13366         }
13367     }
13368
13369   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13370     _bfd_elf_end_eh_frame_parsing (info);
13371
13372   if (info->eh_frame_hdr_type
13373       && !bfd_link_relocatable (info)
13374       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13375     changed = 1;
13376
13377   return changed;
13378 }
13379
13380 bfd_boolean
13381 _bfd_elf_section_already_linked (bfd *abfd,
13382                                  asection *sec,
13383                                  struct bfd_link_info *info)
13384 {
13385   flagword flags;
13386   const char *name, *key;
13387   struct bfd_section_already_linked *l;
13388   struct bfd_section_already_linked_hash_entry *already_linked_list;
13389
13390   if (sec->output_section == bfd_abs_section_ptr)
13391     return FALSE;
13392
13393   flags = sec->flags;
13394
13395   /* Return if it isn't a linkonce section.  A comdat group section
13396      also has SEC_LINK_ONCE set.  */
13397   if ((flags & SEC_LINK_ONCE) == 0)
13398     return FALSE;
13399
13400   /* Don't put group member sections on our list of already linked
13401      sections.  They are handled as a group via their group section.  */
13402   if (elf_sec_group (sec) != NULL)
13403     return FALSE;
13404
13405   /* For a SHT_GROUP section, use the group signature as the key.  */
13406   name = sec->name;
13407   if ((flags & SEC_GROUP) != 0
13408       && elf_next_in_group (sec) != NULL
13409       && elf_group_name (elf_next_in_group (sec)) != NULL)
13410     key = elf_group_name (elf_next_in_group (sec));
13411   else
13412     {
13413       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13414       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13415           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13416         key++;
13417       else
13418         /* Must be a user linkonce section that doesn't follow gcc's
13419            naming convention.  In this case we won't be matching
13420            single member groups.  */
13421         key = name;
13422     }
13423
13424   already_linked_list = bfd_section_already_linked_table_lookup (key);
13425
13426   for (l = already_linked_list->entry; l != NULL; l = l->next)
13427     {
13428       /* We may have 2 different types of sections on the list: group
13429          sections with a signature of <key> (<key> is some string),
13430          and linkonce sections named .gnu.linkonce.<type>.<key>.
13431          Match like sections.  LTO plugin sections are an exception.
13432          They are always named .gnu.linkonce.t.<key> and match either
13433          type of section.  */
13434       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13435            && ((flags & SEC_GROUP) != 0
13436                || strcmp (name, l->sec->name) == 0))
13437           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13438         {
13439           /* The section has already been linked.  See if we should
13440              issue a warning.  */
13441           if (!_bfd_handle_already_linked (sec, l, info))
13442             return FALSE;
13443
13444           if (flags & SEC_GROUP)
13445             {
13446               asection *first = elf_next_in_group (sec);
13447               asection *s = first;
13448
13449               while (s != NULL)
13450                 {
13451                   s->output_section = bfd_abs_section_ptr;
13452                   /* Record which group discards it.  */
13453                   s->kept_section = l->sec;
13454                   s = elf_next_in_group (s);
13455                   /* These lists are circular.  */
13456                   if (s == first)
13457                     break;
13458                 }
13459             }
13460
13461           return TRUE;
13462         }
13463     }
13464
13465   /* A single member comdat group section may be discarded by a
13466      linkonce section and vice versa.  */
13467   if ((flags & SEC_GROUP) != 0)
13468     {
13469       asection *first = elf_next_in_group (sec);
13470
13471       if (first != NULL && elf_next_in_group (first) == first)
13472         /* Check this single member group against linkonce sections.  */
13473         for (l = already_linked_list->entry; l != NULL; l = l->next)
13474           if ((l->sec->flags & SEC_GROUP) == 0
13475               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13476             {
13477               first->output_section = bfd_abs_section_ptr;
13478               first->kept_section = l->sec;
13479               sec->output_section = bfd_abs_section_ptr;
13480               break;
13481             }
13482     }
13483   else
13484     /* Check this linkonce section against single member groups.  */
13485     for (l = already_linked_list->entry; l != NULL; l = l->next)
13486       if (l->sec->flags & SEC_GROUP)
13487         {
13488           asection *first = elf_next_in_group (l->sec);
13489
13490           if (first != NULL
13491               && elf_next_in_group (first) == first
13492               && bfd_elf_match_symbols_in_sections (first, sec, info))
13493             {
13494               sec->output_section = bfd_abs_section_ptr;
13495               sec->kept_section = first;
13496               break;
13497             }
13498         }
13499
13500   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13501      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13502      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13503      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13504      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13505      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13506      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13507      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13508      The reverse order cannot happen as there is never a bfd with only the
13509      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13510      matter as here were are looking only for cross-bfd sections.  */
13511
13512   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13513     for (l = already_linked_list->entry; l != NULL; l = l->next)
13514       if ((l->sec->flags & SEC_GROUP) == 0
13515           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13516         {
13517           if (abfd != l->sec->owner)
13518             sec->output_section = bfd_abs_section_ptr;
13519           break;
13520         }
13521
13522   /* This is the first section with this name.  Record it.  */
13523   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13524     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13525   return sec->output_section == bfd_abs_section_ptr;
13526 }
13527
13528 bfd_boolean
13529 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13530 {
13531   return sym->st_shndx == SHN_COMMON;
13532 }
13533
13534 unsigned int
13535 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13536 {
13537   return SHN_COMMON;
13538 }
13539
13540 asection *
13541 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13542 {
13543   return bfd_com_section_ptr;
13544 }
13545
13546 bfd_vma
13547 _bfd_elf_default_got_elt_size (bfd *abfd,
13548                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13549                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13550                                bfd *ibfd ATTRIBUTE_UNUSED,
13551                                unsigned long symndx ATTRIBUTE_UNUSED)
13552 {
13553   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13554   return bed->s->arch_size / 8;
13555 }
13556
13557 /* Routines to support the creation of dynamic relocs.  */
13558
13559 /* Returns the name of the dynamic reloc section associated with SEC.  */
13560
13561 static const char *
13562 get_dynamic_reloc_section_name (bfd *       abfd,
13563                                 asection *  sec,
13564                                 bfd_boolean is_rela)
13565 {
13566   char *name;
13567   const char *old_name = bfd_get_section_name (NULL, sec);
13568   const char *prefix = is_rela ? ".rela" : ".rel";
13569
13570   if (old_name == NULL)
13571     return NULL;
13572
13573   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13574   sprintf (name, "%s%s", prefix, old_name);
13575
13576   return name;
13577 }
13578
13579 /* Returns the dynamic reloc section associated with SEC.
13580    If necessary compute the name of the dynamic reloc section based
13581    on SEC's name (looked up in ABFD's string table) and the setting
13582    of IS_RELA.  */
13583
13584 asection *
13585 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13586                                     asection *  sec,
13587                                     bfd_boolean is_rela)
13588 {
13589   asection * reloc_sec = elf_section_data (sec)->sreloc;
13590
13591   if (reloc_sec == NULL)
13592     {
13593       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13594
13595       if (name != NULL)
13596         {
13597           reloc_sec = bfd_get_linker_section (abfd, name);
13598
13599           if (reloc_sec != NULL)
13600             elf_section_data (sec)->sreloc = reloc_sec;
13601         }
13602     }
13603
13604   return reloc_sec;
13605 }
13606
13607 /* Returns the dynamic reloc section associated with SEC.  If the
13608    section does not exist it is created and attached to the DYNOBJ
13609    bfd and stored in the SRELOC field of SEC's elf_section_data
13610    structure.
13611
13612    ALIGNMENT is the alignment for the newly created section and
13613    IS_RELA defines whether the name should be .rela.<SEC's name>
13614    or .rel.<SEC's name>.  The section name is looked up in the
13615    string table associated with ABFD.  */
13616
13617 asection *
13618 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13619                                      bfd *dynobj,
13620                                      unsigned int alignment,
13621                                      bfd *abfd,
13622                                      bfd_boolean is_rela)
13623 {
13624   asection * reloc_sec = elf_section_data (sec)->sreloc;
13625
13626   if (reloc_sec == NULL)
13627     {
13628       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13629
13630       if (name == NULL)
13631         return NULL;
13632
13633       reloc_sec = bfd_get_linker_section (dynobj, name);
13634
13635       if (reloc_sec == NULL)
13636         {
13637           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13638                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13639           if ((sec->flags & SEC_ALLOC) != 0)
13640             flags |= SEC_ALLOC | SEC_LOAD;
13641
13642           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13643           if (reloc_sec != NULL)
13644             {
13645               /* _bfd_elf_get_sec_type_attr chooses a section type by
13646                  name.  Override as it may be wrong, eg. for a user
13647                  section named "auto" we'll get ".relauto" which is
13648                  seen to be a .rela section.  */
13649               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13650               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13651                 reloc_sec = NULL;
13652             }
13653         }
13654
13655       elf_section_data (sec)->sreloc = reloc_sec;
13656     }
13657
13658   return reloc_sec;
13659 }
13660
13661 /* Copy the ELF symbol type and other attributes for a linker script
13662    assignment from HSRC to HDEST.  Generally this should be treated as
13663    if we found a strong non-dynamic definition for HDEST (except that
13664    ld ignores multiple definition errors).  */
13665 void
13666 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13667                                      struct bfd_link_hash_entry *hdest,
13668                                      struct bfd_link_hash_entry *hsrc)
13669 {
13670   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13671   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13672   Elf_Internal_Sym isym;
13673
13674   ehdest->type = ehsrc->type;
13675   ehdest->target_internal = ehsrc->target_internal;
13676
13677   isym.st_other = ehsrc->other;
13678   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13679 }
13680
13681 /* Append a RELA relocation REL to section S in BFD.  */
13682
13683 void
13684 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13685 {
13686   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13687   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13688   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13689   bed->s->swap_reloca_out (abfd, rel, loc);
13690 }
13691
13692 /* Append a REL relocation REL to section S in BFD.  */
13693
13694 void
13695 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13696 {
13697   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13698   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13699   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13700   bed->s->swap_reloc_out (abfd, rel, loc);
13701 }