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