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