Remove trailing spaces in gprof
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2015 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 (info->executable)
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
283   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
284                                           flags | SEC_READONLY);
285   if (s == NULL)
286     return FALSE;
287
288   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
289   if (s == NULL
290       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
291     return FALSE;
292
293   /* The special symbol _DYNAMIC is always set to the start of the
294      .dynamic section.  We could set _DYNAMIC in a linker script, but we
295      only want to define it if we are, in fact, creating a .dynamic
296      section.  We don't want to define it if there is no .dynamic
297      section, since on some ELF platforms the start up code examines it
298      to decide how to initialize the process.  */
299   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
300   elf_hash_table (info)->hdynamic = h;
301   if (h == NULL)
302     return FALSE;
303
304   if (info->emit_hash)
305     {
306       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
307                                               flags | SEC_READONLY);
308       if (s == NULL
309           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
310         return FALSE;
311       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
312     }
313
314   if (info->emit_gnu_hash)
315     {
316       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
317                                               flags | SEC_READONLY);
318       if (s == NULL
319           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
320         return FALSE;
321       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
322          4 32-bit words followed by variable count of 64-bit words, then
323          variable count of 32-bit words.  */
324       if (bed->s->arch_size == 64)
325         elf_section_data (s)->this_hdr.sh_entsize = 0;
326       else
327         elf_section_data (s)->this_hdr.sh_entsize = 4;
328     }
329
330   /* Let the backend create the rest of the sections.  This lets the
331      backend set the right flags.  The backend will normally create
332      the .got and .plt sections.  */
333   if (bed->elf_backend_create_dynamic_sections == NULL
334       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
335     return FALSE;
336
337   elf_hash_table (info)->dynamic_sections_created = TRUE;
338
339   return TRUE;
340 }
341
342 /* Create dynamic sections when linking against a dynamic object.  */
343
344 bfd_boolean
345 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
346 {
347   flagword flags, pltflags;
348   struct elf_link_hash_entry *h;
349   asection *s;
350   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
351   struct elf_link_hash_table *htab = elf_hash_table (info);
352
353   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
354      .rel[a].bss sections.  */
355   flags = bed->dynamic_sec_flags;
356
357   pltflags = flags;
358   if (bed->plt_not_loaded)
359     /* We do not clear SEC_ALLOC here because we still want the OS to
360        allocate space for the section; it's just that there's nothing
361        to read in from the object file.  */
362     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
363   else
364     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
365   if (bed->plt_readonly)
366     pltflags |= SEC_READONLY;
367
368   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
369   if (s == NULL
370       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
371     return FALSE;
372   htab->splt = s;
373
374   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
375      .plt section.  */
376   if (bed->want_plt_sym)
377     {
378       h = _bfd_elf_define_linkage_sym (abfd, info, s,
379                                        "_PROCEDURE_LINKAGE_TABLE_");
380       elf_hash_table (info)->hplt = h;
381       if (h == NULL)
382         return FALSE;
383     }
384
385   s = bfd_make_section_anyway_with_flags (abfd,
386                                           (bed->rela_plts_and_copies_p
387                                            ? ".rela.plt" : ".rel.plt"),
388                                           flags | SEC_READONLY);
389   if (s == NULL
390       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
391     return FALSE;
392   htab->srelplt = s;
393
394   if (! _bfd_elf_create_got_section (abfd, info))
395     return FALSE;
396
397   if (bed->want_dynbss)
398     {
399       /* The .dynbss section is a place to put symbols which are defined
400          by dynamic objects, are referenced by regular objects, and are
401          not functions.  We must allocate space for them in the process
402          image and use a R_*_COPY reloc to tell the dynamic linker to
403          initialize them at run time.  The linker script puts the .dynbss
404          section into the .bss section of the final image.  */
405       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
406                                               (SEC_ALLOC | SEC_LINKER_CREATED));
407       if (s == NULL)
408         return FALSE;
409
410       /* The .rel[a].bss section holds copy relocs.  This section is not
411          normally needed.  We need to create it here, though, so that the
412          linker will map it to an output section.  We can't just create it
413          only if we need it, because we will not know whether we need it
414          until we have seen all the input files, and the first time the
415          main linker code calls BFD after examining all the input files
416          (size_dynamic_sections) the input sections have already been
417          mapped to the output sections.  If the section turns out not to
418          be needed, we can discard it later.  We will never need this
419          section when generating a shared object, since they do not use
420          copy relocs.  */
421       if (! info->shared)
422         {
423           s = bfd_make_section_anyway_with_flags (abfd,
424                                                   (bed->rela_plts_and_copies_p
425                                                    ? ".rela.bss" : ".rel.bss"),
426                                                   flags | SEC_READONLY);
427           if (s == NULL
428               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
429             return FALSE;
430         }
431     }
432
433   return TRUE;
434 }
435 \f
436 /* Record a new dynamic symbol.  We record the dynamic symbols as we
437    read the input files, since we need to have a list of all of them
438    before we can determine the final sizes of the output sections.
439    Note that we may actually call this function even though we are not
440    going to output any dynamic symbols; in some cases we know that a
441    symbol should be in the dynamic symbol table, but only if there is
442    one.  */
443
444 bfd_boolean
445 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
446                                     struct elf_link_hash_entry *h)
447 {
448   if (h->dynindx == -1)
449     {
450       struct elf_strtab_hash *dynstr;
451       char *p;
452       const char *name;
453       bfd_size_type indx;
454
455       /* XXX: The ABI draft says the linker must turn hidden and
456          internal symbols into STB_LOCAL symbols when producing the
457          DSO. However, if ld.so honors st_other in the dynamic table,
458          this would not be necessary.  */
459       switch (ELF_ST_VISIBILITY (h->other))
460         {
461         case STV_INTERNAL:
462         case STV_HIDDEN:
463           if (h->root.type != bfd_link_hash_undefined
464               && h->root.type != bfd_link_hash_undefweak)
465             {
466               h->forced_local = 1;
467               if (!elf_hash_table (info)->is_relocatable_executable)
468                 return TRUE;
469             }
470
471         default:
472           break;
473         }
474
475       h->dynindx = elf_hash_table (info)->dynsymcount;
476       ++elf_hash_table (info)->dynsymcount;
477
478       dynstr = elf_hash_table (info)->dynstr;
479       if (dynstr == NULL)
480         {
481           /* Create a strtab to hold the dynamic symbol names.  */
482           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
483           if (dynstr == NULL)
484             return FALSE;
485         }
486
487       /* We don't put any version information in the dynamic string
488          table.  */
489       name = h->root.root.string;
490       p = strchr (name, ELF_VER_CHR);
491       if (p != NULL)
492         /* We know that the p points into writable memory.  In fact,
493            there are only a few symbols that have read-only names, being
494            those like _GLOBAL_OFFSET_TABLE_ that are created specially
495            by the backends.  Most symbols will have names pointing into
496            an ELF string table read from a file, or to objalloc memory.  */
497         *p = 0;
498
499       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
500
501       if (p != NULL)
502         *p = ELF_VER_CHR;
503
504       if (indx == (bfd_size_type) -1)
505         return FALSE;
506       h->dynstr_index = indx;
507     }
508
509   return TRUE;
510 }
511 \f
512 /* Mark a symbol dynamic.  */
513
514 static void
515 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
516                                   struct elf_link_hash_entry *h,
517                                   Elf_Internal_Sym *sym)
518 {
519   struct bfd_elf_dynamic_list *d = info->dynamic_list;
520
521   /* It may be called more than once on the same H.  */
522   if(h->dynamic || info->relocatable)
523     return;
524
525   if ((info->dynamic_data
526        && (h->type == STT_OBJECT
527            || (sym != NULL
528                && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
529       || (d != NULL
530           && h->root.type == bfd_link_hash_new
531           && (*d->match) (&d->head, NULL, h->root.root.string)))
532     h->dynamic = 1;
533 }
534
535 /* Record an assignment to a symbol made by a linker script.  We need
536    this in case some dynamic object refers to this symbol.  */
537
538 bfd_boolean
539 bfd_elf_record_link_assignment (bfd *output_bfd,
540                                 struct bfd_link_info *info,
541                                 const char *name,
542                                 bfd_boolean provide,
543                                 bfd_boolean hidden)
544 {
545   struct elf_link_hash_entry *h, *hv;
546   struct elf_link_hash_table *htab;
547   const struct elf_backend_data *bed;
548
549   if (!is_elf_hash_table (info->hash))
550     return TRUE;
551
552   htab = elf_hash_table (info);
553   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
554   if (h == NULL)
555     return provide;
556
557   switch (h->root.type)
558     {
559     case bfd_link_hash_defined:
560     case bfd_link_hash_defweak:
561     case bfd_link_hash_common:
562       break;
563     case bfd_link_hash_undefweak:
564     case bfd_link_hash_undefined:
565       /* Since we're defining the symbol, don't let it seem to have not
566          been defined.  record_dynamic_symbol and size_dynamic_sections
567          may depend on this.  */
568       h->root.type = bfd_link_hash_new;
569       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
570         bfd_link_repair_undef_list (&htab->root);
571       break;
572     case bfd_link_hash_new:
573       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
574       h->non_elf = 0;
575       break;
576     case bfd_link_hash_indirect:
577       /* We had a versioned symbol in a dynamic library.  We make the
578          the versioned symbol point to this one.  */
579       bed = get_elf_backend_data (output_bfd);
580       hv = h;
581       while (hv->root.type == bfd_link_hash_indirect
582              || hv->root.type == bfd_link_hash_warning)
583         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
584       /* We don't need to update h->root.u since linker will set them
585          later.  */
586       h->root.type = bfd_link_hash_undefined;
587       hv->root.type = bfd_link_hash_indirect;
588       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
589       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
590       break;
591     case bfd_link_hash_warning:
592       abort ();
593       break;
594     }
595
596   /* If this symbol is being provided by the linker script, and it is
597      currently defined by a dynamic object, but not by a regular
598      object, then mark it as undefined so that the generic linker will
599      force the correct value.  */
600   if (provide
601       && h->def_dynamic
602       && !h->def_regular)
603     h->root.type = bfd_link_hash_undefined;
604
605   /* If this symbol is not being provided by the linker script, and it is
606      currently defined by a dynamic object, but not by a regular object,
607      then clear out any version information because the symbol will not be
608      associated with the dynamic object any more.  */
609   if (!provide
610       && h->def_dynamic
611       && !h->def_regular)
612     h->verinfo.verdef = NULL;
613
614   h->def_regular = 1;
615
616   if (hidden)
617     {
618       bed = get_elf_backend_data (output_bfd);
619       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
620         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
621       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
622     }
623
624   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
625      and executables.  */
626   if (!info->relocatable
627       && h->dynindx != -1
628       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
629           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
630     h->forced_local = 1;
631
632   if ((h->def_dynamic
633        || h->ref_dynamic
634        || info->shared
635        || (info->executable && elf_hash_table (info)->is_relocatable_executable))
636       && h->dynindx == -1)
637     {
638       if (! bfd_elf_link_record_dynamic_symbol (info, h))
639         return FALSE;
640
641       /* If this is a weak defined symbol, and we know a corresponding
642          real symbol from the same dynamic object, make sure the real
643          symbol is also made into a dynamic symbol.  */
644       if (h->u.weakdef != NULL
645           && h->u.weakdef->dynindx == -1)
646         {
647           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
648             return FALSE;
649         }
650     }
651
652   return TRUE;
653 }
654
655 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
656    success, and 2 on a failure caused by attempting to record a symbol
657    in a discarded section, eg. a discarded link-once section symbol.  */
658
659 int
660 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
661                                           bfd *input_bfd,
662                                           long input_indx)
663 {
664   bfd_size_type amt;
665   struct elf_link_local_dynamic_entry *entry;
666   struct elf_link_hash_table *eht;
667   struct elf_strtab_hash *dynstr;
668   unsigned long dynstr_index;
669   char *name;
670   Elf_External_Sym_Shndx eshndx;
671   char esym[sizeof (Elf64_External_Sym)];
672
673   if (! is_elf_hash_table (info->hash))
674     return 0;
675
676   /* See if the entry exists already.  */
677   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
678     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
679       return 1;
680
681   amt = sizeof (*entry);
682   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
683   if (entry == NULL)
684     return 0;
685
686   /* Go find the symbol, so that we can find it's name.  */
687   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
688                              1, input_indx, &entry->isym, esym, &eshndx))
689     {
690       bfd_release (input_bfd, entry);
691       return 0;
692     }
693
694   if (entry->isym.st_shndx != SHN_UNDEF
695       && entry->isym.st_shndx < SHN_LORESERVE)
696     {
697       asection *s;
698
699       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
700       if (s == NULL || bfd_is_abs_section (s->output_section))
701         {
702           /* We can still bfd_release here as nothing has done another
703              bfd_alloc.  We can't do this later in this function.  */
704           bfd_release (input_bfd, entry);
705           return 2;
706         }
707     }
708
709   name = (bfd_elf_string_from_elf_section
710           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
711            entry->isym.st_name));
712
713   dynstr = elf_hash_table (info)->dynstr;
714   if (dynstr == NULL)
715     {
716       /* Create a strtab to hold the dynamic symbol names.  */
717       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
718       if (dynstr == NULL)
719         return 0;
720     }
721
722   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
723   if (dynstr_index == (unsigned long) -1)
724     return 0;
725   entry->isym.st_name = dynstr_index;
726
727   eht = elf_hash_table (info);
728
729   entry->next = eht->dynlocal;
730   eht->dynlocal = entry;
731   entry->input_bfd = input_bfd;
732   entry->input_indx = input_indx;
733   eht->dynsymcount++;
734
735   /* Whatever binding the symbol had before, it's now local.  */
736   entry->isym.st_info
737     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
738
739   /* The dynindx will be set at the end of size_dynamic_sections.  */
740
741   return 1;
742 }
743
744 /* Return the dynindex of a local dynamic symbol.  */
745
746 long
747 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
748                                     bfd *input_bfd,
749                                     long input_indx)
750 {
751   struct elf_link_local_dynamic_entry *e;
752
753   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
754     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
755       return e->dynindx;
756   return -1;
757 }
758
759 /* This function is used to renumber the dynamic symbols, if some of
760    them are removed because they are marked as local.  This is called
761    via elf_link_hash_traverse.  */
762
763 static bfd_boolean
764 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
765                                       void *data)
766 {
767   size_t *count = (size_t *) data;
768
769   if (h->forced_local)
770     return TRUE;
771
772   if (h->dynindx != -1)
773     h->dynindx = ++(*count);
774
775   return TRUE;
776 }
777
778
779 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
780    STB_LOCAL binding.  */
781
782 static bfd_boolean
783 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
784                                             void *data)
785 {
786   size_t *count = (size_t *) data;
787
788   if (!h->forced_local)
789     return TRUE;
790
791   if (h->dynindx != -1)
792     h->dynindx = ++(*count);
793
794   return TRUE;
795 }
796
797 /* Return true if the dynamic symbol for a given section should be
798    omitted when creating a shared library.  */
799 bfd_boolean
800 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
801                                    struct bfd_link_info *info,
802                                    asection *p)
803 {
804   struct elf_link_hash_table *htab;
805   asection *ip;
806
807   switch (elf_section_data (p)->this_hdr.sh_type)
808     {
809     case SHT_PROGBITS:
810     case SHT_NOBITS:
811       /* If sh_type is yet undecided, assume it could be
812          SHT_PROGBITS/SHT_NOBITS.  */
813     case SHT_NULL:
814       htab = elf_hash_table (info);
815       if (p == htab->tls_sec)
816         return FALSE;
817
818       if (htab->text_index_section != NULL)
819         return p != htab->text_index_section && p != htab->data_index_section;
820
821       return (htab->dynobj != NULL
822               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
823               && ip->output_section == p);
824
825       /* There shouldn't be section relative relocations
826          against any other section.  */
827     default:
828       return TRUE;
829     }
830 }
831
832 /* Assign dynsym indices.  In a shared library we generate a section
833    symbol for each output section, which come first.  Next come symbols
834    which have been forced to local binding.  Then all of the back-end
835    allocated local dynamic syms, followed by the rest of the global
836    symbols.  */
837
838 static unsigned long
839 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
840                                 struct bfd_link_info *info,
841                                 unsigned long *section_sym_count)
842 {
843   unsigned long dynsymcount = 0;
844
845   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
846     {
847       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
848       asection *p;
849       for (p = output_bfd->sections; p ; p = p->next)
850         if ((p->flags & SEC_EXCLUDE) == 0
851             && (p->flags & SEC_ALLOC) != 0
852             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
853           elf_section_data (p)->dynindx = ++dynsymcount;
854         else
855           elf_section_data (p)->dynindx = 0;
856     }
857   *section_sym_count = dynsymcount;
858
859   elf_link_hash_traverse (elf_hash_table (info),
860                           elf_link_renumber_local_hash_table_dynsyms,
861                           &dynsymcount);
862
863   if (elf_hash_table (info)->dynlocal)
864     {
865       struct elf_link_local_dynamic_entry *p;
866       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
867         p->dynindx = ++dynsymcount;
868     }
869
870   elf_link_hash_traverse (elf_hash_table (info),
871                           elf_link_renumber_hash_table_dynsyms,
872                           &dynsymcount);
873
874   /* There is an unused NULL entry at the head of the table which
875      we must account for in our count.  Unless there weren't any
876      symbols, which means we'll have no table at all.  */
877   if (dynsymcount != 0)
878     ++dynsymcount;
879
880   elf_hash_table (info)->dynsymcount = dynsymcount;
881   return dynsymcount;
882 }
883
884 /* Merge st_other field.  */
885
886 static void
887 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
888                     const Elf_Internal_Sym *isym, asection *sec,
889                     bfd_boolean definition, bfd_boolean dynamic)
890 {
891   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
892
893   /* If st_other has a processor-specific meaning, specific
894      code might be needed here.  */
895   if (bed->elf_backend_merge_symbol_attribute)
896     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
897                                                 dynamic);
898
899   if (!dynamic)
900     {
901       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
902       unsigned hvis = ELF_ST_VISIBILITY (h->other);
903
904       /* Keep the most constraining visibility.  Leave the remainder
905          of the st_other field to elf_backend_merge_symbol_attribute.  */
906       if (symvis - 1 < hvis - 1)
907         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
908     }
909   else if (definition
910            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
911            && (sec->flags & SEC_READONLY) == 0)
912     h->protected_def = 1;
913 }
914
915 /* This function is called when we want to merge a new symbol with an
916    existing symbol.  It handles the various cases which arise when we
917    find a definition in a dynamic object, or when there is already a
918    definition in a dynamic object.  The new symbol is described by
919    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
920    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
921    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
922    of an old common symbol.  We set OVERRIDE if the old symbol is
923    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
924    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
925    to change.  By OK to change, we mean that we shouldn't warn if the
926    type or size does change.  */
927
928 static bfd_boolean
929 _bfd_elf_merge_symbol (bfd *abfd,
930                        struct bfd_link_info *info,
931                        const char *name,
932                        Elf_Internal_Sym *sym,
933                        asection **psec,
934                        bfd_vma *pvalue,
935                        struct elf_link_hash_entry **sym_hash,
936                        bfd **poldbfd,
937                        bfd_boolean *pold_weak,
938                        unsigned int *pold_alignment,
939                        bfd_boolean *skip,
940                        bfd_boolean *override,
941                        bfd_boolean *type_change_ok,
942                        bfd_boolean *size_change_ok,
943                        bfd_boolean *matched)
944 {
945   asection *sec, *oldsec;
946   struct elf_link_hash_entry *h;
947   struct elf_link_hash_entry *hi;
948   struct elf_link_hash_entry *flip;
949   int bind;
950   bfd *oldbfd;
951   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
952   bfd_boolean newweak, oldweak, newfunc, oldfunc;
953   const struct elf_backend_data *bed;
954   char *new_version;
955
956   *skip = FALSE;
957   *override = FALSE;
958
959   sec = *psec;
960   bind = ELF_ST_BIND (sym->st_info);
961
962   if (! bfd_is_und_section (sec))
963     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
964   else
965     h = ((struct elf_link_hash_entry *)
966          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
967   if (h == NULL)
968     return FALSE;
969   *sym_hash = h;
970
971   bed = get_elf_backend_data (abfd);
972
973   /* NEW_VERSION is the symbol version of the new symbol.  */
974   if (h->versioned != unversioned)
975     {
976       /* Symbol version is unknown or versioned.  */
977       new_version = strrchr (name, ELF_VER_CHR);
978       if (new_version)
979         {
980           if (h->versioned == unknown)
981             {
982               if (new_version > name && new_version[-1] != ELF_VER_CHR)
983                 h->versioned = versioned_hidden;
984               else
985                 h->versioned = versioned;
986             }
987           new_version += 1;
988           if (new_version[0] == '\0')
989             new_version = NULL;
990         }
991       else
992         h->versioned = unversioned;
993     }
994   else
995     new_version = NULL;
996
997   /* For merging, we only care about real symbols.  But we need to make
998      sure that indirect symbol dynamic flags are updated.  */
999   hi = h;
1000   while (h->root.type == bfd_link_hash_indirect
1001          || h->root.type == bfd_link_hash_warning)
1002     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1003
1004   if (!*matched)
1005     {
1006       if (hi == h || h->root.type == bfd_link_hash_new)
1007         *matched = TRUE;
1008       else
1009         {
1010           /* OLD_HIDDEN is true if the existing symbol is only visibile
1011              to the symbol with the same symbol version.  NEW_HIDDEN is
1012              true if the new symbol is only visibile to the symbol with
1013              the same symbol version.  */
1014           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1015           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1016           if (!old_hidden && !new_hidden)
1017             /* The new symbol matches the existing symbol if both
1018                aren't hidden.  */
1019             *matched = TRUE;
1020           else
1021             {
1022               /* OLD_VERSION is the symbol version of the existing
1023                  symbol. */
1024               char *old_version;
1025
1026               if (h->versioned >= versioned)
1027                 old_version = strrchr (h->root.root.string,
1028                                        ELF_VER_CHR) + 1;
1029               else
1030                  old_version = NULL;
1031
1032               /* The new symbol matches the existing symbol if they
1033                  have the same symbol version.  */
1034               *matched = (old_version == new_version
1035                           || (old_version != NULL
1036                               && new_version != NULL
1037                               && strcmp (old_version, new_version) == 0));
1038             }
1039         }
1040     }
1041
1042   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1043      existing symbol.  */
1044
1045   oldbfd = NULL;
1046   oldsec = NULL;
1047   switch (h->root.type)
1048     {
1049     default:
1050       break;
1051
1052     case bfd_link_hash_undefined:
1053     case bfd_link_hash_undefweak:
1054       oldbfd = h->root.u.undef.abfd;
1055       break;
1056
1057     case bfd_link_hash_defined:
1058     case bfd_link_hash_defweak:
1059       oldbfd = h->root.u.def.section->owner;
1060       oldsec = h->root.u.def.section;
1061       break;
1062
1063     case bfd_link_hash_common:
1064       oldbfd = h->root.u.c.p->section->owner;
1065       oldsec = h->root.u.c.p->section;
1066       if (pold_alignment)
1067         *pold_alignment = h->root.u.c.p->alignment_power;
1068       break;
1069     }
1070   if (poldbfd && *poldbfd == NULL)
1071     *poldbfd = oldbfd;
1072
1073   /* Differentiate strong and weak symbols.  */
1074   newweak = bind == STB_WEAK;
1075   oldweak = (h->root.type == bfd_link_hash_defweak
1076              || h->root.type == bfd_link_hash_undefweak);
1077   if (pold_weak)
1078     *pold_weak = oldweak;
1079
1080   /* This code is for coping with dynamic objects, and is only useful
1081      if we are doing an ELF link.  */
1082   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1083     return TRUE;
1084
1085   /* We have to check it for every instance since the first few may be
1086      references and not all compilers emit symbol type for undefined
1087      symbols.  */
1088   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1089
1090   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1091      respectively, is from a dynamic object.  */
1092
1093   newdyn = (abfd->flags & DYNAMIC) != 0;
1094
1095   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1096      syms and defined syms in dynamic libraries respectively.
1097      ref_dynamic on the other hand can be set for a symbol defined in
1098      a dynamic library, and def_dynamic may not be set;  When the
1099      definition in a dynamic lib is overridden by a definition in the
1100      executable use of the symbol in the dynamic lib becomes a
1101      reference to the executable symbol.  */
1102   if (newdyn)
1103     {
1104       if (bfd_is_und_section (sec))
1105         {
1106           if (bind != STB_WEAK)
1107             {
1108               h->ref_dynamic_nonweak = 1;
1109               hi->ref_dynamic_nonweak = 1;
1110             }
1111         }
1112       else
1113         {
1114           /* Update the existing symbol only if they match. */
1115           if (*matched)
1116             h->dynamic_def = 1;
1117           hi->dynamic_def = 1;
1118         }
1119     }
1120
1121   /* If we just created the symbol, mark it as being an ELF symbol.
1122      Other than that, there is nothing to do--there is no merge issue
1123      with a newly defined symbol--so we just return.  */
1124
1125   if (h->root.type == bfd_link_hash_new)
1126     {
1127       h->non_elf = 0;
1128       return TRUE;
1129     }
1130
1131   /* In cases involving weak versioned symbols, we may wind up trying
1132      to merge a symbol with itself.  Catch that here, to avoid the
1133      confusion that results if we try to override a symbol with
1134      itself.  The additional tests catch cases like
1135      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1136      dynamic object, which we do want to handle here.  */
1137   if (abfd == oldbfd
1138       && (newweak || oldweak)
1139       && ((abfd->flags & DYNAMIC) == 0
1140           || !h->def_regular))
1141     return TRUE;
1142
1143   olddyn = FALSE;
1144   if (oldbfd != NULL)
1145     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1146   else if (oldsec != NULL)
1147     {
1148       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1149          indices used by MIPS ELF.  */
1150       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1151     }
1152
1153   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1154      respectively, appear to be a definition rather than reference.  */
1155
1156   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1157
1158   olddef = (h->root.type != bfd_link_hash_undefined
1159             && h->root.type != bfd_link_hash_undefweak
1160             && h->root.type != bfd_link_hash_common);
1161
1162   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1163      respectively, appear to be a function.  */
1164
1165   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1166              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1167
1168   oldfunc = (h->type != STT_NOTYPE
1169              && bed->is_function_type (h->type));
1170
1171   /* When we try to create a default indirect symbol from the dynamic
1172      definition with the default version, we skip it if its type and
1173      the type of existing regular definition mismatch.  */
1174   if (pold_alignment == NULL
1175       && newdyn
1176       && newdef
1177       && !olddyn
1178       && (((olddef || h->root.type == bfd_link_hash_common)
1179            && ELF_ST_TYPE (sym->st_info) != h->type
1180            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1181            && h->type != STT_NOTYPE
1182            && !(newfunc && oldfunc))
1183           || (olddef
1184               && ((h->type == STT_GNU_IFUNC)
1185                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1186     {
1187       *skip = TRUE;
1188       return TRUE;
1189     }
1190
1191   /* Check TLS symbols.  We don't check undefined symbols introduced
1192      by "ld -u" which have no type (and oldbfd NULL), and we don't
1193      check symbols from plugins because they also have no type.  */
1194   if (oldbfd != NULL
1195       && (oldbfd->flags & BFD_PLUGIN) == 0
1196       && (abfd->flags & BFD_PLUGIN) == 0
1197       && ELF_ST_TYPE (sym->st_info) != h->type
1198       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1199     {
1200       bfd *ntbfd, *tbfd;
1201       bfd_boolean ntdef, tdef;
1202       asection *ntsec, *tsec;
1203
1204       if (h->type == STT_TLS)
1205         {
1206           ntbfd = abfd;
1207           ntsec = sec;
1208           ntdef = newdef;
1209           tbfd = oldbfd;
1210           tsec = oldsec;
1211           tdef = olddef;
1212         }
1213       else
1214         {
1215           ntbfd = oldbfd;
1216           ntsec = oldsec;
1217           ntdef = olddef;
1218           tbfd = abfd;
1219           tsec = sec;
1220           tdef = newdef;
1221         }
1222
1223       if (tdef && ntdef)
1224         (*_bfd_error_handler)
1225           (_("%s: TLS definition in %B section %A "
1226              "mismatches non-TLS definition in %B section %A"),
1227            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1228       else if (!tdef && !ntdef)
1229         (*_bfd_error_handler)
1230           (_("%s: TLS reference in %B "
1231              "mismatches non-TLS reference in %B"),
1232            tbfd, ntbfd, h->root.root.string);
1233       else if (tdef)
1234         (*_bfd_error_handler)
1235           (_("%s: TLS definition in %B section %A "
1236              "mismatches non-TLS reference in %B"),
1237            tbfd, tsec, ntbfd, h->root.root.string);
1238       else
1239         (*_bfd_error_handler)
1240           (_("%s: TLS reference in %B "
1241              "mismatches non-TLS definition in %B section %A"),
1242            tbfd, ntbfd, ntsec, h->root.root.string);
1243
1244       bfd_set_error (bfd_error_bad_value);
1245       return FALSE;
1246     }
1247
1248   /* If the old symbol has non-default visibility, we ignore the new
1249      definition from a dynamic object.  */
1250   if (newdyn
1251       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1252       && !bfd_is_und_section (sec))
1253     {
1254       *skip = TRUE;
1255       /* Make sure this symbol is dynamic.  */
1256       h->ref_dynamic = 1;
1257       hi->ref_dynamic = 1;
1258       /* A protected symbol has external availability. Make sure it is
1259          recorded as dynamic.
1260
1261          FIXME: Should we check type and size for protected symbol?  */
1262       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1263         return bfd_elf_link_record_dynamic_symbol (info, h);
1264       else
1265         return TRUE;
1266     }
1267   else if (!newdyn
1268            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1269            && h->def_dynamic)
1270     {
1271       /* If the new symbol with non-default visibility comes from a
1272          relocatable file and the old definition comes from a dynamic
1273          object, we remove the old definition.  */
1274       if (hi->root.type == bfd_link_hash_indirect)
1275         {
1276           /* Handle the case where the old dynamic definition is
1277              default versioned.  We need to copy the symbol info from
1278              the symbol with default version to the normal one if it
1279              was referenced before.  */
1280           if (h->ref_regular)
1281             {
1282               hi->root.type = h->root.type;
1283               h->root.type = bfd_link_hash_indirect;
1284               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1285
1286               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1287               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1288                 {
1289                   /* If the new symbol is hidden or internal, completely undo
1290                      any dynamic link state.  */
1291                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1292                   h->forced_local = 0;
1293                   h->ref_dynamic = 0;
1294                 }
1295               else
1296                 h->ref_dynamic = 1;
1297
1298               h->def_dynamic = 0;
1299               /* FIXME: Should we check type and size for protected symbol?  */
1300               h->size = 0;
1301               h->type = 0;
1302
1303               h = hi;
1304             }
1305           else
1306             h = hi;
1307         }
1308
1309       /* If the old symbol was undefined before, then it will still be
1310          on the undefs list.  If the new symbol is undefined or
1311          common, we can't make it bfd_link_hash_new here, because new
1312          undefined or common symbols will be added to the undefs list
1313          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1314          added twice to the undefs list.  Also, if the new symbol is
1315          undefweak then we don't want to lose the strong undef.  */
1316       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1317         {
1318           h->root.type = bfd_link_hash_undefined;
1319           h->root.u.undef.abfd = abfd;
1320         }
1321       else
1322         {
1323           h->root.type = bfd_link_hash_new;
1324           h->root.u.undef.abfd = NULL;
1325         }
1326
1327       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1328         {
1329           /* If the new symbol is hidden or internal, completely undo
1330              any dynamic link state.  */
1331           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1332           h->forced_local = 0;
1333           h->ref_dynamic = 0;
1334         }
1335       else
1336         h->ref_dynamic = 1;
1337       h->def_dynamic = 0;
1338       /* FIXME: Should we check type and size for protected symbol?  */
1339       h->size = 0;
1340       h->type = 0;
1341       return TRUE;
1342     }
1343
1344   /* If a new weak symbol definition comes from a regular file and the
1345      old symbol comes from a dynamic library, we treat the new one as
1346      strong.  Similarly, an old weak symbol definition from a regular
1347      file is treated as strong when the new symbol comes from a dynamic
1348      library.  Further, an old weak symbol from a dynamic library is
1349      treated as strong if the new symbol is from a dynamic library.
1350      This reflects the way glibc's ld.so works.
1351
1352      Do this before setting *type_change_ok or *size_change_ok so that
1353      we warn properly when dynamic library symbols are overridden.  */
1354
1355   if (newdef && !newdyn && olddyn)
1356     newweak = FALSE;
1357   if (olddef && newdyn)
1358     oldweak = FALSE;
1359
1360   /* Allow changes between different types of function symbol.  */
1361   if (newfunc && oldfunc)
1362     *type_change_ok = TRUE;
1363
1364   /* It's OK to change the type if either the existing symbol or the
1365      new symbol is weak.  A type change is also OK if the old symbol
1366      is undefined and the new symbol is defined.  */
1367
1368   if (oldweak
1369       || newweak
1370       || (newdef
1371           && h->root.type == bfd_link_hash_undefined))
1372     *type_change_ok = TRUE;
1373
1374   /* It's OK to change the size if either the existing symbol or the
1375      new symbol is weak, or if the old symbol is undefined.  */
1376
1377   if (*type_change_ok
1378       || h->root.type == bfd_link_hash_undefined)
1379     *size_change_ok = TRUE;
1380
1381   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1382      symbol, respectively, appears to be a common symbol in a dynamic
1383      object.  If a symbol appears in an uninitialized section, and is
1384      not weak, and is not a function, then it may be a common symbol
1385      which was resolved when the dynamic object was created.  We want
1386      to treat such symbols specially, because they raise special
1387      considerations when setting the symbol size: if the symbol
1388      appears as a common symbol in a regular object, and the size in
1389      the regular object is larger, we must make sure that we use the
1390      larger size.  This problematic case can always be avoided in C,
1391      but it must be handled correctly when using Fortran shared
1392      libraries.
1393
1394      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1395      likewise for OLDDYNCOMMON and OLDDEF.
1396
1397      Note that this test is just a heuristic, and that it is quite
1398      possible to have an uninitialized symbol in a shared object which
1399      is really a definition, rather than a common symbol.  This could
1400      lead to some minor confusion when the symbol really is a common
1401      symbol in some regular object.  However, I think it will be
1402      harmless.  */
1403
1404   if (newdyn
1405       && newdef
1406       && !newweak
1407       && (sec->flags & SEC_ALLOC) != 0
1408       && (sec->flags & SEC_LOAD) == 0
1409       && sym->st_size > 0
1410       && !newfunc)
1411     newdyncommon = TRUE;
1412   else
1413     newdyncommon = FALSE;
1414
1415   if (olddyn
1416       && olddef
1417       && h->root.type == bfd_link_hash_defined
1418       && h->def_dynamic
1419       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1420       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1421       && h->size > 0
1422       && !oldfunc)
1423     olddyncommon = TRUE;
1424   else
1425     olddyncommon = FALSE;
1426
1427   /* We now know everything about the old and new symbols.  We ask the
1428      backend to check if we can merge them.  */
1429   if (bed->merge_symbol != NULL)
1430     {
1431       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1432         return FALSE;
1433       sec = *psec;
1434     }
1435
1436   /* If both the old and the new symbols look like common symbols in a
1437      dynamic object, set the size of the symbol to the larger of the
1438      two.  */
1439
1440   if (olddyncommon
1441       && newdyncommon
1442       && sym->st_size != h->size)
1443     {
1444       /* Since we think we have two common symbols, issue a multiple
1445          common warning if desired.  Note that we only warn if the
1446          size is different.  If the size is the same, we simply let
1447          the old symbol override the new one as normally happens with
1448          symbols defined in dynamic objects.  */
1449
1450       if (! ((*info->callbacks->multiple_common)
1451              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1452         return FALSE;
1453
1454       if (sym->st_size > h->size)
1455         h->size = sym->st_size;
1456
1457       *size_change_ok = TRUE;
1458     }
1459
1460   /* If we are looking at a dynamic object, and we have found a
1461      definition, we need to see if the symbol was already defined by
1462      some other object.  If so, we want to use the existing
1463      definition, and we do not want to report a multiple symbol
1464      definition error; we do this by clobbering *PSEC to be
1465      bfd_und_section_ptr.
1466
1467      We treat a common symbol as a definition if the symbol in the
1468      shared library is a function, since common symbols always
1469      represent variables; this can cause confusion in principle, but
1470      any such confusion would seem to indicate an erroneous program or
1471      shared library.  We also permit a common symbol in a regular
1472      object to override a weak symbol in a shared object.  */
1473
1474   if (newdyn
1475       && newdef
1476       && (olddef
1477           || (h->root.type == bfd_link_hash_common
1478               && (newweak || newfunc))))
1479     {
1480       *override = TRUE;
1481       newdef = FALSE;
1482       newdyncommon = FALSE;
1483
1484       *psec = sec = bfd_und_section_ptr;
1485       *size_change_ok = TRUE;
1486
1487       /* If we get here when the old symbol is a common symbol, then
1488          we are explicitly letting it override a weak symbol or
1489          function in a dynamic object, and we don't want to warn about
1490          a type change.  If the old symbol is a defined symbol, a type
1491          change warning may still be appropriate.  */
1492
1493       if (h->root.type == bfd_link_hash_common)
1494         *type_change_ok = TRUE;
1495     }
1496
1497   /* Handle the special case of an old common symbol merging with a
1498      new symbol which looks like a common symbol in a shared object.
1499      We change *PSEC and *PVALUE to make the new symbol look like a
1500      common symbol, and let _bfd_generic_link_add_one_symbol do the
1501      right thing.  */
1502
1503   if (newdyncommon
1504       && h->root.type == bfd_link_hash_common)
1505     {
1506       *override = TRUE;
1507       newdef = FALSE;
1508       newdyncommon = FALSE;
1509       *pvalue = sym->st_size;
1510       *psec = sec = bed->common_section (oldsec);
1511       *size_change_ok = TRUE;
1512     }
1513
1514   /* Skip weak definitions of symbols that are already defined.  */
1515   if (newdef && olddef && newweak)
1516     {
1517       /* Don't skip new non-IR weak syms.  */
1518       if (!(oldbfd != NULL
1519             && (oldbfd->flags & BFD_PLUGIN) != 0
1520             && (abfd->flags & BFD_PLUGIN) == 0))
1521         {
1522           newdef = FALSE;
1523           *skip = TRUE;
1524         }
1525
1526       /* Merge st_other.  If the symbol already has a dynamic index,
1527          but visibility says it should not be visible, turn it into a
1528          local symbol.  */
1529       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1530       if (h->dynindx != -1)
1531         switch (ELF_ST_VISIBILITY (h->other))
1532           {
1533           case STV_INTERNAL:
1534           case STV_HIDDEN:
1535             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1536             break;
1537           }
1538     }
1539
1540   /* If the old symbol is from a dynamic object, and the new symbol is
1541      a definition which is not from a dynamic object, then the new
1542      symbol overrides the old symbol.  Symbols from regular files
1543      always take precedence over symbols from dynamic objects, even if
1544      they are defined after the dynamic object in the link.
1545
1546      As above, we again permit a common symbol in a regular object to
1547      override a definition in a shared object if the shared object
1548      symbol is a function or is weak.  */
1549
1550   flip = NULL;
1551   if (!newdyn
1552       && (newdef
1553           || (bfd_is_com_section (sec)
1554               && (oldweak || oldfunc)))
1555       && olddyn
1556       && olddef
1557       && h->def_dynamic)
1558     {
1559       /* Change the hash table entry to undefined, and let
1560          _bfd_generic_link_add_one_symbol do the right thing with the
1561          new definition.  */
1562
1563       h->root.type = bfd_link_hash_undefined;
1564       h->root.u.undef.abfd = h->root.u.def.section->owner;
1565       *size_change_ok = TRUE;
1566
1567       olddef = FALSE;
1568       olddyncommon = FALSE;
1569
1570       /* We again permit a type change when a common symbol may be
1571          overriding a function.  */
1572
1573       if (bfd_is_com_section (sec))
1574         {
1575           if (oldfunc)
1576             {
1577               /* If a common symbol overrides a function, make sure
1578                  that it isn't defined dynamically nor has type
1579                  function.  */
1580               h->def_dynamic = 0;
1581               h->type = STT_NOTYPE;
1582             }
1583           *type_change_ok = TRUE;
1584         }
1585
1586       if (hi->root.type == bfd_link_hash_indirect)
1587         flip = hi;
1588       else
1589         /* This union may have been set to be non-NULL when this symbol
1590            was seen in a dynamic object.  We must force the union to be
1591            NULL, so that it is correct for a regular symbol.  */
1592         h->verinfo.vertree = NULL;
1593     }
1594
1595   /* Handle the special case of a new common symbol merging with an
1596      old symbol that looks like it might be a common symbol defined in
1597      a shared object.  Note that we have already handled the case in
1598      which a new common symbol should simply override the definition
1599      in the shared library.  */
1600
1601   if (! newdyn
1602       && bfd_is_com_section (sec)
1603       && olddyncommon)
1604     {
1605       /* It would be best if we could set the hash table entry to a
1606          common symbol, but we don't know what to use for the section
1607          or the alignment.  */
1608       if (! ((*info->callbacks->multiple_common)
1609              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1610         return FALSE;
1611
1612       /* If the presumed common symbol in the dynamic object is
1613          larger, pretend that the new symbol has its size.  */
1614
1615       if (h->size > *pvalue)
1616         *pvalue = h->size;
1617
1618       /* We need to remember the alignment required by the symbol
1619          in the dynamic object.  */
1620       BFD_ASSERT (pold_alignment);
1621       *pold_alignment = h->root.u.def.section->alignment_power;
1622
1623       olddef = FALSE;
1624       olddyncommon = FALSE;
1625
1626       h->root.type = bfd_link_hash_undefined;
1627       h->root.u.undef.abfd = h->root.u.def.section->owner;
1628
1629       *size_change_ok = TRUE;
1630       *type_change_ok = TRUE;
1631
1632       if (hi->root.type == bfd_link_hash_indirect)
1633         flip = hi;
1634       else
1635         h->verinfo.vertree = NULL;
1636     }
1637
1638   if (flip != NULL)
1639     {
1640       /* Handle the case where we had a versioned symbol in a dynamic
1641          library and now find a definition in a normal object.  In this
1642          case, we make the versioned symbol point to the normal one.  */
1643       flip->root.type = h->root.type;
1644       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1645       h->root.type = bfd_link_hash_indirect;
1646       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1647       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1648       if (h->def_dynamic)
1649         {
1650           h->def_dynamic = 0;
1651           flip->ref_dynamic = 1;
1652         }
1653     }
1654
1655   return TRUE;
1656 }
1657
1658 /* This function is called to create an indirect symbol from the
1659    default for the symbol with the default version if needed. The
1660    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1661    set DYNSYM if the new indirect symbol is dynamic.  */
1662
1663 static bfd_boolean
1664 _bfd_elf_add_default_symbol (bfd *abfd,
1665                              struct bfd_link_info *info,
1666                              struct elf_link_hash_entry *h,
1667                              const char *name,
1668                              Elf_Internal_Sym *sym,
1669                              asection *sec,
1670                              bfd_vma value,
1671                              bfd **poldbfd,
1672                              bfd_boolean *dynsym)
1673 {
1674   bfd_boolean type_change_ok;
1675   bfd_boolean size_change_ok;
1676   bfd_boolean skip;
1677   char *shortname;
1678   struct elf_link_hash_entry *hi;
1679   struct bfd_link_hash_entry *bh;
1680   const struct elf_backend_data *bed;
1681   bfd_boolean collect;
1682   bfd_boolean dynamic;
1683   bfd_boolean override;
1684   char *p;
1685   size_t len, shortlen;
1686   asection *tmp_sec;
1687   bfd_boolean matched;
1688
1689   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1690     return TRUE;
1691
1692   /* If this symbol has a version, and it is the default version, we
1693      create an indirect symbol from the default name to the fully
1694      decorated name.  This will cause external references which do not
1695      specify a version to be bound to this version of the symbol.  */
1696   p = strchr (name, ELF_VER_CHR);
1697   if (h->versioned == unknown)
1698     {
1699       if (p == NULL)
1700         {
1701           h->versioned = unversioned;
1702           return TRUE;
1703         }
1704       else
1705         {
1706           if (p[1] != ELF_VER_CHR)
1707             {
1708               h->versioned = versioned_hidden;
1709               return TRUE;
1710             }
1711           else
1712             h->versioned = versioned;
1713         }
1714     }
1715
1716   bed = get_elf_backend_data (abfd);
1717   collect = bed->collect;
1718   dynamic = (abfd->flags & DYNAMIC) != 0;
1719
1720   shortlen = p - name;
1721   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1722   if (shortname == NULL)
1723     return FALSE;
1724   memcpy (shortname, name, shortlen);
1725   shortname[shortlen] = '\0';
1726
1727   /* We are going to create a new symbol.  Merge it with any existing
1728      symbol with this name.  For the purposes of the merge, act as
1729      though we were defining the symbol we just defined, although we
1730      actually going to define an indirect symbol.  */
1731   type_change_ok = FALSE;
1732   size_change_ok = FALSE;
1733   matched = TRUE;
1734   tmp_sec = sec;
1735   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1736                               &hi, poldbfd, NULL, NULL, &skip, &override,
1737                               &type_change_ok, &size_change_ok, &matched))
1738     return FALSE;
1739
1740   if (skip)
1741     goto nondefault;
1742
1743   if (! override)
1744     {
1745       /* Add the default symbol if not performing a relocatable link.  */
1746       if (! info->relocatable)
1747         {
1748           bh = &hi->root;
1749           if (! (_bfd_generic_link_add_one_symbol
1750                  (info, abfd, shortname, BSF_INDIRECT,
1751                   bfd_ind_section_ptr,
1752                   0, name, FALSE, collect, &bh)))
1753             return FALSE;
1754           hi = (struct elf_link_hash_entry *) bh;
1755         }
1756     }
1757   else
1758     {
1759       /* In this case the symbol named SHORTNAME is overriding the
1760          indirect symbol we want to add.  We were planning on making
1761          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1762          is the name without a version.  NAME is the fully versioned
1763          name, and it is the default version.
1764
1765          Overriding means that we already saw a definition for the
1766          symbol SHORTNAME in a regular object, and it is overriding
1767          the symbol defined in the dynamic object.
1768
1769          When this happens, we actually want to change NAME, the
1770          symbol we just added, to refer to SHORTNAME.  This will cause
1771          references to NAME in the shared object to become references
1772          to SHORTNAME in the regular object.  This is what we expect
1773          when we override a function in a shared object: that the
1774          references in the shared object will be mapped to the
1775          definition in the regular object.  */
1776
1777       while (hi->root.type == bfd_link_hash_indirect
1778              || hi->root.type == bfd_link_hash_warning)
1779         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1780
1781       h->root.type = bfd_link_hash_indirect;
1782       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1783       if (h->def_dynamic)
1784         {
1785           h->def_dynamic = 0;
1786           hi->ref_dynamic = 1;
1787           if (hi->ref_regular
1788               || hi->def_regular)
1789             {
1790               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1791                 return FALSE;
1792             }
1793         }
1794
1795       /* Now set HI to H, so that the following code will set the
1796          other fields correctly.  */
1797       hi = h;
1798     }
1799
1800   /* Check if HI is a warning symbol.  */
1801   if (hi->root.type == bfd_link_hash_warning)
1802     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1803
1804   /* If there is a duplicate definition somewhere, then HI may not
1805      point to an indirect symbol.  We will have reported an error to
1806      the user in that case.  */
1807
1808   if (hi->root.type == bfd_link_hash_indirect)
1809     {
1810       struct elf_link_hash_entry *ht;
1811
1812       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1813       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1814
1815       /* A reference to the SHORTNAME symbol from a dynamic library
1816          will be satisfied by the versioned symbol at runtime.  In
1817          effect, we have a reference to the versioned symbol.  */
1818       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1819       hi->dynamic_def |= ht->dynamic_def;
1820
1821       /* See if the new flags lead us to realize that the symbol must
1822          be dynamic.  */
1823       if (! *dynsym)
1824         {
1825           if (! dynamic)
1826             {
1827               if (! info->executable
1828                   || hi->def_dynamic
1829                   || hi->ref_dynamic)
1830                 *dynsym = TRUE;
1831             }
1832           else
1833             {
1834               if (hi->ref_regular)
1835                 *dynsym = TRUE;
1836             }
1837         }
1838     }
1839
1840   /* We also need to define an indirection from the nondefault version
1841      of the symbol.  */
1842
1843 nondefault:
1844   len = strlen (name);
1845   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1846   if (shortname == NULL)
1847     return FALSE;
1848   memcpy (shortname, name, shortlen);
1849   memcpy (shortname + shortlen, p + 1, len - shortlen);
1850
1851   /* Once again, merge with any existing symbol.  */
1852   type_change_ok = FALSE;
1853   size_change_ok = FALSE;
1854   tmp_sec = sec;
1855   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1856                               &hi, poldbfd, NULL, NULL, &skip, &override,
1857                               &type_change_ok, &size_change_ok, &matched))
1858     return FALSE;
1859
1860   if (skip)
1861     return TRUE;
1862
1863   if (override)
1864     {
1865       /* Here SHORTNAME is a versioned name, so we don't expect to see
1866          the type of override we do in the case above unless it is
1867          overridden by a versioned definition.  */
1868       if (hi->root.type != bfd_link_hash_defined
1869           && hi->root.type != bfd_link_hash_defweak)
1870         (*_bfd_error_handler)
1871           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1872            abfd, shortname);
1873     }
1874   else
1875     {
1876       bh = &hi->root;
1877       if (! (_bfd_generic_link_add_one_symbol
1878              (info, abfd, shortname, BSF_INDIRECT,
1879               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1880         return FALSE;
1881       hi = (struct elf_link_hash_entry *) bh;
1882
1883       /* If there is a duplicate definition somewhere, then HI may not
1884          point to an indirect symbol.  We will have reported an error
1885          to the user in that case.  */
1886
1887       if (hi->root.type == bfd_link_hash_indirect)
1888         {
1889           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1890           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1891           hi->dynamic_def |= h->dynamic_def;
1892
1893           /* See if the new flags lead us to realize that the symbol
1894              must be dynamic.  */
1895           if (! *dynsym)
1896             {
1897               if (! dynamic)
1898                 {
1899                   if (! info->executable
1900                       || hi->ref_dynamic)
1901                     *dynsym = TRUE;
1902                 }
1903               else
1904                 {
1905                   if (hi->ref_regular)
1906                     *dynsym = TRUE;
1907                 }
1908             }
1909         }
1910     }
1911
1912   return TRUE;
1913 }
1914 \f
1915 /* This routine is used to export all defined symbols into the dynamic
1916    symbol table.  It is called via elf_link_hash_traverse.  */
1917
1918 static bfd_boolean
1919 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1920 {
1921   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1922
1923   /* Ignore indirect symbols.  These are added by the versioning code.  */
1924   if (h->root.type == bfd_link_hash_indirect)
1925     return TRUE;
1926
1927   /* Ignore this if we won't export it.  */
1928   if (!eif->info->export_dynamic && !h->dynamic)
1929     return TRUE;
1930
1931   if (h->dynindx == -1
1932       && (h->def_regular || h->ref_regular)
1933       && ! bfd_hide_sym_by_version (eif->info->version_info,
1934                                     h->root.root.string))
1935     {
1936       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1937         {
1938           eif->failed = TRUE;
1939           return FALSE;
1940         }
1941     }
1942
1943   return TRUE;
1944 }
1945 \f
1946 /* Look through the symbols which are defined in other shared
1947    libraries and referenced here.  Update the list of version
1948    dependencies.  This will be put into the .gnu.version_r section.
1949    This function is called via elf_link_hash_traverse.  */
1950
1951 static bfd_boolean
1952 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1953                                          void *data)
1954 {
1955   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1956   Elf_Internal_Verneed *t;
1957   Elf_Internal_Vernaux *a;
1958   bfd_size_type amt;
1959
1960   /* We only care about symbols defined in shared objects with version
1961      information.  */
1962   if (!h->def_dynamic
1963       || h->def_regular
1964       || h->dynindx == -1
1965       || h->verinfo.verdef == NULL
1966       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
1967           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
1968     return TRUE;
1969
1970   /* See if we already know about this version.  */
1971   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1972        t != NULL;
1973        t = t->vn_nextref)
1974     {
1975       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1976         continue;
1977
1978       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1979         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1980           return TRUE;
1981
1982       break;
1983     }
1984
1985   /* This is a new version.  Add it to tree we are building.  */
1986
1987   if (t == NULL)
1988     {
1989       amt = sizeof *t;
1990       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
1991       if (t == NULL)
1992         {
1993           rinfo->failed = TRUE;
1994           return FALSE;
1995         }
1996
1997       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1998       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
1999       elf_tdata (rinfo->info->output_bfd)->verref = t;
2000     }
2001
2002   amt = sizeof *a;
2003   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2004   if (a == NULL)
2005     {
2006       rinfo->failed = TRUE;
2007       return FALSE;
2008     }
2009
2010   /* Note that we are copying a string pointer here, and testing it
2011      above.  If bfd_elf_string_from_elf_section is ever changed to
2012      discard the string data when low in memory, this will have to be
2013      fixed.  */
2014   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2015
2016   a->vna_flags = h->verinfo.verdef->vd_flags;
2017   a->vna_nextptr = t->vn_auxptr;
2018
2019   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2020   ++rinfo->vers;
2021
2022   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2023
2024   t->vn_auxptr = a;
2025
2026   return TRUE;
2027 }
2028
2029 /* Figure out appropriate versions for all the symbols.  We may not
2030    have the version number script until we have read all of the input
2031    files, so until that point we don't know which symbols should be
2032    local.  This function is called via elf_link_hash_traverse.  */
2033
2034 static bfd_boolean
2035 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2036 {
2037   struct elf_info_failed *sinfo;
2038   struct bfd_link_info *info;
2039   const struct elf_backend_data *bed;
2040   struct elf_info_failed eif;
2041   char *p;
2042   bfd_size_type amt;
2043
2044   sinfo = (struct elf_info_failed *) data;
2045   info = sinfo->info;
2046
2047   /* Fix the symbol flags.  */
2048   eif.failed = FALSE;
2049   eif.info = info;
2050   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2051     {
2052       if (eif.failed)
2053         sinfo->failed = TRUE;
2054       return FALSE;
2055     }
2056
2057   /* We only need version numbers for symbols defined in regular
2058      objects.  */
2059   if (!h->def_regular)
2060     return TRUE;
2061
2062   bed = get_elf_backend_data (info->output_bfd);
2063   p = strchr (h->root.root.string, ELF_VER_CHR);
2064   if (p != NULL && h->verinfo.vertree == NULL)
2065     {
2066       struct bfd_elf_version_tree *t;
2067
2068       ++p;
2069       if (*p == ELF_VER_CHR)
2070         ++p;
2071
2072       /* If there is no version string, we can just return out.  */
2073       if (*p == '\0')
2074         return TRUE;
2075
2076       /* Look for the version.  If we find it, it is no longer weak.  */
2077       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2078         {
2079           if (strcmp (t->name, p) == 0)
2080             {
2081               size_t len;
2082               char *alc;
2083               struct bfd_elf_version_expr *d;
2084
2085               len = p - h->root.root.string;
2086               alc = (char *) bfd_malloc (len);
2087               if (alc == NULL)
2088                 {
2089                   sinfo->failed = TRUE;
2090                   return FALSE;
2091                 }
2092               memcpy (alc, h->root.root.string, len - 1);
2093               alc[len - 1] = '\0';
2094               if (alc[len - 2] == ELF_VER_CHR)
2095                 alc[len - 2] = '\0';
2096
2097               h->verinfo.vertree = t;
2098               t->used = TRUE;
2099               d = NULL;
2100
2101               if (t->globals.list != NULL)
2102                 d = (*t->match) (&t->globals, NULL, alc);
2103
2104               /* See if there is anything to force this symbol to
2105                  local scope.  */
2106               if (d == NULL && t->locals.list != NULL)
2107                 {
2108                   d = (*t->match) (&t->locals, NULL, alc);
2109                   if (d != NULL
2110                       && h->dynindx != -1
2111                       && ! info->export_dynamic)
2112                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2113                 }
2114
2115               free (alc);
2116               break;
2117             }
2118         }
2119
2120       /* If we are building an application, we need to create a
2121          version node for this version.  */
2122       if (t == NULL && info->executable)
2123         {
2124           struct bfd_elf_version_tree **pp;
2125           int version_index;
2126
2127           /* If we aren't going to export this symbol, we don't need
2128              to worry about it.  */
2129           if (h->dynindx == -1)
2130             return TRUE;
2131
2132           amt = sizeof *t;
2133           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2134           if (t == NULL)
2135             {
2136               sinfo->failed = TRUE;
2137               return FALSE;
2138             }
2139
2140           t->name = p;
2141           t->name_indx = (unsigned int) -1;
2142           t->used = TRUE;
2143
2144           version_index = 1;
2145           /* Don't count anonymous version tag.  */
2146           if (sinfo->info->version_info != NULL
2147               && sinfo->info->version_info->vernum == 0)
2148             version_index = 0;
2149           for (pp = &sinfo->info->version_info;
2150                *pp != NULL;
2151                pp = &(*pp)->next)
2152             ++version_index;
2153           t->vernum = version_index;
2154
2155           *pp = t;
2156
2157           h->verinfo.vertree = t;
2158         }
2159       else if (t == NULL)
2160         {
2161           /* We could not find the version for a symbol when
2162              generating a shared archive.  Return an error.  */
2163           (*_bfd_error_handler)
2164             (_("%B: version node not found for symbol %s"),
2165              info->output_bfd, h->root.root.string);
2166           bfd_set_error (bfd_error_bad_value);
2167           sinfo->failed = TRUE;
2168           return FALSE;
2169         }
2170     }
2171
2172   /* If we don't have a version for this symbol, see if we can find
2173      something.  */
2174   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2175     {
2176       bfd_boolean hide;
2177
2178       h->verinfo.vertree
2179         = bfd_find_version_for_sym (sinfo->info->version_info,
2180                                     h->root.root.string, &hide);
2181       if (h->verinfo.vertree != NULL && hide)
2182         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2183     }
2184
2185   return TRUE;
2186 }
2187 \f
2188 /* Read and swap the relocs from the section indicated by SHDR.  This
2189    may be either a REL or a RELA section.  The relocations are
2190    translated into RELA relocations and stored in INTERNAL_RELOCS,
2191    which should have already been allocated to contain enough space.
2192    The EXTERNAL_RELOCS are a buffer where the external form of the
2193    relocations should be stored.
2194
2195    Returns FALSE if something goes wrong.  */
2196
2197 static bfd_boolean
2198 elf_link_read_relocs_from_section (bfd *abfd,
2199                                    asection *sec,
2200                                    Elf_Internal_Shdr *shdr,
2201                                    void *external_relocs,
2202                                    Elf_Internal_Rela *internal_relocs)
2203 {
2204   const struct elf_backend_data *bed;
2205   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2206   const bfd_byte *erela;
2207   const bfd_byte *erelaend;
2208   Elf_Internal_Rela *irela;
2209   Elf_Internal_Shdr *symtab_hdr;
2210   size_t nsyms;
2211
2212   /* Position ourselves at the start of the section.  */
2213   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2214     return FALSE;
2215
2216   /* Read the relocations.  */
2217   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2218     return FALSE;
2219
2220   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2221   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2222
2223   bed = get_elf_backend_data (abfd);
2224
2225   /* Convert the external relocations to the internal format.  */
2226   if (shdr->sh_entsize == bed->s->sizeof_rel)
2227     swap_in = bed->s->swap_reloc_in;
2228   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2229     swap_in = bed->s->swap_reloca_in;
2230   else
2231     {
2232       bfd_set_error (bfd_error_wrong_format);
2233       return FALSE;
2234     }
2235
2236   erela = (const bfd_byte *) external_relocs;
2237   erelaend = erela + shdr->sh_size;
2238   irela = internal_relocs;
2239   while (erela < erelaend)
2240     {
2241       bfd_vma r_symndx;
2242
2243       (*swap_in) (abfd, erela, irela);
2244       r_symndx = ELF32_R_SYM (irela->r_info);
2245       if (bed->s->arch_size == 64)
2246         r_symndx >>= 24;
2247       if (nsyms > 0)
2248         {
2249           if ((size_t) r_symndx >= nsyms)
2250             {
2251               (*_bfd_error_handler)
2252                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2253                    " for offset 0x%lx in section `%A'"),
2254                  abfd, sec,
2255                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2256               bfd_set_error (bfd_error_bad_value);
2257               return FALSE;
2258             }
2259         }
2260       else if (r_symndx != STN_UNDEF)
2261         {
2262           (*_bfd_error_handler)
2263             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2264                " when the object file has no symbol table"),
2265              abfd, sec,
2266              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2267           bfd_set_error (bfd_error_bad_value);
2268           return FALSE;
2269         }
2270       irela += bed->s->int_rels_per_ext_rel;
2271       erela += shdr->sh_entsize;
2272     }
2273
2274   return TRUE;
2275 }
2276
2277 /* Read and swap the relocs for a section O.  They may have been
2278    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2279    not NULL, they are used as buffers to read into.  They are known to
2280    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2281    the return value is allocated using either malloc or bfd_alloc,
2282    according to the KEEP_MEMORY argument.  If O has two relocation
2283    sections (both REL and RELA relocations), then the REL_HDR
2284    relocations will appear first in INTERNAL_RELOCS, followed by the
2285    RELA_HDR relocations.  */
2286
2287 Elf_Internal_Rela *
2288 _bfd_elf_link_read_relocs (bfd *abfd,
2289                            asection *o,
2290                            void *external_relocs,
2291                            Elf_Internal_Rela *internal_relocs,
2292                            bfd_boolean keep_memory)
2293 {
2294   void *alloc1 = NULL;
2295   Elf_Internal_Rela *alloc2 = NULL;
2296   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2297   struct bfd_elf_section_data *esdo = elf_section_data (o);
2298   Elf_Internal_Rela *internal_rela_relocs;
2299
2300   if (esdo->relocs != NULL)
2301     return esdo->relocs;
2302
2303   if (o->reloc_count == 0)
2304     return NULL;
2305
2306   if (internal_relocs == NULL)
2307     {
2308       bfd_size_type size;
2309
2310       size = o->reloc_count;
2311       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2312       if (keep_memory)
2313         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2314       else
2315         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2316       if (internal_relocs == NULL)
2317         goto error_return;
2318     }
2319
2320   if (external_relocs == NULL)
2321     {
2322       bfd_size_type size = 0;
2323
2324       if (esdo->rel.hdr)
2325         size += esdo->rel.hdr->sh_size;
2326       if (esdo->rela.hdr)
2327         size += esdo->rela.hdr->sh_size;
2328
2329       alloc1 = bfd_malloc (size);
2330       if (alloc1 == NULL)
2331         goto error_return;
2332       external_relocs = alloc1;
2333     }
2334
2335   internal_rela_relocs = internal_relocs;
2336   if (esdo->rel.hdr)
2337     {
2338       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2339                                               external_relocs,
2340                                               internal_relocs))
2341         goto error_return;
2342       external_relocs = (((bfd_byte *) external_relocs)
2343                          + esdo->rel.hdr->sh_size);
2344       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2345                                * bed->s->int_rels_per_ext_rel);
2346     }
2347
2348   if (esdo->rela.hdr
2349       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2350                                               external_relocs,
2351                                               internal_rela_relocs)))
2352     goto error_return;
2353
2354   /* Cache the results for next time, if we can.  */
2355   if (keep_memory)
2356     esdo->relocs = internal_relocs;
2357
2358   if (alloc1 != NULL)
2359     free (alloc1);
2360
2361   /* Don't free alloc2, since if it was allocated we are passing it
2362      back (under the name of internal_relocs).  */
2363
2364   return internal_relocs;
2365
2366  error_return:
2367   if (alloc1 != NULL)
2368     free (alloc1);
2369   if (alloc2 != NULL)
2370     {
2371       if (keep_memory)
2372         bfd_release (abfd, alloc2);
2373       else
2374         free (alloc2);
2375     }
2376   return NULL;
2377 }
2378
2379 /* Compute the size of, and allocate space for, REL_HDR which is the
2380    section header for a section containing relocations for O.  */
2381
2382 static bfd_boolean
2383 _bfd_elf_link_size_reloc_section (bfd *abfd,
2384                                   struct bfd_elf_section_reloc_data *reldata)
2385 {
2386   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2387
2388   /* That allows us to calculate the size of the section.  */
2389   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2390
2391   /* The contents field must last into write_object_contents, so we
2392      allocate it with bfd_alloc rather than malloc.  Also since we
2393      cannot be sure that the contents will actually be filled in,
2394      we zero the allocated space.  */
2395   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2396   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2397     return FALSE;
2398
2399   if (reldata->hashes == NULL && reldata->count)
2400     {
2401       struct elf_link_hash_entry **p;
2402
2403       p = ((struct elf_link_hash_entry **)
2404            bfd_zmalloc (reldata->count * sizeof (*p)));
2405       if (p == NULL)
2406         return FALSE;
2407
2408       reldata->hashes = p;
2409     }
2410
2411   return TRUE;
2412 }
2413
2414 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2415    originated from the section given by INPUT_REL_HDR) to the
2416    OUTPUT_BFD.  */
2417
2418 bfd_boolean
2419 _bfd_elf_link_output_relocs (bfd *output_bfd,
2420                              asection *input_section,
2421                              Elf_Internal_Shdr *input_rel_hdr,
2422                              Elf_Internal_Rela *internal_relocs,
2423                              struct elf_link_hash_entry **rel_hash
2424                                ATTRIBUTE_UNUSED)
2425 {
2426   Elf_Internal_Rela *irela;
2427   Elf_Internal_Rela *irelaend;
2428   bfd_byte *erel;
2429   struct bfd_elf_section_reloc_data *output_reldata;
2430   asection *output_section;
2431   const struct elf_backend_data *bed;
2432   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2433   struct bfd_elf_section_data *esdo;
2434
2435   output_section = input_section->output_section;
2436
2437   bed = get_elf_backend_data (output_bfd);
2438   esdo = elf_section_data (output_section);
2439   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2440     {
2441       output_reldata = &esdo->rel;
2442       swap_out = bed->s->swap_reloc_out;
2443     }
2444   else if (esdo->rela.hdr
2445            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2446     {
2447       output_reldata = &esdo->rela;
2448       swap_out = bed->s->swap_reloca_out;
2449     }
2450   else
2451     {
2452       (*_bfd_error_handler)
2453         (_("%B: relocation size mismatch in %B section %A"),
2454          output_bfd, input_section->owner, input_section);
2455       bfd_set_error (bfd_error_wrong_format);
2456       return FALSE;
2457     }
2458
2459   erel = output_reldata->hdr->contents;
2460   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2461   irela = internal_relocs;
2462   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2463                       * bed->s->int_rels_per_ext_rel);
2464   while (irela < irelaend)
2465     {
2466       (*swap_out) (output_bfd, irela, erel);
2467       irela += bed->s->int_rels_per_ext_rel;
2468       erel += input_rel_hdr->sh_entsize;
2469     }
2470
2471   /* Bump the counter, so that we know where to add the next set of
2472      relocations.  */
2473   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2474
2475   return TRUE;
2476 }
2477 \f
2478 /* Make weak undefined symbols in PIE dynamic.  */
2479
2480 bfd_boolean
2481 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2482                                  struct elf_link_hash_entry *h)
2483 {
2484   if (info->pie
2485       && h->dynindx == -1
2486       && h->root.type == bfd_link_hash_undefweak)
2487     return bfd_elf_link_record_dynamic_symbol (info, h);
2488
2489   return TRUE;
2490 }
2491
2492 /* Fix up the flags for a symbol.  This handles various cases which
2493    can only be fixed after all the input files are seen.  This is
2494    currently called by both adjust_dynamic_symbol and
2495    assign_sym_version, which is unnecessary but perhaps more robust in
2496    the face of future changes.  */
2497
2498 static bfd_boolean
2499 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2500                            struct elf_info_failed *eif)
2501 {
2502   const struct elf_backend_data *bed;
2503
2504   /* If this symbol was mentioned in a non-ELF file, try to set
2505      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2506      permit a non-ELF file to correctly refer to a symbol defined in
2507      an ELF dynamic object.  */
2508   if (h->non_elf)
2509     {
2510       while (h->root.type == bfd_link_hash_indirect)
2511         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2512
2513       if (h->root.type != bfd_link_hash_defined
2514           && h->root.type != bfd_link_hash_defweak)
2515         {
2516           h->ref_regular = 1;
2517           h->ref_regular_nonweak = 1;
2518         }
2519       else
2520         {
2521           if (h->root.u.def.section->owner != NULL
2522               && (bfd_get_flavour (h->root.u.def.section->owner)
2523                   == bfd_target_elf_flavour))
2524             {
2525               h->ref_regular = 1;
2526               h->ref_regular_nonweak = 1;
2527             }
2528           else
2529             h->def_regular = 1;
2530         }
2531
2532       if (h->dynindx == -1
2533           && (h->def_dynamic
2534               || h->ref_dynamic))
2535         {
2536           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2537             {
2538               eif->failed = TRUE;
2539               return FALSE;
2540             }
2541         }
2542     }
2543   else
2544     {
2545       /* Unfortunately, NON_ELF is only correct if the symbol
2546          was first seen in a non-ELF file.  Fortunately, if the symbol
2547          was first seen in an ELF file, we're probably OK unless the
2548          symbol was defined in a non-ELF file.  Catch that case here.
2549          FIXME: We're still in trouble if the symbol was first seen in
2550          a dynamic object, and then later in a non-ELF regular object.  */
2551       if ((h->root.type == bfd_link_hash_defined
2552            || h->root.type == bfd_link_hash_defweak)
2553           && !h->def_regular
2554           && (h->root.u.def.section->owner != NULL
2555               ? (bfd_get_flavour (h->root.u.def.section->owner)
2556                  != bfd_target_elf_flavour)
2557               : (bfd_is_abs_section (h->root.u.def.section)
2558                  && !h->def_dynamic)))
2559         h->def_regular = 1;
2560     }
2561
2562   /* Backend specific symbol fixup.  */
2563   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2564   if (bed->elf_backend_fixup_symbol
2565       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2566     return FALSE;
2567
2568   /* If this is a final link, and the symbol was defined as a common
2569      symbol in a regular object file, and there was no definition in
2570      any dynamic object, then the linker will have allocated space for
2571      the symbol in a common section but the DEF_REGULAR
2572      flag will not have been set.  */
2573   if (h->root.type == bfd_link_hash_defined
2574       && !h->def_regular
2575       && h->ref_regular
2576       && !h->def_dynamic
2577       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2578     h->def_regular = 1;
2579
2580   /* If -Bsymbolic was used (which means to bind references to global
2581      symbols to the definition within the shared object), and this
2582      symbol was defined in a regular object, then it actually doesn't
2583      need a PLT entry.  Likewise, if the symbol has non-default
2584      visibility.  If the symbol has hidden or internal visibility, we
2585      will force it local.  */
2586   if (h->needs_plt
2587       && eif->info->shared
2588       && is_elf_hash_table (eif->info->hash)
2589       && (SYMBOLIC_BIND (eif->info, h)
2590           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2591       && h->def_regular)
2592     {
2593       bfd_boolean force_local;
2594
2595       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2596                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2597       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2598     }
2599
2600   /* If a weak undefined symbol has non-default visibility, we also
2601      hide it from the dynamic linker.  */
2602   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2603       && h->root.type == bfd_link_hash_undefweak)
2604     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2605
2606   /* If this is a weak defined symbol in a dynamic object, and we know
2607      the real definition in the dynamic object, copy interesting flags
2608      over to the real definition.  */
2609   if (h->u.weakdef != NULL)
2610     {
2611       /* If the real definition is defined by a regular object file,
2612          don't do anything special.  See the longer description in
2613          _bfd_elf_adjust_dynamic_symbol, below.  */
2614       if (h->u.weakdef->def_regular)
2615         h->u.weakdef = NULL;
2616       else
2617         {
2618           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2619
2620           while (h->root.type == bfd_link_hash_indirect)
2621             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2622
2623           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2624                       || h->root.type == bfd_link_hash_defweak);
2625           BFD_ASSERT (weakdef->def_dynamic);
2626           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2627                       || weakdef->root.type == bfd_link_hash_defweak);
2628           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2629         }
2630     }
2631
2632   return TRUE;
2633 }
2634
2635 /* Make the backend pick a good value for a dynamic symbol.  This is
2636    called via elf_link_hash_traverse, and also calls itself
2637    recursively.  */
2638
2639 static bfd_boolean
2640 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2641 {
2642   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2643   bfd *dynobj;
2644   const struct elf_backend_data *bed;
2645
2646   if (! is_elf_hash_table (eif->info->hash))
2647     return FALSE;
2648
2649   /* Ignore indirect symbols.  These are added by the versioning code.  */
2650   if (h->root.type == bfd_link_hash_indirect)
2651     return TRUE;
2652
2653   /* Fix the symbol flags.  */
2654   if (! _bfd_elf_fix_symbol_flags (h, eif))
2655     return FALSE;
2656
2657   /* If this symbol does not require a PLT entry, and it is not
2658      defined by a dynamic object, or is not referenced by a regular
2659      object, ignore it.  We do have to handle a weak defined symbol,
2660      even if no regular object refers to it, if we decided to add it
2661      to the dynamic symbol table.  FIXME: Do we normally need to worry
2662      about symbols which are defined by one dynamic object and
2663      referenced by another one?  */
2664   if (!h->needs_plt
2665       && h->type != STT_GNU_IFUNC
2666       && (h->def_regular
2667           || !h->def_dynamic
2668           || (!h->ref_regular
2669               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2670     {
2671       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2672       return TRUE;
2673     }
2674
2675   /* If we've already adjusted this symbol, don't do it again.  This
2676      can happen via a recursive call.  */
2677   if (h->dynamic_adjusted)
2678     return TRUE;
2679
2680   /* Don't look at this symbol again.  Note that we must set this
2681      after checking the above conditions, because we may look at a
2682      symbol once, decide not to do anything, and then get called
2683      recursively later after REF_REGULAR is set below.  */
2684   h->dynamic_adjusted = 1;
2685
2686   /* If this is a weak definition, and we know a real definition, and
2687      the real symbol is not itself defined by a regular object file,
2688      then get a good value for the real definition.  We handle the
2689      real symbol first, for the convenience of the backend routine.
2690
2691      Note that there is a confusing case here.  If the real definition
2692      is defined by a regular object file, we don't get the real symbol
2693      from the dynamic object, but we do get the weak symbol.  If the
2694      processor backend uses a COPY reloc, then if some routine in the
2695      dynamic object changes the real symbol, we will not see that
2696      change in the corresponding weak symbol.  This is the way other
2697      ELF linkers work as well, and seems to be a result of the shared
2698      library model.
2699
2700      I will clarify this issue.  Most SVR4 shared libraries define the
2701      variable _timezone and define timezone as a weak synonym.  The
2702      tzset call changes _timezone.  If you write
2703        extern int timezone;
2704        int _timezone = 5;
2705        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2706      you might expect that, since timezone is a synonym for _timezone,
2707      the same number will print both times.  However, if the processor
2708      backend uses a COPY reloc, then actually timezone will be copied
2709      into your process image, and, since you define _timezone
2710      yourself, _timezone will not.  Thus timezone and _timezone will
2711      wind up at different memory locations.  The tzset call will set
2712      _timezone, leaving timezone unchanged.  */
2713
2714   if (h->u.weakdef != NULL)
2715     {
2716       /* If we get to this point, there is an implicit reference to
2717          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2718       h->u.weakdef->ref_regular = 1;
2719
2720       /* Ensure that the backend adjust_dynamic_symbol function sees
2721          H->U.WEAKDEF before H by recursively calling ourselves.  */
2722       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2723         return FALSE;
2724     }
2725
2726   /* If a symbol has no type and no size and does not require a PLT
2727      entry, then we are probably about to do the wrong thing here: we
2728      are probably going to create a COPY reloc for an empty object.
2729      This case can arise when a shared object is built with assembly
2730      code, and the assembly code fails to set the symbol type.  */
2731   if (h->size == 0
2732       && h->type == STT_NOTYPE
2733       && !h->needs_plt)
2734     (*_bfd_error_handler)
2735       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2736        h->root.root.string);
2737
2738   dynobj = elf_hash_table (eif->info)->dynobj;
2739   bed = get_elf_backend_data (dynobj);
2740
2741   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2742     {
2743       eif->failed = TRUE;
2744       return FALSE;
2745     }
2746
2747   return TRUE;
2748 }
2749
2750 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2751    DYNBSS.  */
2752
2753 bfd_boolean
2754 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2755                               struct elf_link_hash_entry *h,
2756                               asection *dynbss)
2757 {
2758   unsigned int power_of_two;
2759   bfd_vma mask;
2760   asection *sec = h->root.u.def.section;
2761
2762   /* The section aligment of definition is the maximum alignment
2763      requirement of symbols defined in the section.  Since we don't
2764      know the symbol alignment requirement, we start with the
2765      maximum alignment and check low bits of the symbol address
2766      for the minimum alignment.  */
2767   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2768   mask = ((bfd_vma) 1 << power_of_two) - 1;
2769   while ((h->root.u.def.value & mask) != 0)
2770     {
2771        mask >>= 1;
2772        --power_of_two;
2773     }
2774
2775   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2776                                                 dynbss))
2777     {
2778       /* Adjust the section alignment if needed.  */
2779       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2780                                        power_of_two))
2781         return FALSE;
2782     }
2783
2784   /* We make sure that the symbol will be aligned properly.  */
2785   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2786
2787   /* Define the symbol as being at this point in DYNBSS.  */
2788   h->root.u.def.section = dynbss;
2789   h->root.u.def.value = dynbss->size;
2790
2791   /* Increment the size of DYNBSS to make room for the symbol.  */
2792   dynbss->size += h->size;
2793
2794   /* No error if extern_protected_data is true.  */
2795   if (h->protected_def
2796       && (!info->extern_protected_data
2797           || (info->extern_protected_data < 0
2798               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2799     info->callbacks->einfo
2800       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2801        h->root.root.string);
2802
2803   return TRUE;
2804 }
2805
2806 /* Adjust all external symbols pointing into SEC_MERGE sections
2807    to reflect the object merging within the sections.  */
2808
2809 static bfd_boolean
2810 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2811 {
2812   asection *sec;
2813
2814   if ((h->root.type == bfd_link_hash_defined
2815        || h->root.type == bfd_link_hash_defweak)
2816       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2817       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2818     {
2819       bfd *output_bfd = (bfd *) data;
2820
2821       h->root.u.def.value =
2822         _bfd_merged_section_offset (output_bfd,
2823                                     &h->root.u.def.section,
2824                                     elf_section_data (sec)->sec_info,
2825                                     h->root.u.def.value);
2826     }
2827
2828   return TRUE;
2829 }
2830
2831 /* Returns false if the symbol referred to by H should be considered
2832    to resolve local to the current module, and true if it should be
2833    considered to bind dynamically.  */
2834
2835 bfd_boolean
2836 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2837                            struct bfd_link_info *info,
2838                            bfd_boolean not_local_protected)
2839 {
2840   bfd_boolean binding_stays_local_p;
2841   const struct elf_backend_data *bed;
2842   struct elf_link_hash_table *hash_table;
2843
2844   if (h == NULL)
2845     return FALSE;
2846
2847   while (h->root.type == bfd_link_hash_indirect
2848          || h->root.type == bfd_link_hash_warning)
2849     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2850
2851   /* If it was forced local, then clearly it's not dynamic.  */
2852   if (h->dynindx == -1)
2853     return FALSE;
2854   if (h->forced_local)
2855     return FALSE;
2856
2857   /* Identify the cases where name binding rules say that a
2858      visible symbol resolves locally.  */
2859   binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2860
2861   switch (ELF_ST_VISIBILITY (h->other))
2862     {
2863     case STV_INTERNAL:
2864     case STV_HIDDEN:
2865       return FALSE;
2866
2867     case STV_PROTECTED:
2868       hash_table = elf_hash_table (info);
2869       if (!is_elf_hash_table (hash_table))
2870         return FALSE;
2871
2872       bed = get_elf_backend_data (hash_table->dynobj);
2873
2874       /* Proper resolution for function pointer equality may require
2875          that these symbols perhaps be resolved dynamically, even though
2876          we should be resolving them to the current module.  */
2877       if (!not_local_protected || !bed->is_function_type (h->type))
2878         binding_stays_local_p = TRUE;
2879       break;
2880
2881     default:
2882       break;
2883     }
2884
2885   /* If it isn't defined locally, then clearly it's dynamic.  */
2886   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2887     return TRUE;
2888
2889   /* Otherwise, the symbol is dynamic if binding rules don't tell
2890      us that it remains local.  */
2891   return !binding_stays_local_p;
2892 }
2893
2894 /* Return true if the symbol referred to by H should be considered
2895    to resolve local to the current module, and false otherwise.  Differs
2896    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2897    undefined symbols.  The two functions are virtually identical except
2898    for the place where forced_local and dynindx == -1 are tested.  If
2899    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2900    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2901    the symbol is local only for defined symbols.
2902    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2903    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2904    treatment of undefined weak symbols.  For those that do not make
2905    undefined weak symbols dynamic, both functions may return false.  */
2906
2907 bfd_boolean
2908 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2909                               struct bfd_link_info *info,
2910                               bfd_boolean local_protected)
2911 {
2912   const struct elf_backend_data *bed;
2913   struct elf_link_hash_table *hash_table;
2914
2915   /* If it's a local sym, of course we resolve locally.  */
2916   if (h == NULL)
2917     return TRUE;
2918
2919   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2920   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2921       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2922     return TRUE;
2923
2924   /* Common symbols that become definitions don't get the DEF_REGULAR
2925      flag set, so test it first, and don't bail out.  */
2926   if (ELF_COMMON_DEF_P (h))
2927     /* Do nothing.  */;
2928   /* If we don't have a definition in a regular file, then we can't
2929      resolve locally.  The sym is either undefined or dynamic.  */
2930   else if (!h->def_regular)
2931     return FALSE;
2932
2933   /* Forced local symbols resolve locally.  */
2934   if (h->forced_local)
2935     return TRUE;
2936
2937   /* As do non-dynamic symbols.  */
2938   if (h->dynindx == -1)
2939     return TRUE;
2940
2941   /* At this point, we know the symbol is defined and dynamic.  In an
2942      executable it must resolve locally, likewise when building symbolic
2943      shared libraries.  */
2944   if (info->executable || SYMBOLIC_BIND (info, h))
2945     return TRUE;
2946
2947   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2948      with default visibility might not resolve locally.  */
2949   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2950     return FALSE;
2951
2952   hash_table = elf_hash_table (info);
2953   if (!is_elf_hash_table (hash_table))
2954     return TRUE;
2955
2956   bed = get_elf_backend_data (hash_table->dynobj);
2957
2958   /* If extern_protected_data is false, STV_PROTECTED non-function
2959      symbols are local.  */
2960   if ((!info->extern_protected_data
2961        || (info->extern_protected_data < 0
2962            && !bed->extern_protected_data))
2963       && !bed->is_function_type (h->type))
2964     return TRUE;
2965
2966   /* Function pointer equality tests may require that STV_PROTECTED
2967      symbols be treated as dynamic symbols.  If the address of a
2968      function not defined in an executable is set to that function's
2969      plt entry in the executable, then the address of the function in
2970      a shared library must also be the plt entry in the executable.  */
2971   return local_protected;
2972 }
2973
2974 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2975    aligned.  Returns the first TLS output section.  */
2976
2977 struct bfd_section *
2978 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2979 {
2980   struct bfd_section *sec, *tls;
2981   unsigned int align = 0;
2982
2983   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2984     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2985       break;
2986   tls = sec;
2987
2988   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2989     if (sec->alignment_power > align)
2990       align = sec->alignment_power;
2991
2992   elf_hash_table (info)->tls_sec = tls;
2993
2994   /* Ensure the alignment of the first section is the largest alignment,
2995      so that the tls segment starts aligned.  */
2996   if (tls != NULL)
2997     tls->alignment_power = align;
2998
2999   return tls;
3000 }
3001
3002 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3003 static bfd_boolean
3004 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3005                                   Elf_Internal_Sym *sym)
3006 {
3007   const struct elf_backend_data *bed;
3008
3009   /* Local symbols do not count, but target specific ones might.  */
3010   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3011       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3012     return FALSE;
3013
3014   bed = get_elf_backend_data (abfd);
3015   /* Function symbols do not count.  */
3016   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3017     return FALSE;
3018
3019   /* If the section is undefined, then so is the symbol.  */
3020   if (sym->st_shndx == SHN_UNDEF)
3021     return FALSE;
3022
3023   /* If the symbol is defined in the common section, then
3024      it is a common definition and so does not count.  */
3025   if (bed->common_definition (sym))
3026     return FALSE;
3027
3028   /* If the symbol is in a target specific section then we
3029      must rely upon the backend to tell us what it is.  */
3030   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3031     /* FIXME - this function is not coded yet:
3032
3033        return _bfd_is_global_symbol_definition (abfd, sym);
3034
3035        Instead for now assume that the definition is not global,
3036        Even if this is wrong, at least the linker will behave
3037        in the same way that it used to do.  */
3038     return FALSE;
3039
3040   return TRUE;
3041 }
3042
3043 /* Search the symbol table of the archive element of the archive ABFD
3044    whose archive map contains a mention of SYMDEF, and determine if
3045    the symbol is defined in this element.  */
3046 static bfd_boolean
3047 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3048 {
3049   Elf_Internal_Shdr * hdr;
3050   bfd_size_type symcount;
3051   bfd_size_type extsymcount;
3052   bfd_size_type extsymoff;
3053   Elf_Internal_Sym *isymbuf;
3054   Elf_Internal_Sym *isym;
3055   Elf_Internal_Sym *isymend;
3056   bfd_boolean result;
3057
3058   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3059   if (abfd == NULL)
3060     return FALSE;
3061
3062   /* Return FALSE if the object has been claimed by plugin.  */
3063   if (abfd->plugin_format == bfd_plugin_yes)
3064     return FALSE;
3065
3066   if (! bfd_check_format (abfd, bfd_object))
3067     return FALSE;
3068
3069   /* Select the appropriate symbol table.  */
3070   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3071     hdr = &elf_tdata (abfd)->symtab_hdr;
3072   else
3073     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3074
3075   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3076
3077   /* The sh_info field of the symtab header tells us where the
3078      external symbols start.  We don't care about the local symbols.  */
3079   if (elf_bad_symtab (abfd))
3080     {
3081       extsymcount = symcount;
3082       extsymoff = 0;
3083     }
3084   else
3085     {
3086       extsymcount = symcount - hdr->sh_info;
3087       extsymoff = hdr->sh_info;
3088     }
3089
3090   if (extsymcount == 0)
3091     return FALSE;
3092
3093   /* Read in the symbol table.  */
3094   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3095                                   NULL, NULL, NULL);
3096   if (isymbuf == NULL)
3097     return FALSE;
3098
3099   /* Scan the symbol table looking for SYMDEF.  */
3100   result = FALSE;
3101   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3102     {
3103       const char *name;
3104
3105       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3106                                               isym->st_name);
3107       if (name == NULL)
3108         break;
3109
3110       if (strcmp (name, symdef->name) == 0)
3111         {
3112           result = is_global_data_symbol_definition (abfd, isym);
3113           break;
3114         }
3115     }
3116
3117   free (isymbuf);
3118
3119   return result;
3120 }
3121 \f
3122 /* Add an entry to the .dynamic table.  */
3123
3124 bfd_boolean
3125 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3126                             bfd_vma tag,
3127                             bfd_vma val)
3128 {
3129   struct elf_link_hash_table *hash_table;
3130   const struct elf_backend_data *bed;
3131   asection *s;
3132   bfd_size_type newsize;
3133   bfd_byte *newcontents;
3134   Elf_Internal_Dyn dyn;
3135
3136   hash_table = elf_hash_table (info);
3137   if (! is_elf_hash_table (hash_table))
3138     return FALSE;
3139
3140   bed = get_elf_backend_data (hash_table->dynobj);
3141   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3142   BFD_ASSERT (s != NULL);
3143
3144   newsize = s->size + bed->s->sizeof_dyn;
3145   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3146   if (newcontents == NULL)
3147     return FALSE;
3148
3149   dyn.d_tag = tag;
3150   dyn.d_un.d_val = val;
3151   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3152
3153   s->size = newsize;
3154   s->contents = newcontents;
3155
3156   return TRUE;
3157 }
3158
3159 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3160    otherwise just check whether one already exists.  Returns -1 on error,
3161    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3162
3163 static int
3164 elf_add_dt_needed_tag (bfd *abfd,
3165                        struct bfd_link_info *info,
3166                        const char *soname,
3167                        bfd_boolean do_it)
3168 {
3169   struct elf_link_hash_table *hash_table;
3170   bfd_size_type strindex;
3171
3172   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3173     return -1;
3174
3175   hash_table = elf_hash_table (info);
3176   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3177   if (strindex == (bfd_size_type) -1)
3178     return -1;
3179
3180   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3181     {
3182       asection *sdyn;
3183       const struct elf_backend_data *bed;
3184       bfd_byte *extdyn;
3185
3186       bed = get_elf_backend_data (hash_table->dynobj);
3187       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3188       if (sdyn != NULL)
3189         for (extdyn = sdyn->contents;
3190              extdyn < sdyn->contents + sdyn->size;
3191              extdyn += bed->s->sizeof_dyn)
3192           {
3193             Elf_Internal_Dyn dyn;
3194
3195             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3196             if (dyn.d_tag == DT_NEEDED
3197                 && dyn.d_un.d_val == strindex)
3198               {
3199                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3200                 return 1;
3201               }
3202           }
3203     }
3204
3205   if (do_it)
3206     {
3207       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3208         return -1;
3209
3210       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3211         return -1;
3212     }
3213   else
3214     /* We were just checking for existence of the tag.  */
3215     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3216
3217   return 0;
3218 }
3219
3220 static bfd_boolean
3221 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3222 {
3223   for (; needed != NULL; needed = needed->next)
3224     if ((elf_dyn_lib_class (needed->by) & DYN_AS_NEEDED) == 0
3225         && strcmp (soname, needed->name) == 0)
3226       return TRUE;
3227
3228   return FALSE;
3229 }
3230
3231 /* Sort symbol by value, section, and size.  */
3232 static int
3233 elf_sort_symbol (const void *arg1, const void *arg2)
3234 {
3235   const struct elf_link_hash_entry *h1;
3236   const struct elf_link_hash_entry *h2;
3237   bfd_signed_vma vdiff;
3238
3239   h1 = *(const struct elf_link_hash_entry **) arg1;
3240   h2 = *(const struct elf_link_hash_entry **) arg2;
3241   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3242   if (vdiff != 0)
3243     return vdiff > 0 ? 1 : -1;
3244   else
3245     {
3246       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3247       if (sdiff != 0)
3248         return sdiff > 0 ? 1 : -1;
3249     }
3250   vdiff = h1->size - h2->size;
3251   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3252 }
3253
3254 /* This function is used to adjust offsets into .dynstr for
3255    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3256
3257 static bfd_boolean
3258 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3259 {
3260   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3261
3262   if (h->dynindx != -1)
3263     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3264   return TRUE;
3265 }
3266
3267 /* Assign string offsets in .dynstr, update all structures referencing
3268    them.  */
3269
3270 static bfd_boolean
3271 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3272 {
3273   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3274   struct elf_link_local_dynamic_entry *entry;
3275   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3276   bfd *dynobj = hash_table->dynobj;
3277   asection *sdyn;
3278   bfd_size_type size;
3279   const struct elf_backend_data *bed;
3280   bfd_byte *extdyn;
3281
3282   _bfd_elf_strtab_finalize (dynstr);
3283   size = _bfd_elf_strtab_size (dynstr);
3284
3285   bed = get_elf_backend_data (dynobj);
3286   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3287   BFD_ASSERT (sdyn != NULL);
3288
3289   /* Update all .dynamic entries referencing .dynstr strings.  */
3290   for (extdyn = sdyn->contents;
3291        extdyn < sdyn->contents + sdyn->size;
3292        extdyn += bed->s->sizeof_dyn)
3293     {
3294       Elf_Internal_Dyn dyn;
3295
3296       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3297       switch (dyn.d_tag)
3298         {
3299         case DT_STRSZ:
3300           dyn.d_un.d_val = size;
3301           break;
3302         case DT_NEEDED:
3303         case DT_SONAME:
3304         case DT_RPATH:
3305         case DT_RUNPATH:
3306         case DT_FILTER:
3307         case DT_AUXILIARY:
3308         case DT_AUDIT:
3309         case DT_DEPAUDIT:
3310           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3311           break;
3312         default:
3313           continue;
3314         }
3315       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3316     }
3317
3318   /* Now update local dynamic symbols.  */
3319   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3320     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3321                                                   entry->isym.st_name);
3322
3323   /* And the rest of dynamic symbols.  */
3324   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3325
3326   /* Adjust version definitions.  */
3327   if (elf_tdata (output_bfd)->cverdefs)
3328     {
3329       asection *s;
3330       bfd_byte *p;
3331       bfd_size_type i;
3332       Elf_Internal_Verdef def;
3333       Elf_Internal_Verdaux defaux;
3334
3335       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3336       p = s->contents;
3337       do
3338         {
3339           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3340                                    &def);
3341           p += sizeof (Elf_External_Verdef);
3342           if (def.vd_aux != sizeof (Elf_External_Verdef))
3343             continue;
3344           for (i = 0; i < def.vd_cnt; ++i)
3345             {
3346               _bfd_elf_swap_verdaux_in (output_bfd,
3347                                         (Elf_External_Verdaux *) p, &defaux);
3348               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3349                                                         defaux.vda_name);
3350               _bfd_elf_swap_verdaux_out (output_bfd,
3351                                          &defaux, (Elf_External_Verdaux *) p);
3352               p += sizeof (Elf_External_Verdaux);
3353             }
3354         }
3355       while (def.vd_next);
3356     }
3357
3358   /* Adjust version references.  */
3359   if (elf_tdata (output_bfd)->verref)
3360     {
3361       asection *s;
3362       bfd_byte *p;
3363       bfd_size_type i;
3364       Elf_Internal_Verneed need;
3365       Elf_Internal_Vernaux needaux;
3366
3367       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3368       p = s->contents;
3369       do
3370         {
3371           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3372                                     &need);
3373           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3374           _bfd_elf_swap_verneed_out (output_bfd, &need,
3375                                      (Elf_External_Verneed *) p);
3376           p += sizeof (Elf_External_Verneed);
3377           for (i = 0; i < need.vn_cnt; ++i)
3378             {
3379               _bfd_elf_swap_vernaux_in (output_bfd,
3380                                         (Elf_External_Vernaux *) p, &needaux);
3381               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3382                                                          needaux.vna_name);
3383               _bfd_elf_swap_vernaux_out (output_bfd,
3384                                          &needaux,
3385                                          (Elf_External_Vernaux *) p);
3386               p += sizeof (Elf_External_Vernaux);
3387             }
3388         }
3389       while (need.vn_next);
3390     }
3391
3392   return TRUE;
3393 }
3394 \f
3395 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3396    The default is to only match when the INPUT and OUTPUT are exactly
3397    the same target.  */
3398
3399 bfd_boolean
3400 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3401                                     const bfd_target *output)
3402 {
3403   return input == output;
3404 }
3405
3406 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3407    This version is used when different targets for the same architecture
3408    are virtually identical.  */
3409
3410 bfd_boolean
3411 _bfd_elf_relocs_compatible (const bfd_target *input,
3412                             const bfd_target *output)
3413 {
3414   const struct elf_backend_data *obed, *ibed;
3415
3416   if (input == output)
3417     return TRUE;
3418
3419   ibed = xvec_get_elf_backend_data (input);
3420   obed = xvec_get_elf_backend_data (output);
3421
3422   if (ibed->arch != obed->arch)
3423     return FALSE;
3424
3425   /* If both backends are using this function, deem them compatible.  */
3426   return ibed->relocs_compatible == obed->relocs_compatible;
3427 }
3428
3429 /* Make a special call to the linker "notice" function to tell it that
3430    we are about to handle an as-needed lib, or have finished
3431    processing the lib.  */
3432
3433 bfd_boolean
3434 _bfd_elf_notice_as_needed (bfd *ibfd,
3435                            struct bfd_link_info *info,
3436                            enum notice_asneeded_action act)
3437 {
3438   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3439 }
3440
3441 /* Add symbols from an ELF object file to the linker hash table.  */
3442
3443 static bfd_boolean
3444 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3445 {
3446   Elf_Internal_Ehdr *ehdr;
3447   Elf_Internal_Shdr *hdr;
3448   bfd_size_type symcount;
3449   bfd_size_type extsymcount;
3450   bfd_size_type extsymoff;
3451   struct elf_link_hash_entry **sym_hash;
3452   bfd_boolean dynamic;
3453   Elf_External_Versym *extversym = NULL;
3454   Elf_External_Versym *ever;
3455   struct elf_link_hash_entry *weaks;
3456   struct elf_link_hash_entry **nondeflt_vers = NULL;
3457   bfd_size_type nondeflt_vers_cnt = 0;
3458   Elf_Internal_Sym *isymbuf = NULL;
3459   Elf_Internal_Sym *isym;
3460   Elf_Internal_Sym *isymend;
3461   const struct elf_backend_data *bed;
3462   bfd_boolean add_needed;
3463   struct elf_link_hash_table *htab;
3464   bfd_size_type amt;
3465   void *alloc_mark = NULL;
3466   struct bfd_hash_entry **old_table = NULL;
3467   unsigned int old_size = 0;
3468   unsigned int old_count = 0;
3469   void *old_tab = NULL;
3470   void *old_ent;
3471   struct bfd_link_hash_entry *old_undefs = NULL;
3472   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3473   long old_dynsymcount = 0;
3474   bfd_size_type old_dynstr_size = 0;
3475   size_t tabsize = 0;
3476   asection *s;
3477   bfd_boolean just_syms;
3478
3479   htab = elf_hash_table (info);
3480   bed = get_elf_backend_data (abfd);
3481
3482   if ((abfd->flags & DYNAMIC) == 0)
3483     dynamic = FALSE;
3484   else
3485     {
3486       dynamic = TRUE;
3487
3488       /* You can't use -r against a dynamic object.  Also, there's no
3489          hope of using a dynamic object which does not exactly match
3490          the format of the output file.  */
3491       if (info->relocatable
3492           || !is_elf_hash_table (htab)
3493           || info->output_bfd->xvec != abfd->xvec)
3494         {
3495           if (info->relocatable)
3496             bfd_set_error (bfd_error_invalid_operation);
3497           else
3498             bfd_set_error (bfd_error_wrong_format);
3499           goto error_return;
3500         }
3501     }
3502
3503   ehdr = elf_elfheader (abfd);
3504   if (info->warn_alternate_em
3505       && bed->elf_machine_code != ehdr->e_machine
3506       && ((bed->elf_machine_alt1 != 0
3507            && ehdr->e_machine == bed->elf_machine_alt1)
3508           || (bed->elf_machine_alt2 != 0
3509               && ehdr->e_machine == bed->elf_machine_alt2)))
3510     info->callbacks->einfo
3511       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3512        ehdr->e_machine, abfd, bed->elf_machine_code);
3513
3514   /* As a GNU extension, any input sections which are named
3515      .gnu.warning.SYMBOL are treated as warning symbols for the given
3516      symbol.  This differs from .gnu.warning sections, which generate
3517      warnings when they are included in an output file.  */
3518   /* PR 12761: Also generate this warning when building shared libraries.  */
3519   for (s = abfd->sections; s != NULL; s = s->next)
3520     {
3521       const char *name;
3522
3523       name = bfd_get_section_name (abfd, s);
3524       if (CONST_STRNEQ (name, ".gnu.warning."))
3525         {
3526           char *msg;
3527           bfd_size_type sz;
3528
3529           name += sizeof ".gnu.warning." - 1;
3530
3531           /* If this is a shared object, then look up the symbol
3532              in the hash table.  If it is there, and it is already
3533              been defined, then we will not be using the entry
3534              from this shared object, so we don't need to warn.
3535              FIXME: If we see the definition in a regular object
3536              later on, we will warn, but we shouldn't.  The only
3537              fix is to keep track of what warnings we are supposed
3538              to emit, and then handle them all at the end of the
3539              link.  */
3540           if (dynamic)
3541             {
3542               struct elf_link_hash_entry *h;
3543
3544               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3545
3546               /* FIXME: What about bfd_link_hash_common?  */
3547               if (h != NULL
3548                   && (h->root.type == bfd_link_hash_defined
3549                       || h->root.type == bfd_link_hash_defweak))
3550                 continue;
3551             }
3552
3553           sz = s->size;
3554           msg = (char *) bfd_alloc (abfd, sz + 1);
3555           if (msg == NULL)
3556             goto error_return;
3557
3558           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3559             goto error_return;
3560
3561           msg[sz] = '\0';
3562
3563           if (! (_bfd_generic_link_add_one_symbol
3564                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3565                   FALSE, bed->collect, NULL)))
3566             goto error_return;
3567
3568           if (info->executable)
3569             {
3570               /* Clobber the section size so that the warning does
3571                  not get copied into the output file.  */
3572               s->size = 0;
3573
3574               /* Also set SEC_EXCLUDE, so that symbols defined in
3575                  the warning section don't get copied to the output.  */
3576               s->flags |= SEC_EXCLUDE;
3577             }
3578         }
3579     }
3580
3581   just_syms = ((s = abfd->sections) != NULL
3582                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3583
3584   add_needed = TRUE;
3585   if (! dynamic)
3586     {
3587       /* If we are creating a shared library, create all the dynamic
3588          sections immediately.  We need to attach them to something,
3589          so we attach them to this BFD, provided it is the right
3590          format and is not from ld --just-symbols.  FIXME: If there
3591          are no input BFD's of the same format as the output, we can't
3592          make a shared library.  */
3593       if (!just_syms
3594           && info->shared
3595           && is_elf_hash_table (htab)
3596           && info->output_bfd->xvec == abfd->xvec
3597           && !htab->dynamic_sections_created)
3598         {
3599           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3600             goto error_return;
3601         }
3602     }
3603   else if (!is_elf_hash_table (htab))
3604     goto error_return;
3605   else
3606     {
3607       const char *soname = NULL;
3608       char *audit = NULL;
3609       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3610       int ret;
3611
3612       /* ld --just-symbols and dynamic objects don't mix very well.
3613          ld shouldn't allow it.  */
3614       if (just_syms)
3615         abort ();
3616
3617       /* If this dynamic lib was specified on the command line with
3618          --as-needed in effect, then we don't want to add a DT_NEEDED
3619          tag unless the lib is actually used.  Similary for libs brought
3620          in by another lib's DT_NEEDED.  When --no-add-needed is used
3621          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3622          any dynamic library in DT_NEEDED tags in the dynamic lib at
3623          all.  */
3624       add_needed = (elf_dyn_lib_class (abfd)
3625                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3626                        | DYN_NO_NEEDED)) == 0;
3627
3628       s = bfd_get_section_by_name (abfd, ".dynamic");
3629       if (s != NULL)
3630         {
3631           bfd_byte *dynbuf;
3632           bfd_byte *extdyn;
3633           unsigned int elfsec;
3634           unsigned long shlink;
3635
3636           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3637             {
3638 error_free_dyn:
3639               free (dynbuf);
3640               goto error_return;
3641             }
3642
3643           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3644           if (elfsec == SHN_BAD)
3645             goto error_free_dyn;
3646           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3647
3648           for (extdyn = dynbuf;
3649                extdyn < dynbuf + s->size;
3650                extdyn += bed->s->sizeof_dyn)
3651             {
3652               Elf_Internal_Dyn dyn;
3653
3654               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3655               if (dyn.d_tag == DT_SONAME)
3656                 {
3657                   unsigned int tagv = dyn.d_un.d_val;
3658                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3659                   if (soname == NULL)
3660                     goto error_free_dyn;
3661                 }
3662               if (dyn.d_tag == DT_NEEDED)
3663                 {
3664                   struct bfd_link_needed_list *n, **pn;
3665                   char *fnm, *anm;
3666                   unsigned int tagv = dyn.d_un.d_val;
3667
3668                   amt = sizeof (struct bfd_link_needed_list);
3669                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3670                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3671                   if (n == NULL || fnm == NULL)
3672                     goto error_free_dyn;
3673                   amt = strlen (fnm) + 1;
3674                   anm = (char *) bfd_alloc (abfd, amt);
3675                   if (anm == NULL)
3676                     goto error_free_dyn;
3677                   memcpy (anm, fnm, amt);
3678                   n->name = anm;
3679                   n->by = abfd;
3680                   n->next = NULL;
3681                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3682                     ;
3683                   *pn = n;
3684                 }
3685               if (dyn.d_tag == DT_RUNPATH)
3686                 {
3687                   struct bfd_link_needed_list *n, **pn;
3688                   char *fnm, *anm;
3689                   unsigned int tagv = dyn.d_un.d_val;
3690
3691                   amt = sizeof (struct bfd_link_needed_list);
3692                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3693                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3694                   if (n == NULL || fnm == NULL)
3695                     goto error_free_dyn;
3696                   amt = strlen (fnm) + 1;
3697                   anm = (char *) bfd_alloc (abfd, amt);
3698                   if (anm == NULL)
3699                     goto error_free_dyn;
3700                   memcpy (anm, fnm, amt);
3701                   n->name = anm;
3702                   n->by = abfd;
3703                   n->next = NULL;
3704                   for (pn = & runpath;
3705                        *pn != NULL;
3706                        pn = &(*pn)->next)
3707                     ;
3708                   *pn = n;
3709                 }
3710               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3711               if (!runpath && dyn.d_tag == DT_RPATH)
3712                 {
3713                   struct bfd_link_needed_list *n, **pn;
3714                   char *fnm, *anm;
3715                   unsigned int tagv = dyn.d_un.d_val;
3716
3717                   amt = sizeof (struct bfd_link_needed_list);
3718                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3719                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3720                   if (n == NULL || fnm == NULL)
3721                     goto error_free_dyn;
3722                   amt = strlen (fnm) + 1;
3723                   anm = (char *) bfd_alloc (abfd, amt);
3724                   if (anm == NULL)
3725                     goto error_free_dyn;
3726                   memcpy (anm, fnm, amt);
3727                   n->name = anm;
3728                   n->by = abfd;
3729                   n->next = NULL;
3730                   for (pn = & rpath;
3731                        *pn != NULL;
3732                        pn = &(*pn)->next)
3733                     ;
3734                   *pn = n;
3735                 }
3736               if (dyn.d_tag == DT_AUDIT)
3737                 {
3738                   unsigned int tagv = dyn.d_un.d_val;
3739                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3740                 }
3741             }
3742
3743           free (dynbuf);
3744         }
3745
3746       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3747          frees all more recently bfd_alloc'd blocks as well.  */
3748       if (runpath)
3749         rpath = runpath;
3750
3751       if (rpath)
3752         {
3753           struct bfd_link_needed_list **pn;
3754           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3755             ;
3756           *pn = rpath;
3757         }
3758
3759       /* We do not want to include any of the sections in a dynamic
3760          object in the output file.  We hack by simply clobbering the
3761          list of sections in the BFD.  This could be handled more
3762          cleanly by, say, a new section flag; the existing
3763          SEC_NEVER_LOAD flag is not the one we want, because that one
3764          still implies that the section takes up space in the output
3765          file.  */
3766       bfd_section_list_clear (abfd);
3767
3768       /* Find the name to use in a DT_NEEDED entry that refers to this
3769          object.  If the object has a DT_SONAME entry, we use it.
3770          Otherwise, if the generic linker stuck something in
3771          elf_dt_name, we use that.  Otherwise, we just use the file
3772          name.  */
3773       if (soname == NULL || *soname == '\0')
3774         {
3775           soname = elf_dt_name (abfd);
3776           if (soname == NULL || *soname == '\0')
3777             soname = bfd_get_filename (abfd);
3778         }
3779
3780       /* Save the SONAME because sometimes the linker emulation code
3781          will need to know it.  */
3782       elf_dt_name (abfd) = soname;
3783
3784       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3785       if (ret < 0)
3786         goto error_return;
3787
3788       /* If we have already included this dynamic object in the
3789          link, just ignore it.  There is no reason to include a
3790          particular dynamic object more than once.  */
3791       if (ret > 0)
3792         return TRUE;
3793
3794       /* Save the DT_AUDIT entry for the linker emulation code. */
3795       elf_dt_audit (abfd) = audit;
3796     }
3797
3798   /* If this is a dynamic object, we always link against the .dynsym
3799      symbol table, not the .symtab symbol table.  The dynamic linker
3800      will only see the .dynsym symbol table, so there is no reason to
3801      look at .symtab for a dynamic object.  */
3802
3803   if (! dynamic || elf_dynsymtab (abfd) == 0)
3804     hdr = &elf_tdata (abfd)->symtab_hdr;
3805   else
3806     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3807
3808   symcount = hdr->sh_size / bed->s->sizeof_sym;
3809
3810   /* The sh_info field of the symtab header tells us where the
3811      external symbols start.  We don't care about the local symbols at
3812      this point.  */
3813   if (elf_bad_symtab (abfd))
3814     {
3815       extsymcount = symcount;
3816       extsymoff = 0;
3817     }
3818   else
3819     {
3820       extsymcount = symcount - hdr->sh_info;
3821       extsymoff = hdr->sh_info;
3822     }
3823
3824   sym_hash = elf_sym_hashes (abfd);
3825   if (extsymcount != 0)
3826     {
3827       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3828                                       NULL, NULL, NULL);
3829       if (isymbuf == NULL)
3830         goto error_return;
3831
3832       if (sym_hash == NULL)
3833         {
3834           /* We store a pointer to the hash table entry for each
3835              external symbol.  */
3836           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3837           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3838           if (sym_hash == NULL)
3839             goto error_free_sym;
3840           elf_sym_hashes (abfd) = sym_hash;
3841         }
3842     }
3843
3844   if (dynamic)
3845     {
3846       /* Read in any version definitions.  */
3847       if (!_bfd_elf_slurp_version_tables (abfd,
3848                                           info->default_imported_symver))
3849         goto error_free_sym;
3850
3851       /* Read in the symbol versions, but don't bother to convert them
3852          to internal format.  */
3853       if (elf_dynversym (abfd) != 0)
3854         {
3855           Elf_Internal_Shdr *versymhdr;
3856
3857           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3858           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3859           if (extversym == NULL)
3860             goto error_free_sym;
3861           amt = versymhdr->sh_size;
3862           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3863               || bfd_bread (extversym, amt, abfd) != amt)
3864             goto error_free_vers;
3865         }
3866     }
3867
3868   /* If we are loading an as-needed shared lib, save the symbol table
3869      state before we start adding symbols.  If the lib turns out
3870      to be unneeded, restore the state.  */
3871   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3872     {
3873       unsigned int i;
3874       size_t entsize;
3875
3876       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3877         {
3878           struct bfd_hash_entry *p;
3879           struct elf_link_hash_entry *h;
3880
3881           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3882             {
3883               h = (struct elf_link_hash_entry *) p;
3884               entsize += htab->root.table.entsize;
3885               if (h->root.type == bfd_link_hash_warning)
3886                 entsize += htab->root.table.entsize;
3887             }
3888         }
3889
3890       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3891       old_tab = bfd_malloc (tabsize + entsize);
3892       if (old_tab == NULL)
3893         goto error_free_vers;
3894
3895       /* Remember the current objalloc pointer, so that all mem for
3896          symbols added can later be reclaimed.  */
3897       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3898       if (alloc_mark == NULL)
3899         goto error_free_vers;
3900
3901       /* Make a special call to the linker "notice" function to
3902          tell it that we are about to handle an as-needed lib.  */
3903       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
3904         goto error_free_vers;
3905
3906       /* Clone the symbol table.  Remember some pointers into the
3907          symbol table, and dynamic symbol count.  */
3908       old_ent = (char *) old_tab + tabsize;
3909       memcpy (old_tab, htab->root.table.table, tabsize);
3910       old_undefs = htab->root.undefs;
3911       old_undefs_tail = htab->root.undefs_tail;
3912       old_table = htab->root.table.table;
3913       old_size = htab->root.table.size;
3914       old_count = htab->root.table.count;
3915       old_dynsymcount = htab->dynsymcount;
3916       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
3917
3918       for (i = 0; i < htab->root.table.size; i++)
3919         {
3920           struct bfd_hash_entry *p;
3921           struct elf_link_hash_entry *h;
3922
3923           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3924             {
3925               memcpy (old_ent, p, htab->root.table.entsize);
3926               old_ent = (char *) old_ent + htab->root.table.entsize;
3927               h = (struct elf_link_hash_entry *) p;
3928               if (h->root.type == bfd_link_hash_warning)
3929                 {
3930                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3931                   old_ent = (char *) old_ent + htab->root.table.entsize;
3932                 }
3933             }
3934         }
3935     }
3936
3937   weaks = NULL;
3938   ever = extversym != NULL ? extversym + extsymoff : NULL;
3939   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3940        isym < isymend;
3941        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3942     {
3943       int bind;
3944       bfd_vma value;
3945       asection *sec, *new_sec;
3946       flagword flags;
3947       const char *name;
3948       struct elf_link_hash_entry *h;
3949       struct elf_link_hash_entry *hi;
3950       bfd_boolean definition;
3951       bfd_boolean size_change_ok;
3952       bfd_boolean type_change_ok;
3953       bfd_boolean new_weakdef;
3954       bfd_boolean new_weak;
3955       bfd_boolean old_weak;
3956       bfd_boolean override;
3957       bfd_boolean common;
3958       unsigned int old_alignment;
3959       bfd *old_bfd;
3960       bfd_boolean matched;
3961
3962       override = FALSE;
3963
3964       flags = BSF_NO_FLAGS;
3965       sec = NULL;
3966       value = isym->st_value;
3967       common = bed->common_definition (isym);
3968
3969       bind = ELF_ST_BIND (isym->st_info);
3970       switch (bind)
3971         {
3972         case STB_LOCAL:
3973           /* This should be impossible, since ELF requires that all
3974              global symbols follow all local symbols, and that sh_info
3975              point to the first global symbol.  Unfortunately, Irix 5
3976              screws this up.  */
3977           continue;
3978
3979         case STB_GLOBAL:
3980           if (isym->st_shndx != SHN_UNDEF && !common)
3981             flags = BSF_GLOBAL;
3982           break;
3983
3984         case STB_WEAK:
3985           flags = BSF_WEAK;
3986           break;
3987
3988         case STB_GNU_UNIQUE:
3989           flags = BSF_GNU_UNIQUE;
3990           break;
3991
3992         default:
3993           /* Leave it up to the processor backend.  */
3994           break;
3995         }
3996
3997       if (isym->st_shndx == SHN_UNDEF)
3998         sec = bfd_und_section_ptr;
3999       else if (isym->st_shndx == SHN_ABS)
4000         sec = bfd_abs_section_ptr;
4001       else if (isym->st_shndx == SHN_COMMON)
4002         {
4003           sec = bfd_com_section_ptr;
4004           /* What ELF calls the size we call the value.  What ELF
4005              calls the value we call the alignment.  */
4006           value = isym->st_size;
4007         }
4008       else
4009         {
4010           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4011           if (sec == NULL)
4012             sec = bfd_abs_section_ptr;
4013           else if (discarded_section (sec))
4014             {
4015               /* Symbols from discarded section are undefined.  We keep
4016                  its visibility.  */
4017               sec = bfd_und_section_ptr;
4018               isym->st_shndx = SHN_UNDEF;
4019             }
4020           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4021             value -= sec->vma;
4022         }
4023
4024       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4025                                               isym->st_name);
4026       if (name == NULL)
4027         goto error_free_vers;
4028
4029       if (isym->st_shndx == SHN_COMMON
4030           && (abfd->flags & BFD_PLUGIN) != 0)
4031         {
4032           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4033
4034           if (xc == NULL)
4035             {
4036               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4037                                  | SEC_EXCLUDE);
4038               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4039               if (xc == NULL)
4040                 goto error_free_vers;
4041             }
4042           sec = xc;
4043         }
4044       else if (isym->st_shndx == SHN_COMMON
4045                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4046                && !info->relocatable)
4047         {
4048           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4049
4050           if (tcomm == NULL)
4051             {
4052               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4053                                  | SEC_LINKER_CREATED);
4054               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4055               if (tcomm == NULL)
4056                 goto error_free_vers;
4057             }
4058           sec = tcomm;
4059         }
4060       else if (bed->elf_add_symbol_hook)
4061         {
4062           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4063                                              &sec, &value))
4064             goto error_free_vers;
4065
4066           /* The hook function sets the name to NULL if this symbol
4067              should be skipped for some reason.  */
4068           if (name == NULL)
4069             continue;
4070         }
4071
4072       /* Sanity check that all possibilities were handled.  */
4073       if (sec == NULL)
4074         {
4075           bfd_set_error (bfd_error_bad_value);
4076           goto error_free_vers;
4077         }
4078
4079       /* Silently discard TLS symbols from --just-syms.  There's
4080          no way to combine a static TLS block with a new TLS block
4081          for this executable.  */
4082       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4083           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4084         continue;
4085
4086       if (bfd_is_und_section (sec)
4087           || bfd_is_com_section (sec))
4088         definition = FALSE;
4089       else
4090         definition = TRUE;
4091
4092       size_change_ok = FALSE;
4093       type_change_ok = bed->type_change_ok;
4094       old_weak = FALSE;
4095       matched = FALSE;
4096       old_alignment = 0;
4097       old_bfd = NULL;
4098       new_sec = sec;
4099
4100       if (is_elf_hash_table (htab))
4101         {
4102           Elf_Internal_Versym iver;
4103           unsigned int vernum = 0;
4104           bfd_boolean skip;
4105
4106           if (ever == NULL)
4107             {
4108               if (info->default_imported_symver)
4109                 /* Use the default symbol version created earlier.  */
4110                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4111               else
4112                 iver.vs_vers = 0;
4113             }
4114           else
4115             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4116
4117           vernum = iver.vs_vers & VERSYM_VERSION;
4118
4119           /* If this is a hidden symbol, or if it is not version
4120              1, we append the version name to the symbol name.
4121              However, we do not modify a non-hidden absolute symbol
4122              if it is not a function, because it might be the version
4123              symbol itself.  FIXME: What if it isn't?  */
4124           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4125               || (vernum > 1
4126                   && (!bfd_is_abs_section (sec)
4127                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4128             {
4129               const char *verstr;
4130               size_t namelen, verlen, newlen;
4131               char *newname, *p;
4132
4133               if (isym->st_shndx != SHN_UNDEF)
4134                 {
4135                   if (vernum > elf_tdata (abfd)->cverdefs)
4136                     verstr = NULL;
4137                   else if (vernum > 1)
4138                     verstr =
4139                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4140                   else
4141                     verstr = "";
4142
4143                   if (verstr == NULL)
4144                     {
4145                       (*_bfd_error_handler)
4146                         (_("%B: %s: invalid version %u (max %d)"),
4147                          abfd, name, vernum,
4148                          elf_tdata (abfd)->cverdefs);
4149                       bfd_set_error (bfd_error_bad_value);
4150                       goto error_free_vers;
4151                     }
4152                 }
4153               else
4154                 {
4155                   /* We cannot simply test for the number of
4156                      entries in the VERNEED section since the
4157                      numbers for the needed versions do not start
4158                      at 0.  */
4159                   Elf_Internal_Verneed *t;
4160
4161                   verstr = NULL;
4162                   for (t = elf_tdata (abfd)->verref;
4163                        t != NULL;
4164                        t = t->vn_nextref)
4165                     {
4166                       Elf_Internal_Vernaux *a;
4167
4168                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4169                         {
4170                           if (a->vna_other == vernum)
4171                             {
4172                               verstr = a->vna_nodename;
4173                               break;
4174                             }
4175                         }
4176                       if (a != NULL)
4177                         break;
4178                     }
4179                   if (verstr == NULL)
4180                     {
4181                       (*_bfd_error_handler)
4182                         (_("%B: %s: invalid needed version %d"),
4183                          abfd, name, vernum);
4184                       bfd_set_error (bfd_error_bad_value);
4185                       goto error_free_vers;
4186                     }
4187                 }
4188
4189               namelen = strlen (name);
4190               verlen = strlen (verstr);
4191               newlen = namelen + verlen + 2;
4192               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4193                   && isym->st_shndx != SHN_UNDEF)
4194                 ++newlen;
4195
4196               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4197               if (newname == NULL)
4198                 goto error_free_vers;
4199               memcpy (newname, name, namelen);
4200               p = newname + namelen;
4201               *p++ = ELF_VER_CHR;
4202               /* If this is a defined non-hidden version symbol,
4203                  we add another @ to the name.  This indicates the
4204                  default version of the symbol.  */
4205               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4206                   && isym->st_shndx != SHN_UNDEF)
4207                 *p++ = ELF_VER_CHR;
4208               memcpy (p, verstr, verlen + 1);
4209
4210               name = newname;
4211             }
4212
4213           /* If this symbol has default visibility and the user has
4214              requested we not re-export it, then mark it as hidden.  */
4215           if (definition
4216               && !dynamic
4217               && abfd->no_export
4218               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4219             isym->st_other = (STV_HIDDEN
4220                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4221
4222           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4223                                       sym_hash, &old_bfd, &old_weak,
4224                                       &old_alignment, &skip, &override,
4225                                       &type_change_ok, &size_change_ok,
4226                                       &matched))
4227             goto error_free_vers;
4228
4229           if (skip)
4230             continue;
4231
4232           /* Override a definition only if the new symbol matches the
4233              existing one.  */
4234           if (override && matched)
4235             definition = FALSE;
4236
4237           h = *sym_hash;
4238           while (h->root.type == bfd_link_hash_indirect
4239                  || h->root.type == bfd_link_hash_warning)
4240             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4241
4242           if (elf_tdata (abfd)->verdef != NULL
4243               && vernum > 1
4244               && definition)
4245             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4246         }
4247
4248       if (! (_bfd_generic_link_add_one_symbol
4249              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4250               (struct bfd_link_hash_entry **) sym_hash)))
4251         goto error_free_vers;
4252
4253       h = *sym_hash;
4254       /* We need to make sure that indirect symbol dynamic flags are
4255          updated.  */
4256       hi = h;
4257       while (h->root.type == bfd_link_hash_indirect
4258              || h->root.type == bfd_link_hash_warning)
4259         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4260
4261       *sym_hash = h;
4262
4263       new_weak = (flags & BSF_WEAK) != 0;
4264       new_weakdef = FALSE;
4265       if (dynamic
4266           && definition
4267           && new_weak
4268           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4269           && is_elf_hash_table (htab)
4270           && h->u.weakdef == NULL)
4271         {
4272           /* Keep a list of all weak defined non function symbols from
4273              a dynamic object, using the weakdef field.  Later in this
4274              function we will set the weakdef field to the correct
4275              value.  We only put non-function symbols from dynamic
4276              objects on this list, because that happens to be the only
4277              time we need to know the normal symbol corresponding to a
4278              weak symbol, and the information is time consuming to
4279              figure out.  If the weakdef field is not already NULL,
4280              then this symbol was already defined by some previous
4281              dynamic object, and we will be using that previous
4282              definition anyhow.  */
4283
4284           h->u.weakdef = weaks;
4285           weaks = h;
4286           new_weakdef = TRUE;
4287         }
4288
4289       /* Set the alignment of a common symbol.  */
4290       if ((common || bfd_is_com_section (sec))
4291           && h->root.type == bfd_link_hash_common)
4292         {
4293           unsigned int align;
4294
4295           if (common)
4296             align = bfd_log2 (isym->st_value);
4297           else
4298             {
4299               /* The new symbol is a common symbol in a shared object.
4300                  We need to get the alignment from the section.  */
4301               align = new_sec->alignment_power;
4302             }
4303           if (align > old_alignment)
4304             h->root.u.c.p->alignment_power = align;
4305           else
4306             h->root.u.c.p->alignment_power = old_alignment;
4307         }
4308
4309       if (is_elf_hash_table (htab))
4310         {
4311           /* Set a flag in the hash table entry indicating the type of
4312              reference or definition we just found.  A dynamic symbol
4313              is one which is referenced or defined by both a regular
4314              object and a shared object.  */
4315           bfd_boolean dynsym = FALSE;
4316
4317           /* Plugin symbols aren't normal.  Don't set def_regular or
4318              ref_regular for them, or make them dynamic.  */
4319           if ((abfd->flags & BFD_PLUGIN) != 0)
4320             ;
4321           else if (! dynamic)
4322             {
4323               if (! definition)
4324                 {
4325                   h->ref_regular = 1;
4326                   if (bind != STB_WEAK)
4327                     h->ref_regular_nonweak = 1;
4328                 }
4329               else
4330                 {
4331                   h->def_regular = 1;
4332                   if (h->def_dynamic)
4333                     {
4334                       h->def_dynamic = 0;
4335                       h->ref_dynamic = 1;
4336                     }
4337                 }
4338
4339               /* If the indirect symbol has been forced local, don't
4340                  make the real symbol dynamic.  */
4341               if ((h == hi || !hi->forced_local)
4342                   && ((! info->executable && ! info->relocatable)
4343                       || h->def_dynamic
4344                       || h->ref_dynamic))
4345                 dynsym = TRUE;
4346             }
4347           else
4348             {
4349               if (! definition)
4350                 {
4351                   h->ref_dynamic = 1;
4352                   hi->ref_dynamic = 1;
4353                 }
4354               else
4355                 {
4356                   h->def_dynamic = 1;
4357                   hi->def_dynamic = 1;
4358                 }
4359
4360               /* If the indirect symbol has been forced local, don't
4361                  make the real symbol dynamic.  */
4362               if ((h == hi || !hi->forced_local)
4363                   && (h->def_regular
4364                       || h->ref_regular
4365                       || (h->u.weakdef != NULL
4366                           && ! new_weakdef
4367                           && h->u.weakdef->dynindx != -1)))
4368                 dynsym = TRUE;
4369             }
4370
4371           /* Check to see if we need to add an indirect symbol for
4372              the default name.  */
4373           if (definition
4374               || (!override && h->root.type == bfd_link_hash_common))
4375             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4376                                               sec, value, &old_bfd, &dynsym))
4377               goto error_free_vers;
4378
4379           /* Check the alignment when a common symbol is involved. This
4380              can change when a common symbol is overridden by a normal
4381              definition or a common symbol is ignored due to the old
4382              normal definition. We need to make sure the maximum
4383              alignment is maintained.  */
4384           if ((old_alignment || common)
4385               && h->root.type != bfd_link_hash_common)
4386             {
4387               unsigned int common_align;
4388               unsigned int normal_align;
4389               unsigned int symbol_align;
4390               bfd *normal_bfd;
4391               bfd *common_bfd;
4392
4393               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4394                           || h->root.type == bfd_link_hash_defweak);
4395
4396               symbol_align = ffs (h->root.u.def.value) - 1;
4397               if (h->root.u.def.section->owner != NULL
4398                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4399                 {
4400                   normal_align = h->root.u.def.section->alignment_power;
4401                   if (normal_align > symbol_align)
4402                     normal_align = symbol_align;
4403                 }
4404               else
4405                 normal_align = symbol_align;
4406
4407               if (old_alignment)
4408                 {
4409                   common_align = old_alignment;
4410                   common_bfd = old_bfd;
4411                   normal_bfd = abfd;
4412                 }
4413               else
4414                 {
4415                   common_align = bfd_log2 (isym->st_value);
4416                   common_bfd = abfd;
4417                   normal_bfd = old_bfd;
4418                 }
4419
4420               if (normal_align < common_align)
4421                 {
4422                   /* PR binutils/2735 */
4423                   if (normal_bfd == NULL)
4424                     (*_bfd_error_handler)
4425                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4426                          " greater than the alignment (%u) of its section %A"),
4427                        common_bfd, h->root.u.def.section,
4428                        1 << common_align, name, 1 << normal_align);
4429                   else
4430                     (*_bfd_error_handler)
4431                       (_("Warning: alignment %u of symbol `%s' in %B"
4432                          " is smaller than %u in %B"),
4433                        normal_bfd, common_bfd,
4434                        1 << normal_align, name, 1 << common_align);
4435                 }
4436             }
4437
4438           /* Remember the symbol size if it isn't undefined.  */
4439           if (isym->st_size != 0
4440               && isym->st_shndx != SHN_UNDEF
4441               && (definition || h->size == 0))
4442             {
4443               if (h->size != 0
4444                   && h->size != isym->st_size
4445                   && ! size_change_ok)
4446                 (*_bfd_error_handler)
4447                   (_("Warning: size of symbol `%s' changed"
4448                      " from %lu in %B to %lu in %B"),
4449                    old_bfd, abfd,
4450                    name, (unsigned long) h->size,
4451                    (unsigned long) isym->st_size);
4452
4453               h->size = isym->st_size;
4454             }
4455
4456           /* If this is a common symbol, then we always want H->SIZE
4457              to be the size of the common symbol.  The code just above
4458              won't fix the size if a common symbol becomes larger.  We
4459              don't warn about a size change here, because that is
4460              covered by --warn-common.  Allow changes between different
4461              function types.  */
4462           if (h->root.type == bfd_link_hash_common)
4463             h->size = h->root.u.c.size;
4464
4465           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4466               && ((definition && !new_weak)
4467                   || (old_weak && h->root.type == bfd_link_hash_common)
4468                   || h->type == STT_NOTYPE))
4469             {
4470               unsigned int type = ELF_ST_TYPE (isym->st_info);
4471
4472               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4473                  symbol.  */
4474               if (type == STT_GNU_IFUNC
4475                   && (abfd->flags & DYNAMIC) != 0)
4476                 type = STT_FUNC;
4477
4478               if (h->type != type)
4479                 {
4480                   if (h->type != STT_NOTYPE && ! type_change_ok)
4481                     (*_bfd_error_handler)
4482                       (_("Warning: type of symbol `%s' changed"
4483                          " from %d to %d in %B"),
4484                        abfd, name, h->type, type);
4485
4486                   h->type = type;
4487                 }
4488             }
4489
4490           /* Merge st_other field.  */
4491           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4492
4493           /* We don't want to make debug symbol dynamic.  */
4494           if (definition && (sec->flags & SEC_DEBUGGING) && !info->relocatable)
4495             dynsym = FALSE;
4496
4497           /* Nor should we make plugin symbols dynamic.  */
4498           if ((abfd->flags & BFD_PLUGIN) != 0)
4499             dynsym = FALSE;
4500
4501           if (definition)
4502             {
4503               h->target_internal = isym->st_target_internal;
4504               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4505             }
4506
4507           if (definition && !dynamic)
4508             {
4509               char *p = strchr (name, ELF_VER_CHR);
4510               if (p != NULL && p[1] != ELF_VER_CHR)
4511                 {
4512                   /* Queue non-default versions so that .symver x, x@FOO
4513                      aliases can be checked.  */
4514                   if (!nondeflt_vers)
4515                     {
4516                       amt = ((isymend - isym + 1)
4517                              * sizeof (struct elf_link_hash_entry *));
4518                       nondeflt_vers
4519                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4520                       if (!nondeflt_vers)
4521                         goto error_free_vers;
4522                     }
4523                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4524                 }
4525             }
4526
4527           if (dynsym && h->dynindx == -1)
4528             {
4529               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4530                 goto error_free_vers;
4531               if (h->u.weakdef != NULL
4532                   && ! new_weakdef
4533                   && h->u.weakdef->dynindx == -1)
4534                 {
4535                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4536                     goto error_free_vers;
4537                 }
4538             }
4539           else if (dynsym && h->dynindx != -1)
4540             /* If the symbol already has a dynamic index, but
4541                visibility says it should not be visible, turn it into
4542                a local symbol.  */
4543             switch (ELF_ST_VISIBILITY (h->other))
4544               {
4545               case STV_INTERNAL:
4546               case STV_HIDDEN:
4547                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4548                 dynsym = FALSE;
4549                 break;
4550               }
4551
4552           /* Don't add DT_NEEDED for references from the dummy bfd.  */
4553           if (!add_needed
4554               && definition
4555               && ((dynsym
4556                    && h->ref_regular_nonweak
4557                    && (old_bfd == NULL
4558                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4559                   || (h->ref_dynamic_nonweak
4560                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4561                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4562             {
4563               int ret;
4564               const char *soname = elf_dt_name (abfd);
4565
4566               info->callbacks->minfo ("%!", soname, old_bfd,
4567                                       h->root.root.string);
4568
4569               /* A symbol from a library loaded via DT_NEEDED of some
4570                  other library is referenced by a regular object.
4571                  Add a DT_NEEDED entry for it.  Issue an error if
4572                  --no-add-needed is used and the reference was not
4573                  a weak one.  */
4574               if (old_bfd != NULL
4575                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4576                 {
4577                   (*_bfd_error_handler)
4578                     (_("%B: undefined reference to symbol '%s'"),
4579                      old_bfd, name);
4580                   bfd_set_error (bfd_error_missing_dso);
4581                   goto error_free_vers;
4582                 }
4583
4584               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4585                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4586
4587               add_needed = TRUE;
4588               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4589               if (ret < 0)
4590                 goto error_free_vers;
4591
4592               BFD_ASSERT (ret == 0);
4593             }
4594         }
4595     }
4596
4597   if (extversym != NULL)
4598     {
4599       free (extversym);
4600       extversym = NULL;
4601     }
4602
4603   if (isymbuf != NULL)
4604     {
4605       free (isymbuf);
4606       isymbuf = NULL;
4607     }
4608
4609   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4610     {
4611       unsigned int i;
4612
4613       /* Restore the symbol table.  */
4614       old_ent = (char *) old_tab + tabsize;
4615       memset (elf_sym_hashes (abfd), 0,
4616               extsymcount * sizeof (struct elf_link_hash_entry *));
4617       htab->root.table.table = old_table;
4618       htab->root.table.size = old_size;
4619       htab->root.table.count = old_count;
4620       memcpy (htab->root.table.table, old_tab, tabsize);
4621       htab->root.undefs = old_undefs;
4622       htab->root.undefs_tail = old_undefs_tail;
4623       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4624       for (i = 0; i < htab->root.table.size; i++)
4625         {
4626           struct bfd_hash_entry *p;
4627           struct elf_link_hash_entry *h;
4628           bfd_size_type size;
4629           unsigned int alignment_power;
4630
4631           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4632             {
4633               h = (struct elf_link_hash_entry *) p;
4634               if (h->root.type == bfd_link_hash_warning)
4635                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4636               if (h->dynindx >= old_dynsymcount
4637                   && h->dynstr_index < old_dynstr_size)
4638                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4639
4640               /* Preserve the maximum alignment and size for common
4641                  symbols even if this dynamic lib isn't on DT_NEEDED
4642                  since it can still be loaded at run time by another
4643                  dynamic lib.  */
4644               if (h->root.type == bfd_link_hash_common)
4645                 {
4646                   size = h->root.u.c.size;
4647                   alignment_power = h->root.u.c.p->alignment_power;
4648                 }
4649               else
4650                 {
4651                   size = 0;
4652                   alignment_power = 0;
4653                 }
4654               memcpy (p, old_ent, htab->root.table.entsize);
4655               old_ent = (char *) old_ent + htab->root.table.entsize;
4656               h = (struct elf_link_hash_entry *) p;
4657               if (h->root.type == bfd_link_hash_warning)
4658                 {
4659                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4660                   old_ent = (char *) old_ent + htab->root.table.entsize;
4661                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4662                 }
4663               if (h->root.type == bfd_link_hash_common)
4664                 {
4665                   if (size > h->root.u.c.size)
4666                     h->root.u.c.size = size;
4667                   if (alignment_power > h->root.u.c.p->alignment_power)
4668                     h->root.u.c.p->alignment_power = alignment_power;
4669                 }
4670             }
4671         }
4672
4673       /* Make a special call to the linker "notice" function to
4674          tell it that symbols added for crefs may need to be removed.  */
4675       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4676         goto error_free_vers;
4677
4678       free (old_tab);
4679       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4680                            alloc_mark);
4681       if (nondeflt_vers != NULL)
4682         free (nondeflt_vers);
4683       return TRUE;
4684     }
4685
4686   if (old_tab != NULL)
4687     {
4688       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4689         goto error_free_vers;
4690       free (old_tab);
4691       old_tab = NULL;
4692     }
4693
4694   /* Now that all the symbols from this input file are created, if
4695      not performing a relocatable link, handle .symver foo, foo@BAR
4696      such that any relocs against foo become foo@BAR.  */
4697   if (!info->relocatable && nondeflt_vers != NULL)
4698     {
4699       bfd_size_type cnt, symidx;
4700
4701       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4702         {
4703           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4704           char *shortname, *p;
4705
4706           p = strchr (h->root.root.string, ELF_VER_CHR);
4707           if (p == NULL
4708               || (h->root.type != bfd_link_hash_defined
4709                   && h->root.type != bfd_link_hash_defweak))
4710             continue;
4711
4712           amt = p - h->root.root.string;
4713           shortname = (char *) bfd_malloc (amt + 1);
4714           if (!shortname)
4715             goto error_free_vers;
4716           memcpy (shortname, h->root.root.string, amt);
4717           shortname[amt] = '\0';
4718
4719           hi = (struct elf_link_hash_entry *)
4720                bfd_link_hash_lookup (&htab->root, shortname,
4721                                      FALSE, FALSE, FALSE);
4722           if (hi != NULL
4723               && hi->root.type == h->root.type
4724               && hi->root.u.def.value == h->root.u.def.value
4725               && hi->root.u.def.section == h->root.u.def.section)
4726             {
4727               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4728               hi->root.type = bfd_link_hash_indirect;
4729               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4730               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4731               sym_hash = elf_sym_hashes (abfd);
4732               if (sym_hash)
4733                 for (symidx = 0; symidx < extsymcount; ++symidx)
4734                   if (sym_hash[symidx] == hi)
4735                     {
4736                       sym_hash[symidx] = h;
4737                       break;
4738                     }
4739             }
4740           free (shortname);
4741         }
4742       free (nondeflt_vers);
4743       nondeflt_vers = NULL;
4744     }
4745
4746   /* Now set the weakdefs field correctly for all the weak defined
4747      symbols we found.  The only way to do this is to search all the
4748      symbols.  Since we only need the information for non functions in
4749      dynamic objects, that's the only time we actually put anything on
4750      the list WEAKS.  We need this information so that if a regular
4751      object refers to a symbol defined weakly in a dynamic object, the
4752      real symbol in the dynamic object is also put in the dynamic
4753      symbols; we also must arrange for both symbols to point to the
4754      same memory location.  We could handle the general case of symbol
4755      aliasing, but a general symbol alias can only be generated in
4756      assembler code, handling it correctly would be very time
4757      consuming, and other ELF linkers don't handle general aliasing
4758      either.  */
4759   if (weaks != NULL)
4760     {
4761       struct elf_link_hash_entry **hpp;
4762       struct elf_link_hash_entry **hppend;
4763       struct elf_link_hash_entry **sorted_sym_hash;
4764       struct elf_link_hash_entry *h;
4765       size_t sym_count;
4766
4767       /* Since we have to search the whole symbol list for each weak
4768          defined symbol, search time for N weak defined symbols will be
4769          O(N^2). Binary search will cut it down to O(NlogN).  */
4770       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4771       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4772       if (sorted_sym_hash == NULL)
4773         goto error_return;
4774       sym_hash = sorted_sym_hash;
4775       hpp = elf_sym_hashes (abfd);
4776       hppend = hpp + extsymcount;
4777       sym_count = 0;
4778       for (; hpp < hppend; hpp++)
4779         {
4780           h = *hpp;
4781           if (h != NULL
4782               && h->root.type == bfd_link_hash_defined
4783               && !bed->is_function_type (h->type))
4784             {
4785               *sym_hash = h;
4786               sym_hash++;
4787               sym_count++;
4788             }
4789         }
4790
4791       qsort (sorted_sym_hash, sym_count,
4792              sizeof (struct elf_link_hash_entry *),
4793              elf_sort_symbol);
4794
4795       while (weaks != NULL)
4796         {
4797           struct elf_link_hash_entry *hlook;
4798           asection *slook;
4799           bfd_vma vlook;
4800           size_t i, j, idx = 0;
4801
4802           hlook = weaks;
4803           weaks = hlook->u.weakdef;
4804           hlook->u.weakdef = NULL;
4805
4806           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4807                       || hlook->root.type == bfd_link_hash_defweak
4808                       || hlook->root.type == bfd_link_hash_common
4809                       || hlook->root.type == bfd_link_hash_indirect);
4810           slook = hlook->root.u.def.section;
4811           vlook = hlook->root.u.def.value;
4812
4813           i = 0;
4814           j = sym_count;
4815           while (i != j)
4816             {
4817               bfd_signed_vma vdiff;
4818               idx = (i + j) / 2;
4819               h = sorted_sym_hash[idx];
4820               vdiff = vlook - h->root.u.def.value;
4821               if (vdiff < 0)
4822                 j = idx;
4823               else if (vdiff > 0)
4824                 i = idx + 1;
4825               else
4826                 {
4827                   long sdiff = slook->id - h->root.u.def.section->id;
4828                   if (sdiff < 0)
4829                     j = idx;
4830                   else if (sdiff > 0)
4831                     i = idx + 1;
4832                   else
4833                     break;
4834                 }
4835             }
4836
4837           /* We didn't find a value/section match.  */
4838           if (i == j)
4839             continue;
4840
4841           /* With multiple aliases, or when the weak symbol is already
4842              strongly defined, we have multiple matching symbols and
4843              the binary search above may land on any of them.  Step
4844              one past the matching symbol(s).  */
4845           while (++idx != j)
4846             {
4847               h = sorted_sym_hash[idx];
4848               if (h->root.u.def.section != slook
4849                   || h->root.u.def.value != vlook)
4850                 break;
4851             }
4852
4853           /* Now look back over the aliases.  Since we sorted by size
4854              as well as value and section, we'll choose the one with
4855              the largest size.  */
4856           while (idx-- != i)
4857             {
4858               h = sorted_sym_hash[idx];
4859
4860               /* Stop if value or section doesn't match.  */
4861               if (h->root.u.def.section != slook
4862                   || h->root.u.def.value != vlook)
4863                 break;
4864               else if (h != hlook)
4865                 {
4866                   hlook->u.weakdef = h;
4867
4868                   /* If the weak definition is in the list of dynamic
4869                      symbols, make sure the real definition is put
4870                      there as well.  */
4871                   if (hlook->dynindx != -1 && h->dynindx == -1)
4872                     {
4873                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4874                         {
4875                         err_free_sym_hash:
4876                           free (sorted_sym_hash);
4877                           goto error_return;
4878                         }
4879                     }
4880
4881                   /* If the real definition is in the list of dynamic
4882                      symbols, make sure the weak definition is put
4883                      there as well.  If we don't do this, then the
4884                      dynamic loader might not merge the entries for the
4885                      real definition and the weak definition.  */
4886                   if (h->dynindx != -1 && hlook->dynindx == -1)
4887                     {
4888                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4889                         goto err_free_sym_hash;
4890                     }
4891                   break;
4892                 }
4893             }
4894         }
4895
4896       free (sorted_sym_hash);
4897     }
4898
4899   if (bed->check_directives
4900       && !(*bed->check_directives) (abfd, info))
4901     return FALSE;
4902
4903   /* If this object is the same format as the output object, and it is
4904      not a shared library, then let the backend look through the
4905      relocs.
4906
4907      This is required to build global offset table entries and to
4908      arrange for dynamic relocs.  It is not required for the
4909      particular common case of linking non PIC code, even when linking
4910      against shared libraries, but unfortunately there is no way of
4911      knowing whether an object file has been compiled PIC or not.
4912      Looking through the relocs is not particularly time consuming.
4913      The problem is that we must either (1) keep the relocs in memory,
4914      which causes the linker to require additional runtime memory or
4915      (2) read the relocs twice from the input file, which wastes time.
4916      This would be a good case for using mmap.
4917
4918      I have no idea how to handle linking PIC code into a file of a
4919      different format.  It probably can't be done.  */
4920   if (! dynamic
4921       && is_elf_hash_table (htab)
4922       && bed->check_relocs != NULL
4923       && elf_object_id (abfd) == elf_hash_table_id (htab)
4924       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4925     {
4926       asection *o;
4927
4928       for (o = abfd->sections; o != NULL; o = o->next)
4929         {
4930           Elf_Internal_Rela *internal_relocs;
4931           bfd_boolean ok;
4932
4933           if ((o->flags & SEC_RELOC) == 0
4934               || o->reloc_count == 0
4935               || ((info->strip == strip_all || info->strip == strip_debugger)
4936                   && (o->flags & SEC_DEBUGGING) != 0)
4937               || bfd_is_abs_section (o->output_section))
4938             continue;
4939
4940           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4941                                                        info->keep_memory);
4942           if (internal_relocs == NULL)
4943             goto error_return;
4944
4945           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4946
4947           if (elf_section_data (o)->relocs != internal_relocs)
4948             free (internal_relocs);
4949
4950           if (! ok)
4951             goto error_return;
4952         }
4953     }
4954
4955   /* If this is a non-traditional link, try to optimize the handling
4956      of the .stab/.stabstr sections.  */
4957   if (! dynamic
4958       && ! info->traditional_format
4959       && is_elf_hash_table (htab)
4960       && (info->strip != strip_all && info->strip != strip_debugger))
4961     {
4962       asection *stabstr;
4963
4964       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4965       if (stabstr != NULL)
4966         {
4967           bfd_size_type string_offset = 0;
4968           asection *stab;
4969
4970           for (stab = abfd->sections; stab; stab = stab->next)
4971             if (CONST_STRNEQ (stab->name, ".stab")
4972                 && (!stab->name[5] ||
4973                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4974                 && (stab->flags & SEC_MERGE) == 0
4975                 && !bfd_is_abs_section (stab->output_section))
4976               {
4977                 struct bfd_elf_section_data *secdata;
4978
4979                 secdata = elf_section_data (stab);
4980                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4981                                                stabstr, &secdata->sec_info,
4982                                                &string_offset))
4983                   goto error_return;
4984                 if (secdata->sec_info)
4985                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
4986             }
4987         }
4988     }
4989
4990   if (is_elf_hash_table (htab) && add_needed)
4991     {
4992       /* Add this bfd to the loaded list.  */
4993       struct elf_link_loaded_list *n;
4994
4995       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
4996       if (n == NULL)
4997         goto error_return;
4998       n->abfd = abfd;
4999       n->next = htab->loaded;
5000       htab->loaded = n;
5001     }
5002
5003   return TRUE;
5004
5005  error_free_vers:
5006   if (old_tab != NULL)
5007     free (old_tab);
5008   if (nondeflt_vers != NULL)
5009     free (nondeflt_vers);
5010   if (extversym != NULL)
5011     free (extversym);
5012  error_free_sym:
5013   if (isymbuf != NULL)
5014     free (isymbuf);
5015  error_return:
5016   return FALSE;
5017 }
5018
5019 /* Return the linker hash table entry of a symbol that might be
5020    satisfied by an archive symbol.  Return -1 on error.  */
5021
5022 struct elf_link_hash_entry *
5023 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5024                                 struct bfd_link_info *info,
5025                                 const char *name)
5026 {
5027   struct elf_link_hash_entry *h;
5028   char *p, *copy;
5029   size_t len, first;
5030
5031   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5032   if (h != NULL)
5033     return h;
5034
5035   /* If this is a default version (the name contains @@), look up the
5036      symbol again with only one `@' as well as without the version.
5037      The effect is that references to the symbol with and without the
5038      version will be matched by the default symbol in the archive.  */
5039
5040   p = strchr (name, ELF_VER_CHR);
5041   if (p == NULL || p[1] != ELF_VER_CHR)
5042     return h;
5043
5044   /* First check with only one `@'.  */
5045   len = strlen (name);
5046   copy = (char *) bfd_alloc (abfd, len);
5047   if (copy == NULL)
5048     return (struct elf_link_hash_entry *) 0 - 1;
5049
5050   first = p - name + 1;
5051   memcpy (copy, name, first);
5052   memcpy (copy + first, name + first + 1, len - first);
5053
5054   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5055   if (h == NULL)
5056     {
5057       /* We also need to check references to the symbol without the
5058          version.  */
5059       copy[first - 1] = '\0';
5060       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5061                                 FALSE, FALSE, TRUE);
5062     }
5063
5064   bfd_release (abfd, copy);
5065   return h;
5066 }
5067
5068 /* Add symbols from an ELF archive file to the linker hash table.  We
5069    don't use _bfd_generic_link_add_archive_symbols because we need to
5070    handle versioned symbols.
5071
5072    Fortunately, ELF archive handling is simpler than that done by
5073    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5074    oddities.  In ELF, if we find a symbol in the archive map, and the
5075    symbol is currently undefined, we know that we must pull in that
5076    object file.
5077
5078    Unfortunately, we do have to make multiple passes over the symbol
5079    table until nothing further is resolved.  */
5080
5081 static bfd_boolean
5082 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5083 {
5084   symindex c;
5085   unsigned char *included = NULL;
5086   carsym *symdefs;
5087   bfd_boolean loop;
5088   bfd_size_type amt;
5089   const struct elf_backend_data *bed;
5090   struct elf_link_hash_entry * (*archive_symbol_lookup)
5091     (bfd *, struct bfd_link_info *, const char *);
5092
5093   if (! bfd_has_map (abfd))
5094     {
5095       /* An empty archive is a special case.  */
5096       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5097         return TRUE;
5098       bfd_set_error (bfd_error_no_armap);
5099       return FALSE;
5100     }
5101
5102   /* Keep track of all symbols we know to be already defined, and all
5103      files we know to be already included.  This is to speed up the
5104      second and subsequent passes.  */
5105   c = bfd_ardata (abfd)->symdef_count;
5106   if (c == 0)
5107     return TRUE;
5108   amt = c;
5109   amt *= sizeof (*included);
5110   included = (unsigned char *) bfd_zmalloc (amt);
5111   if (included == NULL)
5112     return FALSE;
5113
5114   symdefs = bfd_ardata (abfd)->symdefs;
5115   bed = get_elf_backend_data (abfd);
5116   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5117
5118   do
5119     {
5120       file_ptr last;
5121       symindex i;
5122       carsym *symdef;
5123       carsym *symdefend;
5124
5125       loop = FALSE;
5126       last = -1;
5127
5128       symdef = symdefs;
5129       symdefend = symdef + c;
5130       for (i = 0; symdef < symdefend; symdef++, i++)
5131         {
5132           struct elf_link_hash_entry *h;
5133           bfd *element;
5134           struct bfd_link_hash_entry *undefs_tail;
5135           symindex mark;
5136
5137           if (included[i])
5138             continue;
5139           if (symdef->file_offset == last)
5140             {
5141               included[i] = TRUE;
5142               continue;
5143             }
5144
5145           h = archive_symbol_lookup (abfd, info, symdef->name);
5146           if (h == (struct elf_link_hash_entry *) 0 - 1)
5147             goto error_return;
5148
5149           if (h == NULL)
5150             continue;
5151
5152           if (h->root.type == bfd_link_hash_common)
5153             {
5154               /* We currently have a common symbol.  The archive map contains
5155                  a reference to this symbol, so we may want to include it.  We
5156                  only want to include it however, if this archive element
5157                  contains a definition of the symbol, not just another common
5158                  declaration of it.
5159
5160                  Unfortunately some archivers (including GNU ar) will put
5161                  declarations of common symbols into their archive maps, as
5162                  well as real definitions, so we cannot just go by the archive
5163                  map alone.  Instead we must read in the element's symbol
5164                  table and check that to see what kind of symbol definition
5165                  this is.  */
5166               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5167                 continue;
5168             }
5169           else if (h->root.type != bfd_link_hash_undefined)
5170             {
5171               if (h->root.type != bfd_link_hash_undefweak)
5172                 /* Symbol must be defined.  Don't check it again.  */
5173                 included[i] = TRUE;
5174               continue;
5175             }
5176
5177           /* We need to include this archive member.  */
5178           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5179           if (element == NULL)
5180             goto error_return;
5181
5182           if (! bfd_check_format (element, bfd_object))
5183             goto error_return;
5184
5185           undefs_tail = info->hash->undefs_tail;
5186
5187           if (!(*info->callbacks
5188                 ->add_archive_element) (info, element, symdef->name, &element))
5189             goto error_return;
5190           if (!bfd_link_add_symbols (element, info))
5191             goto error_return;
5192
5193           /* If there are any new undefined symbols, we need to make
5194              another pass through the archive in order to see whether
5195              they can be defined.  FIXME: This isn't perfect, because
5196              common symbols wind up on undefs_tail and because an
5197              undefined symbol which is defined later on in this pass
5198              does not require another pass.  This isn't a bug, but it
5199              does make the code less efficient than it could be.  */
5200           if (undefs_tail != info->hash->undefs_tail)
5201             loop = TRUE;
5202
5203           /* Look backward to mark all symbols from this object file
5204              which we have already seen in this pass.  */
5205           mark = i;
5206           do
5207             {
5208               included[mark] = TRUE;
5209               if (mark == 0)
5210                 break;
5211               --mark;
5212             }
5213           while (symdefs[mark].file_offset == symdef->file_offset);
5214
5215           /* We mark subsequent symbols from this object file as we go
5216              on through the loop.  */
5217           last = symdef->file_offset;
5218         }
5219     }
5220   while (loop);
5221
5222   free (included);
5223
5224   return TRUE;
5225
5226  error_return:
5227   if (included != NULL)
5228     free (included);
5229   return FALSE;
5230 }
5231
5232 /* Given an ELF BFD, add symbols to the global hash table as
5233    appropriate.  */
5234
5235 bfd_boolean
5236 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5237 {
5238   switch (bfd_get_format (abfd))
5239     {
5240     case bfd_object:
5241       return elf_link_add_object_symbols (abfd, info);
5242     case bfd_archive:
5243       return elf_link_add_archive_symbols (abfd, info);
5244     default:
5245       bfd_set_error (bfd_error_wrong_format);
5246       return FALSE;
5247     }
5248 }
5249 \f
5250 struct hash_codes_info
5251 {
5252   unsigned long *hashcodes;
5253   bfd_boolean error;
5254 };
5255
5256 /* This function will be called though elf_link_hash_traverse to store
5257    all hash value of the exported symbols in an array.  */
5258
5259 static bfd_boolean
5260 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5261 {
5262   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5263   const char *name;
5264   unsigned long ha;
5265   char *alc = NULL;
5266
5267   /* Ignore indirect symbols.  These are added by the versioning code.  */
5268   if (h->dynindx == -1)
5269     return TRUE;
5270
5271   name = h->root.root.string;
5272   if (h->versioned >= versioned)
5273     {
5274       char *p = strchr (name, ELF_VER_CHR);
5275       if (p != NULL)
5276         {
5277           alc = (char *) bfd_malloc (p - name + 1);
5278           if (alc == NULL)
5279             {
5280               inf->error = TRUE;
5281               return FALSE;
5282             }
5283           memcpy (alc, name, p - name);
5284           alc[p - name] = '\0';
5285           name = alc;
5286         }
5287     }
5288
5289   /* Compute the hash value.  */
5290   ha = bfd_elf_hash (name);
5291
5292   /* Store the found hash value in the array given as the argument.  */
5293   *(inf->hashcodes)++ = ha;
5294
5295   /* And store it in the struct so that we can put it in the hash table
5296      later.  */
5297   h->u.elf_hash_value = ha;
5298
5299   if (alc != NULL)
5300     free (alc);
5301
5302   return TRUE;
5303 }
5304
5305 struct collect_gnu_hash_codes
5306 {
5307   bfd *output_bfd;
5308   const struct elf_backend_data *bed;
5309   unsigned long int nsyms;
5310   unsigned long int maskbits;
5311   unsigned long int *hashcodes;
5312   unsigned long int *hashval;
5313   unsigned long int *indx;
5314   unsigned long int *counts;
5315   bfd_vma *bitmask;
5316   bfd_byte *contents;
5317   long int min_dynindx;
5318   unsigned long int bucketcount;
5319   unsigned long int symindx;
5320   long int local_indx;
5321   long int shift1, shift2;
5322   unsigned long int mask;
5323   bfd_boolean error;
5324 };
5325
5326 /* This function will be called though elf_link_hash_traverse to store
5327    all hash value of the exported symbols in an array.  */
5328
5329 static bfd_boolean
5330 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5331 {
5332   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5333   const char *name;
5334   unsigned long ha;
5335   char *alc = NULL;
5336
5337   /* Ignore indirect symbols.  These are added by the versioning code.  */
5338   if (h->dynindx == -1)
5339     return TRUE;
5340
5341   /* Ignore also local symbols and undefined symbols.  */
5342   if (! (*s->bed->elf_hash_symbol) (h))
5343     return TRUE;
5344
5345   name = h->root.root.string;
5346   if (h->versioned >= versioned)
5347     {
5348       char *p = strchr (name, ELF_VER_CHR);
5349       if (p != NULL)
5350         {
5351           alc = (char *) bfd_malloc (p - name + 1);
5352           if (alc == NULL)
5353             {
5354               s->error = TRUE;
5355               return FALSE;
5356             }
5357           memcpy (alc, name, p - name);
5358           alc[p - name] = '\0';
5359           name = alc;
5360         }
5361     }
5362
5363   /* Compute the hash value.  */
5364   ha = bfd_elf_gnu_hash (name);
5365
5366   /* Store the found hash value in the array for compute_bucket_count,
5367      and also for .dynsym reordering purposes.  */
5368   s->hashcodes[s->nsyms] = ha;
5369   s->hashval[h->dynindx] = ha;
5370   ++s->nsyms;
5371   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5372     s->min_dynindx = h->dynindx;
5373
5374   if (alc != NULL)
5375     free (alc);
5376
5377   return TRUE;
5378 }
5379
5380 /* This function will be called though elf_link_hash_traverse to do
5381    final dynaminc symbol renumbering.  */
5382
5383 static bfd_boolean
5384 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5385 {
5386   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5387   unsigned long int bucket;
5388   unsigned long int val;
5389
5390   /* Ignore indirect symbols.  */
5391   if (h->dynindx == -1)
5392     return TRUE;
5393
5394   /* Ignore also local symbols and undefined symbols.  */
5395   if (! (*s->bed->elf_hash_symbol) (h))
5396     {
5397       if (h->dynindx >= s->min_dynindx)
5398         h->dynindx = s->local_indx++;
5399       return TRUE;
5400     }
5401
5402   bucket = s->hashval[h->dynindx] % s->bucketcount;
5403   val = (s->hashval[h->dynindx] >> s->shift1)
5404         & ((s->maskbits >> s->shift1) - 1);
5405   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5406   s->bitmask[val]
5407     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5408   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5409   if (s->counts[bucket] == 1)
5410     /* Last element terminates the chain.  */
5411     val |= 1;
5412   bfd_put_32 (s->output_bfd, val,
5413               s->contents + (s->indx[bucket] - s->symindx) * 4);
5414   --s->counts[bucket];
5415   h->dynindx = s->indx[bucket]++;
5416   return TRUE;
5417 }
5418
5419 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5420
5421 bfd_boolean
5422 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5423 {
5424   return !(h->forced_local
5425            || h->root.type == bfd_link_hash_undefined
5426            || h->root.type == bfd_link_hash_undefweak
5427            || ((h->root.type == bfd_link_hash_defined
5428                 || h->root.type == bfd_link_hash_defweak)
5429                && h->root.u.def.section->output_section == NULL));
5430 }
5431
5432 /* Array used to determine the number of hash table buckets to use
5433    based on the number of symbols there are.  If there are fewer than
5434    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5435    fewer than 37 we use 17 buckets, and so forth.  We never use more
5436    than 32771 buckets.  */
5437
5438 static const size_t elf_buckets[] =
5439 {
5440   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5441   16411, 32771, 0
5442 };
5443
5444 /* Compute bucket count for hashing table.  We do not use a static set
5445    of possible tables sizes anymore.  Instead we determine for all
5446    possible reasonable sizes of the table the outcome (i.e., the
5447    number of collisions etc) and choose the best solution.  The
5448    weighting functions are not too simple to allow the table to grow
5449    without bounds.  Instead one of the weighting factors is the size.
5450    Therefore the result is always a good payoff between few collisions
5451    (= short chain lengths) and table size.  */
5452 static size_t
5453 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5454                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5455                       unsigned long int nsyms,
5456                       int gnu_hash)
5457 {
5458   size_t best_size = 0;
5459   unsigned long int i;
5460
5461   /* We have a problem here.  The following code to optimize the table
5462      size requires an integer type with more the 32 bits.  If
5463      BFD_HOST_U_64_BIT is set we know about such a type.  */
5464 #ifdef BFD_HOST_U_64_BIT
5465   if (info->optimize)
5466     {
5467       size_t minsize;
5468       size_t maxsize;
5469       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5470       bfd *dynobj = elf_hash_table (info)->dynobj;
5471       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5472       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5473       unsigned long int *counts;
5474       bfd_size_type amt;
5475       unsigned int no_improvement_count = 0;
5476
5477       /* Possible optimization parameters: if we have NSYMS symbols we say
5478          that the hashing table must at least have NSYMS/4 and at most
5479          2*NSYMS buckets.  */
5480       minsize = nsyms / 4;
5481       if (minsize == 0)
5482         minsize = 1;
5483       best_size = maxsize = nsyms * 2;
5484       if (gnu_hash)
5485         {
5486           if (minsize < 2)
5487             minsize = 2;
5488           if ((best_size & 31) == 0)
5489             ++best_size;
5490         }
5491
5492       /* Create array where we count the collisions in.  We must use bfd_malloc
5493          since the size could be large.  */
5494       amt = maxsize;
5495       amt *= sizeof (unsigned long int);
5496       counts = (unsigned long int *) bfd_malloc (amt);
5497       if (counts == NULL)
5498         return 0;
5499
5500       /* Compute the "optimal" size for the hash table.  The criteria is a
5501          minimal chain length.  The minor criteria is (of course) the size
5502          of the table.  */
5503       for (i = minsize; i < maxsize; ++i)
5504         {
5505           /* Walk through the array of hashcodes and count the collisions.  */
5506           BFD_HOST_U_64_BIT max;
5507           unsigned long int j;
5508           unsigned long int fact;
5509
5510           if (gnu_hash && (i & 31) == 0)
5511             continue;
5512
5513           memset (counts, '\0', i * sizeof (unsigned long int));
5514
5515           /* Determine how often each hash bucket is used.  */
5516           for (j = 0; j < nsyms; ++j)
5517             ++counts[hashcodes[j] % i];
5518
5519           /* For the weight function we need some information about the
5520              pagesize on the target.  This is information need not be 100%
5521              accurate.  Since this information is not available (so far) we
5522              define it here to a reasonable default value.  If it is crucial
5523              to have a better value some day simply define this value.  */
5524 # ifndef BFD_TARGET_PAGESIZE
5525 #  define BFD_TARGET_PAGESIZE   (4096)
5526 # endif
5527
5528           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5529              and the chains.  */
5530           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5531
5532 # if 1
5533           /* Variant 1: optimize for short chains.  We add the squares
5534              of all the chain lengths (which favors many small chain
5535              over a few long chains).  */
5536           for (j = 0; j < i; ++j)
5537             max += counts[j] * counts[j];
5538
5539           /* This adds penalties for the overall size of the table.  */
5540           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5541           max *= fact * fact;
5542 # else
5543           /* Variant 2: Optimize a lot more for small table.  Here we
5544              also add squares of the size but we also add penalties for
5545              empty slots (the +1 term).  */
5546           for (j = 0; j < i; ++j)
5547             max += (1 + counts[j]) * (1 + counts[j]);
5548
5549           /* The overall size of the table is considered, but not as
5550              strong as in variant 1, where it is squared.  */
5551           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5552           max *= fact;
5553 # endif
5554
5555           /* Compare with current best results.  */
5556           if (max < best_chlen)
5557             {
5558               best_chlen = max;
5559               best_size = i;
5560               no_improvement_count = 0;
5561             }
5562           /* PR 11843: Avoid futile long searches for the best bucket size
5563              when there are a large number of symbols.  */
5564           else if (++no_improvement_count == 100)
5565             break;
5566         }
5567
5568       free (counts);
5569     }
5570   else
5571 #endif /* defined (BFD_HOST_U_64_BIT) */
5572     {
5573       /* This is the fallback solution if no 64bit type is available or if we
5574          are not supposed to spend much time on optimizations.  We select the
5575          bucket count using a fixed set of numbers.  */
5576       for (i = 0; elf_buckets[i] != 0; i++)
5577         {
5578           best_size = elf_buckets[i];
5579           if (nsyms < elf_buckets[i + 1])
5580             break;
5581         }
5582       if (gnu_hash && best_size < 2)
5583         best_size = 2;
5584     }
5585
5586   return best_size;
5587 }
5588
5589 /* Size any SHT_GROUP section for ld -r.  */
5590
5591 bfd_boolean
5592 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5593 {
5594   bfd *ibfd;
5595
5596   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5597     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5598         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5599       return FALSE;
5600   return TRUE;
5601 }
5602
5603 /* Set a default stack segment size.  The value in INFO wins.  If it
5604    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5605    undefined it is initialized.  */
5606
5607 bfd_boolean
5608 bfd_elf_stack_segment_size (bfd *output_bfd,
5609                             struct bfd_link_info *info,
5610                             const char *legacy_symbol,
5611                             bfd_vma default_size)
5612 {
5613   struct elf_link_hash_entry *h = NULL;
5614
5615   /* Look for legacy symbol.  */
5616   if (legacy_symbol)
5617     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5618                               FALSE, FALSE, FALSE);
5619   if (h && (h->root.type == bfd_link_hash_defined
5620             || h->root.type == bfd_link_hash_defweak)
5621       && h->def_regular
5622       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5623     {
5624       /* The symbol has no type if specified on the command line.  */
5625       h->type = STT_OBJECT;
5626       if (info->stacksize)
5627         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5628                                output_bfd, legacy_symbol);
5629       else if (h->root.u.def.section != bfd_abs_section_ptr)
5630         (*_bfd_error_handler) (_("%B: %s not absolute"),
5631                                output_bfd, legacy_symbol);
5632       else
5633         info->stacksize = h->root.u.def.value;
5634     }
5635
5636   if (!info->stacksize)
5637     /* If the user didn't set a size, or explicitly inhibit the
5638        size, set it now.  */
5639     info->stacksize = default_size;
5640
5641   /* Provide the legacy symbol, if it is referenced.  */
5642   if (h && (h->root.type == bfd_link_hash_undefined
5643             || h->root.type == bfd_link_hash_undefweak))
5644     {
5645       struct bfd_link_hash_entry *bh = NULL;
5646
5647       if (!(_bfd_generic_link_add_one_symbol
5648             (info, output_bfd, legacy_symbol,
5649              BSF_GLOBAL, bfd_abs_section_ptr,
5650              info->stacksize >= 0 ? info->stacksize : 0,
5651              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5652         return FALSE;
5653
5654       h = (struct elf_link_hash_entry *) bh;
5655       h->def_regular = 1;
5656       h->type = STT_OBJECT;
5657     }
5658
5659   return TRUE;
5660 }
5661
5662 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5663    called by the ELF linker emulation before_allocation routine.  We
5664    must set the sizes of the sections before the linker sets the
5665    addresses of the various sections.  */
5666
5667 bfd_boolean
5668 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5669                                const char *soname,
5670                                const char *rpath,
5671                                const char *filter_shlib,
5672                                const char *audit,
5673                                const char *depaudit,
5674                                const char * const *auxiliary_filters,
5675                                struct bfd_link_info *info,
5676                                asection **sinterpptr)
5677 {
5678   bfd_size_type soname_indx;
5679   bfd *dynobj;
5680   const struct elf_backend_data *bed;
5681   struct elf_info_failed asvinfo;
5682
5683   *sinterpptr = NULL;
5684
5685   soname_indx = (bfd_size_type) -1;
5686
5687   if (!is_elf_hash_table (info->hash))
5688     return TRUE;
5689
5690   bed = get_elf_backend_data (output_bfd);
5691
5692   /* Any syms created from now on start with -1 in
5693      got.refcount/offset and plt.refcount/offset.  */
5694   elf_hash_table (info)->init_got_refcount
5695     = elf_hash_table (info)->init_got_offset;
5696   elf_hash_table (info)->init_plt_refcount
5697     = elf_hash_table (info)->init_plt_offset;
5698
5699   if (info->relocatable
5700       && !_bfd_elf_size_group_sections (info))
5701     return FALSE;
5702
5703   /* The backend may have to create some sections regardless of whether
5704      we're dynamic or not.  */
5705   if (bed->elf_backend_always_size_sections
5706       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5707     return FALSE;
5708
5709   /* Determine any GNU_STACK segment requirements, after the backend
5710      has had a chance to set a default segment size.  */
5711   if (info->execstack)
5712     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5713   else if (info->noexecstack)
5714     elf_stack_flags (output_bfd) = PF_R | PF_W;
5715   else
5716     {
5717       bfd *inputobj;
5718       asection *notesec = NULL;
5719       int exec = 0;
5720
5721       for (inputobj = info->input_bfds;
5722            inputobj;
5723            inputobj = inputobj->link.next)
5724         {
5725           asection *s;
5726
5727           if (inputobj->flags
5728               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5729             continue;
5730           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5731           if (s)
5732             {
5733               if (s->flags & SEC_CODE)
5734                 exec = PF_X;
5735               notesec = s;
5736             }
5737           else if (bed->default_execstack)
5738             exec = PF_X;
5739         }
5740       if (notesec || info->stacksize > 0)
5741         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5742       if (notesec && exec && info->relocatable
5743           && notesec->output_section != bfd_abs_section_ptr)
5744         notesec->output_section->flags |= SEC_CODE;
5745     }
5746
5747   dynobj = elf_hash_table (info)->dynobj;
5748
5749   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5750     {
5751       struct elf_info_failed eif;
5752       struct elf_link_hash_entry *h;
5753       asection *dynstr;
5754       struct bfd_elf_version_tree *t;
5755       struct bfd_elf_version_expr *d;
5756       asection *s;
5757       bfd_boolean all_defined;
5758
5759       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5760       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5761
5762       if (soname != NULL)
5763         {
5764           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5765                                              soname, TRUE);
5766           if (soname_indx == (bfd_size_type) -1
5767               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5768             return FALSE;
5769         }
5770
5771       if (info->symbolic)
5772         {
5773           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5774             return FALSE;
5775           info->flags |= DF_SYMBOLIC;
5776         }
5777
5778       if (rpath != NULL)
5779         {
5780           bfd_size_type indx;
5781           bfd_vma tag;
5782
5783           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5784                                       TRUE);
5785           if (indx == (bfd_size_type) -1)
5786             return FALSE;
5787
5788           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5789           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5790             return FALSE;
5791         }
5792
5793       if (filter_shlib != NULL)
5794         {
5795           bfd_size_type indx;
5796
5797           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5798                                       filter_shlib, TRUE);
5799           if (indx == (bfd_size_type) -1
5800               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5801             return FALSE;
5802         }
5803
5804       if (auxiliary_filters != NULL)
5805         {
5806           const char * const *p;
5807
5808           for (p = auxiliary_filters; *p != NULL; p++)
5809             {
5810               bfd_size_type indx;
5811
5812               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5813                                           *p, TRUE);
5814               if (indx == (bfd_size_type) -1
5815                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5816                 return FALSE;
5817             }
5818         }
5819
5820       if (audit != NULL)
5821         {
5822           bfd_size_type indx;
5823
5824           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5825                                       TRUE);
5826           if (indx == (bfd_size_type) -1
5827               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5828             return FALSE;
5829         }
5830
5831       if (depaudit != NULL)
5832         {
5833           bfd_size_type indx;
5834
5835           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5836                                       TRUE);
5837           if (indx == (bfd_size_type) -1
5838               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5839             return FALSE;
5840         }
5841
5842       eif.info = info;
5843       eif.failed = FALSE;
5844
5845       /* If we are supposed to export all symbols into the dynamic symbol
5846          table (this is not the normal case), then do so.  */
5847       if (info->export_dynamic
5848           || (info->executable && info->dynamic))
5849         {
5850           elf_link_hash_traverse (elf_hash_table (info),
5851                                   _bfd_elf_export_symbol,
5852                                   &eif);
5853           if (eif.failed)
5854             return FALSE;
5855         }
5856
5857       /* Make all global versions with definition.  */
5858       for (t = info->version_info; t != NULL; t = t->next)
5859         for (d = t->globals.list; d != NULL; d = d->next)
5860           if (!d->symver && d->literal)
5861             {
5862               const char *verstr, *name;
5863               size_t namelen, verlen, newlen;
5864               char *newname, *p, leading_char;
5865               struct elf_link_hash_entry *newh;
5866
5867               leading_char = bfd_get_symbol_leading_char (output_bfd);
5868               name = d->pattern;
5869               namelen = strlen (name) + (leading_char != '\0');
5870               verstr = t->name;
5871               verlen = strlen (verstr);
5872               newlen = namelen + verlen + 3;
5873
5874               newname = (char *) bfd_malloc (newlen);
5875               if (newname == NULL)
5876                 return FALSE;
5877               newname[0] = leading_char;
5878               memcpy (newname + (leading_char != '\0'), name, namelen);
5879
5880               /* Check the hidden versioned definition.  */
5881               p = newname + namelen;
5882               *p++ = ELF_VER_CHR;
5883               memcpy (p, verstr, verlen + 1);
5884               newh = elf_link_hash_lookup (elf_hash_table (info),
5885                                            newname, FALSE, FALSE,
5886                                            FALSE);
5887               if (newh == NULL
5888                   || (newh->root.type != bfd_link_hash_defined
5889                       && newh->root.type != bfd_link_hash_defweak))
5890                 {
5891                   /* Check the default versioned definition.  */
5892                   *p++ = ELF_VER_CHR;
5893                   memcpy (p, verstr, verlen + 1);
5894                   newh = elf_link_hash_lookup (elf_hash_table (info),
5895                                                newname, FALSE, FALSE,
5896                                                FALSE);
5897                 }
5898               free (newname);
5899
5900               /* Mark this version if there is a definition and it is
5901                  not defined in a shared object.  */
5902               if (newh != NULL
5903                   && !newh->def_dynamic
5904                   && (newh->root.type == bfd_link_hash_defined
5905                       || newh->root.type == bfd_link_hash_defweak))
5906                 d->symver = 1;
5907             }
5908
5909       /* Attach all the symbols to their version information.  */
5910       asvinfo.info = info;
5911       asvinfo.failed = FALSE;
5912
5913       elf_link_hash_traverse (elf_hash_table (info),
5914                               _bfd_elf_link_assign_sym_version,
5915                               &asvinfo);
5916       if (asvinfo.failed)
5917         return FALSE;
5918
5919       if (!info->allow_undefined_version)
5920         {
5921           /* Check if all global versions have a definition.  */
5922           all_defined = TRUE;
5923           for (t = info->version_info; t != NULL; t = t->next)
5924             for (d = t->globals.list; d != NULL; d = d->next)
5925               if (d->literal && !d->symver && !d->script)
5926                 {
5927                   (*_bfd_error_handler)
5928                     (_("%s: undefined version: %s"),
5929                      d->pattern, t->name);
5930                   all_defined = FALSE;
5931                 }
5932
5933           if (!all_defined)
5934             {
5935               bfd_set_error (bfd_error_bad_value);
5936               return FALSE;
5937             }
5938         }
5939
5940       /* Find all symbols which were defined in a dynamic object and make
5941          the backend pick a reasonable value for them.  */
5942       elf_link_hash_traverse (elf_hash_table (info),
5943                               _bfd_elf_adjust_dynamic_symbol,
5944                               &eif);
5945       if (eif.failed)
5946         return FALSE;
5947
5948       /* Add some entries to the .dynamic section.  We fill in some of the
5949          values later, in bfd_elf_final_link, but we must add the entries
5950          now so that we know the final size of the .dynamic section.  */
5951
5952       /* If there are initialization and/or finalization functions to
5953          call then add the corresponding DT_INIT/DT_FINI entries.  */
5954       h = (info->init_function
5955            ? elf_link_hash_lookup (elf_hash_table (info),
5956                                    info->init_function, FALSE,
5957                                    FALSE, FALSE)
5958            : NULL);
5959       if (h != NULL
5960           && (h->ref_regular
5961               || h->def_regular))
5962         {
5963           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5964             return FALSE;
5965         }
5966       h = (info->fini_function
5967            ? elf_link_hash_lookup (elf_hash_table (info),
5968                                    info->fini_function, FALSE,
5969                                    FALSE, FALSE)
5970            : NULL);
5971       if (h != NULL
5972           && (h->ref_regular
5973               || h->def_regular))
5974         {
5975           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5976             return FALSE;
5977         }
5978
5979       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5980       if (s != NULL && s->linker_has_input)
5981         {
5982           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5983           if (! info->executable)
5984             {
5985               bfd *sub;
5986               asection *o;
5987
5988               for (sub = info->input_bfds; sub != NULL;
5989                    sub = sub->link.next)
5990                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5991                   for (o = sub->sections; o != NULL; o = o->next)
5992                     if (elf_section_data (o)->this_hdr.sh_type
5993                         == SHT_PREINIT_ARRAY)
5994                       {
5995                         (*_bfd_error_handler)
5996                           (_("%B: .preinit_array section is not allowed in DSO"),
5997                            sub);
5998                         break;
5999                       }
6000
6001               bfd_set_error (bfd_error_nonrepresentable_section);
6002               return FALSE;
6003             }
6004
6005           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6006               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6007             return FALSE;
6008         }
6009       s = bfd_get_section_by_name (output_bfd, ".init_array");
6010       if (s != NULL && s->linker_has_input)
6011         {
6012           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6013               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6014             return FALSE;
6015         }
6016       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6017       if (s != NULL && s->linker_has_input)
6018         {
6019           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6020               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6021             return FALSE;
6022         }
6023
6024       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6025       /* If .dynstr is excluded from the link, we don't want any of
6026          these tags.  Strictly, we should be checking each section
6027          individually;  This quick check covers for the case where
6028          someone does a /DISCARD/ : { *(*) }.  */
6029       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6030         {
6031           bfd_size_type strsize;
6032
6033           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6034           if ((info->emit_hash
6035                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6036               || (info->emit_gnu_hash
6037                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6038               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6039               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6040               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6041               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6042                                               bed->s->sizeof_sym))
6043             return FALSE;
6044         }
6045     }
6046
6047   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6048     return FALSE;
6049
6050   /* The backend must work out the sizes of all the other dynamic
6051      sections.  */
6052   if (dynobj != NULL
6053       && bed->elf_backend_size_dynamic_sections != NULL
6054       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6055     return FALSE;
6056
6057   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6058     {
6059       unsigned long section_sym_count;
6060       struct bfd_elf_version_tree *verdefs;
6061       asection *s;
6062
6063       /* Set up the version definition section.  */
6064       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6065       BFD_ASSERT (s != NULL);
6066
6067       /* We may have created additional version definitions if we are
6068          just linking a regular application.  */
6069       verdefs = info->version_info;
6070
6071       /* Skip anonymous version tag.  */
6072       if (verdefs != NULL && verdefs->vernum == 0)
6073         verdefs = verdefs->next;
6074
6075       if (verdefs == NULL && !info->create_default_symver)
6076         s->flags |= SEC_EXCLUDE;
6077       else
6078         {
6079           unsigned int cdefs;
6080           bfd_size_type size;
6081           struct bfd_elf_version_tree *t;
6082           bfd_byte *p;
6083           Elf_Internal_Verdef def;
6084           Elf_Internal_Verdaux defaux;
6085           struct bfd_link_hash_entry *bh;
6086           struct elf_link_hash_entry *h;
6087           const char *name;
6088
6089           cdefs = 0;
6090           size = 0;
6091
6092           /* Make space for the base version.  */
6093           size += sizeof (Elf_External_Verdef);
6094           size += sizeof (Elf_External_Verdaux);
6095           ++cdefs;
6096
6097           /* Make space for the default version.  */
6098           if (info->create_default_symver)
6099             {
6100               size += sizeof (Elf_External_Verdef);
6101               ++cdefs;
6102             }
6103
6104           for (t = verdefs; t != NULL; t = t->next)
6105             {
6106               struct bfd_elf_version_deps *n;
6107
6108               /* Don't emit base version twice.  */
6109               if (t->vernum == 0)
6110                 continue;
6111
6112               size += sizeof (Elf_External_Verdef);
6113               size += sizeof (Elf_External_Verdaux);
6114               ++cdefs;
6115
6116               for (n = t->deps; n != NULL; n = n->next)
6117                 size += sizeof (Elf_External_Verdaux);
6118             }
6119
6120           s->size = size;
6121           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6122           if (s->contents == NULL && s->size != 0)
6123             return FALSE;
6124
6125           /* Fill in the version definition section.  */
6126
6127           p = s->contents;
6128
6129           def.vd_version = VER_DEF_CURRENT;
6130           def.vd_flags = VER_FLG_BASE;
6131           def.vd_ndx = 1;
6132           def.vd_cnt = 1;
6133           if (info->create_default_symver)
6134             {
6135               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6136               def.vd_next = sizeof (Elf_External_Verdef);
6137             }
6138           else
6139             {
6140               def.vd_aux = sizeof (Elf_External_Verdef);
6141               def.vd_next = (sizeof (Elf_External_Verdef)
6142                              + sizeof (Elf_External_Verdaux));
6143             }
6144
6145           if (soname_indx != (bfd_size_type) -1)
6146             {
6147               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6148                                       soname_indx);
6149               def.vd_hash = bfd_elf_hash (soname);
6150               defaux.vda_name = soname_indx;
6151               name = soname;
6152             }
6153           else
6154             {
6155               bfd_size_type indx;
6156
6157               name = lbasename (output_bfd->filename);
6158               def.vd_hash = bfd_elf_hash (name);
6159               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6160                                           name, FALSE);
6161               if (indx == (bfd_size_type) -1)
6162                 return FALSE;
6163               defaux.vda_name = indx;
6164             }
6165           defaux.vda_next = 0;
6166
6167           _bfd_elf_swap_verdef_out (output_bfd, &def,
6168                                     (Elf_External_Verdef *) p);
6169           p += sizeof (Elf_External_Verdef);
6170           if (info->create_default_symver)
6171             {
6172               /* Add a symbol representing this version.  */
6173               bh = NULL;
6174               if (! (_bfd_generic_link_add_one_symbol
6175                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6176                       0, NULL, FALSE,
6177                       get_elf_backend_data (dynobj)->collect, &bh)))
6178                 return FALSE;
6179               h = (struct elf_link_hash_entry *) bh;
6180               h->non_elf = 0;
6181               h->def_regular = 1;
6182               h->type = STT_OBJECT;
6183               h->verinfo.vertree = NULL;
6184
6185               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6186                 return FALSE;
6187
6188               /* Create a duplicate of the base version with the same
6189                  aux block, but different flags.  */
6190               def.vd_flags = 0;
6191               def.vd_ndx = 2;
6192               def.vd_aux = sizeof (Elf_External_Verdef);
6193               if (verdefs)
6194                 def.vd_next = (sizeof (Elf_External_Verdef)
6195                                + sizeof (Elf_External_Verdaux));
6196               else
6197                 def.vd_next = 0;
6198               _bfd_elf_swap_verdef_out (output_bfd, &def,
6199                                         (Elf_External_Verdef *) p);
6200               p += sizeof (Elf_External_Verdef);
6201             }
6202           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6203                                      (Elf_External_Verdaux *) p);
6204           p += sizeof (Elf_External_Verdaux);
6205
6206           for (t = verdefs; t != NULL; t = t->next)
6207             {
6208               unsigned int cdeps;
6209               struct bfd_elf_version_deps *n;
6210
6211               /* Don't emit the base version twice.  */
6212               if (t->vernum == 0)
6213                 continue;
6214
6215               cdeps = 0;
6216               for (n = t->deps; n != NULL; n = n->next)
6217                 ++cdeps;
6218
6219               /* Add a symbol representing this version.  */
6220               bh = NULL;
6221               if (! (_bfd_generic_link_add_one_symbol
6222                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6223                       0, NULL, FALSE,
6224                       get_elf_backend_data (dynobj)->collect, &bh)))
6225                 return FALSE;
6226               h = (struct elf_link_hash_entry *) bh;
6227               h->non_elf = 0;
6228               h->def_regular = 1;
6229               h->type = STT_OBJECT;
6230               h->verinfo.vertree = t;
6231
6232               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6233                 return FALSE;
6234
6235               def.vd_version = VER_DEF_CURRENT;
6236               def.vd_flags = 0;
6237               if (t->globals.list == NULL
6238                   && t->locals.list == NULL
6239                   && ! t->used)
6240                 def.vd_flags |= VER_FLG_WEAK;
6241               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6242               def.vd_cnt = cdeps + 1;
6243               def.vd_hash = bfd_elf_hash (t->name);
6244               def.vd_aux = sizeof (Elf_External_Verdef);
6245               def.vd_next = 0;
6246
6247               /* If a basever node is next, it *must* be the last node in
6248                  the chain, otherwise Verdef construction breaks.  */
6249               if (t->next != NULL && t->next->vernum == 0)
6250                 BFD_ASSERT (t->next->next == NULL);
6251
6252               if (t->next != NULL && t->next->vernum != 0)
6253                 def.vd_next = (sizeof (Elf_External_Verdef)
6254                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6255
6256               _bfd_elf_swap_verdef_out (output_bfd, &def,
6257                                         (Elf_External_Verdef *) p);
6258               p += sizeof (Elf_External_Verdef);
6259
6260               defaux.vda_name = h->dynstr_index;
6261               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6262                                       h->dynstr_index);
6263               defaux.vda_next = 0;
6264               if (t->deps != NULL)
6265                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6266               t->name_indx = defaux.vda_name;
6267
6268               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6269                                          (Elf_External_Verdaux *) p);
6270               p += sizeof (Elf_External_Verdaux);
6271
6272               for (n = t->deps; n != NULL; n = n->next)
6273                 {
6274                   if (n->version_needed == NULL)
6275                     {
6276                       /* This can happen if there was an error in the
6277                          version script.  */
6278                       defaux.vda_name = 0;
6279                     }
6280                   else
6281                     {
6282                       defaux.vda_name = n->version_needed->name_indx;
6283                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6284                                               defaux.vda_name);
6285                     }
6286                   if (n->next == NULL)
6287                     defaux.vda_next = 0;
6288                   else
6289                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6290
6291                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6292                                              (Elf_External_Verdaux *) p);
6293                   p += sizeof (Elf_External_Verdaux);
6294                 }
6295             }
6296
6297           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6298               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6299             return FALSE;
6300
6301           elf_tdata (output_bfd)->cverdefs = cdefs;
6302         }
6303
6304       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6305         {
6306           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6307             return FALSE;
6308         }
6309       else if (info->flags & DF_BIND_NOW)
6310         {
6311           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6312             return FALSE;
6313         }
6314
6315       if (info->flags_1)
6316         {
6317           if (info->executable)
6318             info->flags_1 &= ~ (DF_1_INITFIRST
6319                                 | DF_1_NODELETE
6320                                 | DF_1_NOOPEN);
6321           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6322             return FALSE;
6323         }
6324
6325       /* Work out the size of the version reference section.  */
6326
6327       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6328       BFD_ASSERT (s != NULL);
6329       {
6330         struct elf_find_verdep_info sinfo;
6331
6332         sinfo.info = info;
6333         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6334         if (sinfo.vers == 0)
6335           sinfo.vers = 1;
6336         sinfo.failed = FALSE;
6337
6338         elf_link_hash_traverse (elf_hash_table (info),
6339                                 _bfd_elf_link_find_version_dependencies,
6340                                 &sinfo);
6341         if (sinfo.failed)
6342           return FALSE;
6343
6344         if (elf_tdata (output_bfd)->verref == NULL)
6345           s->flags |= SEC_EXCLUDE;
6346         else
6347           {
6348             Elf_Internal_Verneed *t;
6349             unsigned int size;
6350             unsigned int crefs;
6351             bfd_byte *p;
6352
6353             /* Build the version dependency section.  */
6354             size = 0;
6355             crefs = 0;
6356             for (t = elf_tdata (output_bfd)->verref;
6357                  t != NULL;
6358                  t = t->vn_nextref)
6359               {
6360                 Elf_Internal_Vernaux *a;
6361
6362                 size += sizeof (Elf_External_Verneed);
6363                 ++crefs;
6364                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6365                   size += sizeof (Elf_External_Vernaux);
6366               }
6367
6368             s->size = size;
6369             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6370             if (s->contents == NULL)
6371               return FALSE;
6372
6373             p = s->contents;
6374             for (t = elf_tdata (output_bfd)->verref;
6375                  t != NULL;
6376                  t = t->vn_nextref)
6377               {
6378                 unsigned int caux;
6379                 Elf_Internal_Vernaux *a;
6380                 bfd_size_type indx;
6381
6382                 caux = 0;
6383                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6384                   ++caux;
6385
6386                 t->vn_version = VER_NEED_CURRENT;
6387                 t->vn_cnt = caux;
6388                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6389                                             elf_dt_name (t->vn_bfd) != NULL
6390                                             ? elf_dt_name (t->vn_bfd)
6391                                             : lbasename (t->vn_bfd->filename),
6392                                             FALSE);
6393                 if (indx == (bfd_size_type) -1)
6394                   return FALSE;
6395                 t->vn_file = indx;
6396                 t->vn_aux = sizeof (Elf_External_Verneed);
6397                 if (t->vn_nextref == NULL)
6398                   t->vn_next = 0;
6399                 else
6400                   t->vn_next = (sizeof (Elf_External_Verneed)
6401                                 + caux * sizeof (Elf_External_Vernaux));
6402
6403                 _bfd_elf_swap_verneed_out (output_bfd, t,
6404                                            (Elf_External_Verneed *) p);
6405                 p += sizeof (Elf_External_Verneed);
6406
6407                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6408                   {
6409                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6410                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6411                                                 a->vna_nodename, FALSE);
6412                     if (indx == (bfd_size_type) -1)
6413                       return FALSE;
6414                     a->vna_name = indx;
6415                     if (a->vna_nextptr == NULL)
6416                       a->vna_next = 0;
6417                     else
6418                       a->vna_next = sizeof (Elf_External_Vernaux);
6419
6420                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6421                                                (Elf_External_Vernaux *) p);
6422                     p += sizeof (Elf_External_Vernaux);
6423                   }
6424               }
6425
6426             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6427                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6428               return FALSE;
6429
6430             elf_tdata (output_bfd)->cverrefs = crefs;
6431           }
6432       }
6433
6434       if ((elf_tdata (output_bfd)->cverrefs == 0
6435            && elf_tdata (output_bfd)->cverdefs == 0)
6436           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6437                                              &section_sym_count) == 0)
6438         {
6439           s = bfd_get_linker_section (dynobj, ".gnu.version");
6440           s->flags |= SEC_EXCLUDE;
6441         }
6442     }
6443   return TRUE;
6444 }
6445
6446 /* Find the first non-excluded output section.  We'll use its
6447    section symbol for some emitted relocs.  */
6448 void
6449 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6450 {
6451   asection *s;
6452
6453   for (s = output_bfd->sections; s != NULL; s = s->next)
6454     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6455         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6456       {
6457         elf_hash_table (info)->text_index_section = s;
6458         break;
6459       }
6460 }
6461
6462 /* Find two non-excluded output sections, one for code, one for data.
6463    We'll use their section symbols for some emitted relocs.  */
6464 void
6465 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6466 {
6467   asection *s;
6468
6469   /* Data first, since setting text_index_section changes
6470      _bfd_elf_link_omit_section_dynsym.  */
6471   for (s = output_bfd->sections; s != NULL; s = s->next)
6472     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6473         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6474       {
6475         elf_hash_table (info)->data_index_section = s;
6476         break;
6477       }
6478
6479   for (s = output_bfd->sections; s != NULL; s = s->next)
6480     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6481          == (SEC_ALLOC | SEC_READONLY))
6482         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6483       {
6484         elf_hash_table (info)->text_index_section = s;
6485         break;
6486       }
6487
6488   if (elf_hash_table (info)->text_index_section == NULL)
6489     elf_hash_table (info)->text_index_section
6490       = elf_hash_table (info)->data_index_section;
6491 }
6492
6493 bfd_boolean
6494 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6495 {
6496   const struct elf_backend_data *bed;
6497
6498   if (!is_elf_hash_table (info->hash))
6499     return TRUE;
6500
6501   bed = get_elf_backend_data (output_bfd);
6502   (*bed->elf_backend_init_index_section) (output_bfd, info);
6503
6504   if (elf_hash_table (info)->dynamic_sections_created)
6505     {
6506       bfd *dynobj;
6507       asection *s;
6508       bfd_size_type dynsymcount;
6509       unsigned long section_sym_count;
6510       unsigned int dtagcount;
6511
6512       dynobj = elf_hash_table (info)->dynobj;
6513
6514       /* Assign dynsym indicies.  In a shared library we generate a
6515          section symbol for each output section, which come first.
6516          Next come all of the back-end allocated local dynamic syms,
6517          followed by the rest of the global symbols.  */
6518
6519       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6520                                                     &section_sym_count);
6521
6522       /* Work out the size of the symbol version section.  */
6523       s = bfd_get_linker_section (dynobj, ".gnu.version");
6524       BFD_ASSERT (s != NULL);
6525       if (dynsymcount != 0
6526           && (s->flags & SEC_EXCLUDE) == 0)
6527         {
6528           s->size = dynsymcount * sizeof (Elf_External_Versym);
6529           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6530           if (s->contents == NULL)
6531             return FALSE;
6532
6533           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6534             return FALSE;
6535         }
6536
6537       /* Set the size of the .dynsym and .hash sections.  We counted
6538          the number of dynamic symbols in elf_link_add_object_symbols.
6539          We will build the contents of .dynsym and .hash when we build
6540          the final symbol table, because until then we do not know the
6541          correct value to give the symbols.  We built the .dynstr
6542          section as we went along in elf_link_add_object_symbols.  */
6543       s = bfd_get_linker_section (dynobj, ".dynsym");
6544       BFD_ASSERT (s != NULL);
6545       s->size = dynsymcount * bed->s->sizeof_sym;
6546
6547       if (dynsymcount != 0)
6548         {
6549           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6550           if (s->contents == NULL)
6551             return FALSE;
6552
6553           /* The first entry in .dynsym is a dummy symbol.
6554              Clear all the section syms, in case we don't output them all.  */
6555           ++section_sym_count;
6556           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6557         }
6558
6559       elf_hash_table (info)->bucketcount = 0;
6560
6561       /* Compute the size of the hashing table.  As a side effect this
6562          computes the hash values for all the names we export.  */
6563       if (info->emit_hash)
6564         {
6565           unsigned long int *hashcodes;
6566           struct hash_codes_info hashinf;
6567           bfd_size_type amt;
6568           unsigned long int nsyms;
6569           size_t bucketcount;
6570           size_t hash_entry_size;
6571
6572           /* Compute the hash values for all exported symbols.  At the same
6573              time store the values in an array so that we could use them for
6574              optimizations.  */
6575           amt = dynsymcount * sizeof (unsigned long int);
6576           hashcodes = (unsigned long int *) bfd_malloc (amt);
6577           if (hashcodes == NULL)
6578             return FALSE;
6579           hashinf.hashcodes = hashcodes;
6580           hashinf.error = FALSE;
6581
6582           /* Put all hash values in HASHCODES.  */
6583           elf_link_hash_traverse (elf_hash_table (info),
6584                                   elf_collect_hash_codes, &hashinf);
6585           if (hashinf.error)
6586             {
6587               free (hashcodes);
6588               return FALSE;
6589             }
6590
6591           nsyms = hashinf.hashcodes - hashcodes;
6592           bucketcount
6593             = compute_bucket_count (info, hashcodes, nsyms, 0);
6594           free (hashcodes);
6595
6596           if (bucketcount == 0)
6597             return FALSE;
6598
6599           elf_hash_table (info)->bucketcount = bucketcount;
6600
6601           s = bfd_get_linker_section (dynobj, ".hash");
6602           BFD_ASSERT (s != NULL);
6603           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6604           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6605           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6606           if (s->contents == NULL)
6607             return FALSE;
6608
6609           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6610           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6611                    s->contents + hash_entry_size);
6612         }
6613
6614       if (info->emit_gnu_hash)
6615         {
6616           size_t i, cnt;
6617           unsigned char *contents;
6618           struct collect_gnu_hash_codes cinfo;
6619           bfd_size_type amt;
6620           size_t bucketcount;
6621
6622           memset (&cinfo, 0, sizeof (cinfo));
6623
6624           /* Compute the hash values for all exported symbols.  At the same
6625              time store the values in an array so that we could use them for
6626              optimizations.  */
6627           amt = dynsymcount * 2 * sizeof (unsigned long int);
6628           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6629           if (cinfo.hashcodes == NULL)
6630             return FALSE;
6631
6632           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6633           cinfo.min_dynindx = -1;
6634           cinfo.output_bfd = output_bfd;
6635           cinfo.bed = bed;
6636
6637           /* Put all hash values in HASHCODES.  */
6638           elf_link_hash_traverse (elf_hash_table (info),
6639                                   elf_collect_gnu_hash_codes, &cinfo);
6640           if (cinfo.error)
6641             {
6642               free (cinfo.hashcodes);
6643               return FALSE;
6644             }
6645
6646           bucketcount
6647             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6648
6649           if (bucketcount == 0)
6650             {
6651               free (cinfo.hashcodes);
6652               return FALSE;
6653             }
6654
6655           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6656           BFD_ASSERT (s != NULL);
6657
6658           if (cinfo.nsyms == 0)
6659             {
6660               /* Empty .gnu.hash section is special.  */
6661               BFD_ASSERT (cinfo.min_dynindx == -1);
6662               free (cinfo.hashcodes);
6663               s->size = 5 * 4 + bed->s->arch_size / 8;
6664               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6665               if (contents == NULL)
6666                 return FALSE;
6667               s->contents = contents;
6668               /* 1 empty bucket.  */
6669               bfd_put_32 (output_bfd, 1, contents);
6670               /* SYMIDX above the special symbol 0.  */
6671               bfd_put_32 (output_bfd, 1, contents + 4);
6672               /* Just one word for bitmask.  */
6673               bfd_put_32 (output_bfd, 1, contents + 8);
6674               /* Only hash fn bloom filter.  */
6675               bfd_put_32 (output_bfd, 0, contents + 12);
6676               /* No hashes are valid - empty bitmask.  */
6677               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6678               /* No hashes in the only bucket.  */
6679               bfd_put_32 (output_bfd, 0,
6680                           contents + 16 + bed->s->arch_size / 8);
6681             }
6682           else
6683             {
6684               unsigned long int maskwords, maskbitslog2, x;
6685               BFD_ASSERT (cinfo.min_dynindx != -1);
6686
6687               x = cinfo.nsyms;
6688               maskbitslog2 = 1;
6689               while ((x >>= 1) != 0)
6690                 ++maskbitslog2;
6691               if (maskbitslog2 < 3)
6692                 maskbitslog2 = 5;
6693               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6694                 maskbitslog2 = maskbitslog2 + 3;
6695               else
6696                 maskbitslog2 = maskbitslog2 + 2;
6697               if (bed->s->arch_size == 64)
6698                 {
6699                   if (maskbitslog2 == 5)
6700                     maskbitslog2 = 6;
6701                   cinfo.shift1 = 6;
6702                 }
6703               else
6704                 cinfo.shift1 = 5;
6705               cinfo.mask = (1 << cinfo.shift1) - 1;
6706               cinfo.shift2 = maskbitslog2;
6707               cinfo.maskbits = 1 << maskbitslog2;
6708               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6709               amt = bucketcount * sizeof (unsigned long int) * 2;
6710               amt += maskwords * sizeof (bfd_vma);
6711               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6712               if (cinfo.bitmask == NULL)
6713                 {
6714                   free (cinfo.hashcodes);
6715                   return FALSE;
6716                 }
6717
6718               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6719               cinfo.indx = cinfo.counts + bucketcount;
6720               cinfo.symindx = dynsymcount - cinfo.nsyms;
6721               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6722
6723               /* Determine how often each hash bucket is used.  */
6724               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6725               for (i = 0; i < cinfo.nsyms; ++i)
6726                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6727
6728               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6729                 if (cinfo.counts[i] != 0)
6730                   {
6731                     cinfo.indx[i] = cnt;
6732                     cnt += cinfo.counts[i];
6733                   }
6734               BFD_ASSERT (cnt == dynsymcount);
6735               cinfo.bucketcount = bucketcount;
6736               cinfo.local_indx = cinfo.min_dynindx;
6737
6738               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6739               s->size += cinfo.maskbits / 8;
6740               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6741               if (contents == NULL)
6742                 {
6743                   free (cinfo.bitmask);
6744                   free (cinfo.hashcodes);
6745                   return FALSE;
6746                 }
6747
6748               s->contents = contents;
6749               bfd_put_32 (output_bfd, bucketcount, contents);
6750               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6751               bfd_put_32 (output_bfd, maskwords, contents + 8);
6752               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6753               contents += 16 + cinfo.maskbits / 8;
6754
6755               for (i = 0; i < bucketcount; ++i)
6756                 {
6757                   if (cinfo.counts[i] == 0)
6758                     bfd_put_32 (output_bfd, 0, contents);
6759                   else
6760                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6761                   contents += 4;
6762                 }
6763
6764               cinfo.contents = contents;
6765
6766               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6767               elf_link_hash_traverse (elf_hash_table (info),
6768                                       elf_renumber_gnu_hash_syms, &cinfo);
6769
6770               contents = s->contents + 16;
6771               for (i = 0; i < maskwords; ++i)
6772                 {
6773                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6774                            contents);
6775                   contents += bed->s->arch_size / 8;
6776                 }
6777
6778               free (cinfo.bitmask);
6779               free (cinfo.hashcodes);
6780             }
6781         }
6782
6783       s = bfd_get_linker_section (dynobj, ".dynstr");
6784       BFD_ASSERT (s != NULL);
6785
6786       elf_finalize_dynstr (output_bfd, info);
6787
6788       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6789
6790       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6791         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6792           return FALSE;
6793     }
6794
6795   return TRUE;
6796 }
6797 \f
6798 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6799
6800 static void
6801 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6802                             asection *sec)
6803 {
6804   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6805   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6806 }
6807
6808 /* Finish SHF_MERGE section merging.  */
6809
6810 bfd_boolean
6811 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6812 {
6813   bfd *ibfd;
6814   asection *sec;
6815
6816   if (!is_elf_hash_table (info->hash))
6817     return FALSE;
6818
6819   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6820     if ((ibfd->flags & DYNAMIC) == 0)
6821       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6822         if ((sec->flags & SEC_MERGE) != 0
6823             && !bfd_is_abs_section (sec->output_section))
6824           {
6825             struct bfd_elf_section_data *secdata;
6826
6827             secdata = elf_section_data (sec);
6828             if (! _bfd_add_merge_section (abfd,
6829                                           &elf_hash_table (info)->merge_info,
6830                                           sec, &secdata->sec_info))
6831               return FALSE;
6832             else if (secdata->sec_info)
6833               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6834           }
6835
6836   if (elf_hash_table (info)->merge_info != NULL)
6837     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6838                          merge_sections_remove_hook);
6839   return TRUE;
6840 }
6841
6842 /* Create an entry in an ELF linker hash table.  */
6843
6844 struct bfd_hash_entry *
6845 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6846                             struct bfd_hash_table *table,
6847                             const char *string)
6848 {
6849   /* Allocate the structure if it has not already been allocated by a
6850      subclass.  */
6851   if (entry == NULL)
6852     {
6853       entry = (struct bfd_hash_entry *)
6854         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6855       if (entry == NULL)
6856         return entry;
6857     }
6858
6859   /* Call the allocation method of the superclass.  */
6860   entry = _bfd_link_hash_newfunc (entry, table, string);
6861   if (entry != NULL)
6862     {
6863       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6864       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6865
6866       /* Set local fields.  */
6867       ret->indx = -1;
6868       ret->dynindx = -1;
6869       ret->got = htab->init_got_refcount;
6870       ret->plt = htab->init_plt_refcount;
6871       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6872                               - offsetof (struct elf_link_hash_entry, size)));
6873       /* Assume that we have been called by a non-ELF symbol reader.
6874          This flag is then reset by the code which reads an ELF input
6875          file.  This ensures that a symbol created by a non-ELF symbol
6876          reader will have the flag set correctly.  */
6877       ret->non_elf = 1;
6878     }
6879
6880   return entry;
6881 }
6882
6883 /* Copy data from an indirect symbol to its direct symbol, hiding the
6884    old indirect symbol.  Also used for copying flags to a weakdef.  */
6885
6886 void
6887 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6888                                   struct elf_link_hash_entry *dir,
6889                                   struct elf_link_hash_entry *ind)
6890 {
6891   struct elf_link_hash_table *htab;
6892
6893   /* Copy down any references that we may have already seen to the
6894      symbol which just became indirect if DIR isn't a hidden versioned
6895      symbol.  */
6896
6897   if (dir->versioned != versioned_hidden)
6898     {
6899       dir->ref_dynamic |= ind->ref_dynamic;
6900       dir->ref_regular |= ind->ref_regular;
6901       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6902       dir->non_got_ref |= ind->non_got_ref;
6903       dir->needs_plt |= ind->needs_plt;
6904       dir->pointer_equality_needed |= ind->pointer_equality_needed;
6905     }
6906
6907   if (ind->root.type != bfd_link_hash_indirect)
6908     return;
6909
6910   /* Copy over the global and procedure linkage table refcount entries.
6911      These may have been already set up by a check_relocs routine.  */
6912   htab = elf_hash_table (info);
6913   if (ind->got.refcount > htab->init_got_refcount.refcount)
6914     {
6915       if (dir->got.refcount < 0)
6916         dir->got.refcount = 0;
6917       dir->got.refcount += ind->got.refcount;
6918       ind->got.refcount = htab->init_got_refcount.refcount;
6919     }
6920
6921   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6922     {
6923       if (dir->plt.refcount < 0)
6924         dir->plt.refcount = 0;
6925       dir->plt.refcount += ind->plt.refcount;
6926       ind->plt.refcount = htab->init_plt_refcount.refcount;
6927     }
6928
6929   if (ind->dynindx != -1)
6930     {
6931       if (dir->dynindx != -1)
6932         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6933       dir->dynindx = ind->dynindx;
6934       dir->dynstr_index = ind->dynstr_index;
6935       ind->dynindx = -1;
6936       ind->dynstr_index = 0;
6937     }
6938 }
6939
6940 void
6941 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6942                                 struct elf_link_hash_entry *h,
6943                                 bfd_boolean force_local)
6944 {
6945   /* STT_GNU_IFUNC symbol must go through PLT.  */
6946   if (h->type != STT_GNU_IFUNC)
6947     {
6948       h->plt = elf_hash_table (info)->init_plt_offset;
6949       h->needs_plt = 0;
6950     }
6951   if (force_local)
6952     {
6953       h->forced_local = 1;
6954       if (h->dynindx != -1)
6955         {
6956           h->dynindx = -1;
6957           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6958                                   h->dynstr_index);
6959         }
6960     }
6961 }
6962
6963 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
6964    caller.  */
6965
6966 bfd_boolean
6967 _bfd_elf_link_hash_table_init
6968   (struct elf_link_hash_table *table,
6969    bfd *abfd,
6970    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6971                                       struct bfd_hash_table *,
6972                                       const char *),
6973    unsigned int entsize,
6974    enum elf_target_id target_id)
6975 {
6976   bfd_boolean ret;
6977   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6978
6979   table->init_got_refcount.refcount = can_refcount - 1;
6980   table->init_plt_refcount.refcount = can_refcount - 1;
6981   table->init_got_offset.offset = -(bfd_vma) 1;
6982   table->init_plt_offset.offset = -(bfd_vma) 1;
6983   /* The first dynamic symbol is a dummy.  */
6984   table->dynsymcount = 1;
6985
6986   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6987
6988   table->root.type = bfd_link_elf_hash_table;
6989   table->hash_table_id = target_id;
6990
6991   return ret;
6992 }
6993
6994 /* Create an ELF linker hash table.  */
6995
6996 struct bfd_link_hash_table *
6997 _bfd_elf_link_hash_table_create (bfd *abfd)
6998 {
6999   struct elf_link_hash_table *ret;
7000   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7001
7002   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7003   if (ret == NULL)
7004     return NULL;
7005
7006   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7007                                        sizeof (struct elf_link_hash_entry),
7008                                        GENERIC_ELF_DATA))
7009     {
7010       free (ret);
7011       return NULL;
7012     }
7013   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7014
7015   return &ret->root;
7016 }
7017
7018 /* Destroy an ELF linker hash table.  */
7019
7020 void
7021 _bfd_elf_link_hash_table_free (bfd *obfd)
7022 {
7023   struct elf_link_hash_table *htab;
7024
7025   htab = (struct elf_link_hash_table *) obfd->link.hash;
7026   if (htab->dynstr != NULL)
7027     _bfd_elf_strtab_free (htab->dynstr);
7028   _bfd_merge_sections_free (htab->merge_info);
7029   _bfd_generic_link_hash_table_free (obfd);
7030 }
7031
7032 /* This is a hook for the ELF emulation code in the generic linker to
7033    tell the backend linker what file name to use for the DT_NEEDED
7034    entry for a dynamic object.  */
7035
7036 void
7037 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7038 {
7039   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7040       && bfd_get_format (abfd) == bfd_object)
7041     elf_dt_name (abfd) = name;
7042 }
7043
7044 int
7045 bfd_elf_get_dyn_lib_class (bfd *abfd)
7046 {
7047   int lib_class;
7048   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7049       && bfd_get_format (abfd) == bfd_object)
7050     lib_class = elf_dyn_lib_class (abfd);
7051   else
7052     lib_class = 0;
7053   return lib_class;
7054 }
7055
7056 void
7057 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7058 {
7059   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7060       && bfd_get_format (abfd) == bfd_object)
7061     elf_dyn_lib_class (abfd) = lib_class;
7062 }
7063
7064 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7065    the linker ELF emulation code.  */
7066
7067 struct bfd_link_needed_list *
7068 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7069                          struct bfd_link_info *info)
7070 {
7071   if (! is_elf_hash_table (info->hash))
7072     return NULL;
7073   return elf_hash_table (info)->needed;
7074 }
7075
7076 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7077    hook for the linker ELF emulation code.  */
7078
7079 struct bfd_link_needed_list *
7080 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7081                           struct bfd_link_info *info)
7082 {
7083   if (! is_elf_hash_table (info->hash))
7084     return NULL;
7085   return elf_hash_table (info)->runpath;
7086 }
7087
7088 /* Get the name actually used for a dynamic object for a link.  This
7089    is the SONAME entry if there is one.  Otherwise, it is the string
7090    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7091
7092 const char *
7093 bfd_elf_get_dt_soname (bfd *abfd)
7094 {
7095   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7096       && bfd_get_format (abfd) == bfd_object)
7097     return elf_dt_name (abfd);
7098   return NULL;
7099 }
7100
7101 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7102    the ELF linker emulation code.  */
7103
7104 bfd_boolean
7105 bfd_elf_get_bfd_needed_list (bfd *abfd,
7106                              struct bfd_link_needed_list **pneeded)
7107 {
7108   asection *s;
7109   bfd_byte *dynbuf = NULL;
7110   unsigned int elfsec;
7111   unsigned long shlink;
7112   bfd_byte *extdyn, *extdynend;
7113   size_t extdynsize;
7114   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7115
7116   *pneeded = NULL;
7117
7118   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7119       || bfd_get_format (abfd) != bfd_object)
7120     return TRUE;
7121
7122   s = bfd_get_section_by_name (abfd, ".dynamic");
7123   if (s == NULL || s->size == 0)
7124     return TRUE;
7125
7126   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7127     goto error_return;
7128
7129   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7130   if (elfsec == SHN_BAD)
7131     goto error_return;
7132
7133   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7134
7135   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7136   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7137
7138   extdyn = dynbuf;
7139   extdynend = extdyn + s->size;
7140   for (; extdyn < extdynend; extdyn += extdynsize)
7141     {
7142       Elf_Internal_Dyn dyn;
7143
7144       (*swap_dyn_in) (abfd, extdyn, &dyn);
7145
7146       if (dyn.d_tag == DT_NULL)
7147         break;
7148
7149       if (dyn.d_tag == DT_NEEDED)
7150         {
7151           const char *string;
7152           struct bfd_link_needed_list *l;
7153           unsigned int tagv = dyn.d_un.d_val;
7154           bfd_size_type amt;
7155
7156           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7157           if (string == NULL)
7158             goto error_return;
7159
7160           amt = sizeof *l;
7161           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7162           if (l == NULL)
7163             goto error_return;
7164
7165           l->by = abfd;
7166           l->name = string;
7167           l->next = *pneeded;
7168           *pneeded = l;
7169         }
7170     }
7171
7172   free (dynbuf);
7173
7174   return TRUE;
7175
7176  error_return:
7177   if (dynbuf != NULL)
7178     free (dynbuf);
7179   return FALSE;
7180 }
7181
7182 struct elf_symbuf_symbol
7183 {
7184   unsigned long st_name;        /* Symbol name, index in string tbl */
7185   unsigned char st_info;        /* Type and binding attributes */
7186   unsigned char st_other;       /* Visibilty, and target specific */
7187 };
7188
7189 struct elf_symbuf_head
7190 {
7191   struct elf_symbuf_symbol *ssym;
7192   bfd_size_type count;
7193   unsigned int st_shndx;
7194 };
7195
7196 struct elf_symbol
7197 {
7198   union
7199     {
7200       Elf_Internal_Sym *isym;
7201       struct elf_symbuf_symbol *ssym;
7202     } u;
7203   const char *name;
7204 };
7205
7206 /* Sort references to symbols by ascending section number.  */
7207
7208 static int
7209 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7210 {
7211   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7212   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7213
7214   return s1->st_shndx - s2->st_shndx;
7215 }
7216
7217 static int
7218 elf_sym_name_compare (const void *arg1, const void *arg2)
7219 {
7220   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7221   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7222   return strcmp (s1->name, s2->name);
7223 }
7224
7225 static struct elf_symbuf_head *
7226 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7227 {
7228   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7229   struct elf_symbuf_symbol *ssym;
7230   struct elf_symbuf_head *ssymbuf, *ssymhead;
7231   bfd_size_type i, shndx_count, total_size;
7232
7233   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7234   if (indbuf == NULL)
7235     return NULL;
7236
7237   for (ind = indbuf, i = 0; i < symcount; i++)
7238     if (isymbuf[i].st_shndx != SHN_UNDEF)
7239       *ind++ = &isymbuf[i];
7240   indbufend = ind;
7241
7242   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7243          elf_sort_elf_symbol);
7244
7245   shndx_count = 0;
7246   if (indbufend > indbuf)
7247     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7248       if (ind[0]->st_shndx != ind[1]->st_shndx)
7249         shndx_count++;
7250
7251   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7252                 + (indbufend - indbuf) * sizeof (*ssym));
7253   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7254   if (ssymbuf == NULL)
7255     {
7256       free (indbuf);
7257       return NULL;
7258     }
7259
7260   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7261   ssymbuf->ssym = NULL;
7262   ssymbuf->count = shndx_count;
7263   ssymbuf->st_shndx = 0;
7264   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7265     {
7266       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7267         {
7268           ssymhead++;
7269           ssymhead->ssym = ssym;
7270           ssymhead->count = 0;
7271           ssymhead->st_shndx = (*ind)->st_shndx;
7272         }
7273       ssym->st_name = (*ind)->st_name;
7274       ssym->st_info = (*ind)->st_info;
7275       ssym->st_other = (*ind)->st_other;
7276       ssymhead->count++;
7277     }
7278   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7279               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7280                   == total_size));
7281
7282   free (indbuf);
7283   return ssymbuf;
7284 }
7285
7286 /* Check if 2 sections define the same set of local and global
7287    symbols.  */
7288
7289 static bfd_boolean
7290 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7291                                    struct bfd_link_info *info)
7292 {
7293   bfd *bfd1, *bfd2;
7294   const struct elf_backend_data *bed1, *bed2;
7295   Elf_Internal_Shdr *hdr1, *hdr2;
7296   bfd_size_type symcount1, symcount2;
7297   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7298   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7299   Elf_Internal_Sym *isym, *isymend;
7300   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7301   bfd_size_type count1, count2, i;
7302   unsigned int shndx1, shndx2;
7303   bfd_boolean result;
7304
7305   bfd1 = sec1->owner;
7306   bfd2 = sec2->owner;
7307
7308   /* Both sections have to be in ELF.  */
7309   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7310       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7311     return FALSE;
7312
7313   if (elf_section_type (sec1) != elf_section_type (sec2))
7314     return FALSE;
7315
7316   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7317   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7318   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7319     return FALSE;
7320
7321   bed1 = get_elf_backend_data (bfd1);
7322   bed2 = get_elf_backend_data (bfd2);
7323   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7324   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7325   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7326   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7327
7328   if (symcount1 == 0 || symcount2 == 0)
7329     return FALSE;
7330
7331   result = FALSE;
7332   isymbuf1 = NULL;
7333   isymbuf2 = NULL;
7334   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7335   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7336
7337   if (ssymbuf1 == NULL)
7338     {
7339       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7340                                        NULL, NULL, NULL);
7341       if (isymbuf1 == NULL)
7342         goto done;
7343
7344       if (!info->reduce_memory_overheads)
7345         elf_tdata (bfd1)->symbuf = ssymbuf1
7346           = elf_create_symbuf (symcount1, isymbuf1);
7347     }
7348
7349   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7350     {
7351       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7352                                        NULL, NULL, NULL);
7353       if (isymbuf2 == NULL)
7354         goto done;
7355
7356       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7357         elf_tdata (bfd2)->symbuf = ssymbuf2
7358           = elf_create_symbuf (symcount2, isymbuf2);
7359     }
7360
7361   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7362     {
7363       /* Optimized faster version.  */
7364       bfd_size_type lo, hi, mid;
7365       struct elf_symbol *symp;
7366       struct elf_symbuf_symbol *ssym, *ssymend;
7367
7368       lo = 0;
7369       hi = ssymbuf1->count;
7370       ssymbuf1++;
7371       count1 = 0;
7372       while (lo < hi)
7373         {
7374           mid = (lo + hi) / 2;
7375           if (shndx1 < ssymbuf1[mid].st_shndx)
7376             hi = mid;
7377           else if (shndx1 > ssymbuf1[mid].st_shndx)
7378             lo = mid + 1;
7379           else
7380             {
7381               count1 = ssymbuf1[mid].count;
7382               ssymbuf1 += mid;
7383               break;
7384             }
7385         }
7386
7387       lo = 0;
7388       hi = ssymbuf2->count;
7389       ssymbuf2++;
7390       count2 = 0;
7391       while (lo < hi)
7392         {
7393           mid = (lo + hi) / 2;
7394           if (shndx2 < ssymbuf2[mid].st_shndx)
7395             hi = mid;
7396           else if (shndx2 > ssymbuf2[mid].st_shndx)
7397             lo = mid + 1;
7398           else
7399             {
7400               count2 = ssymbuf2[mid].count;
7401               ssymbuf2 += mid;
7402               break;
7403             }
7404         }
7405
7406       if (count1 == 0 || count2 == 0 || count1 != count2)
7407         goto done;
7408
7409       symtable1
7410         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7411       symtable2
7412         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7413       if (symtable1 == NULL || symtable2 == NULL)
7414         goto done;
7415
7416       symp = symtable1;
7417       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7418            ssym < ssymend; ssym++, symp++)
7419         {
7420           symp->u.ssym = ssym;
7421           symp->name = bfd_elf_string_from_elf_section (bfd1,
7422                                                         hdr1->sh_link,
7423                                                         ssym->st_name);
7424         }
7425
7426       symp = symtable2;
7427       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7428            ssym < ssymend; ssym++, symp++)
7429         {
7430           symp->u.ssym = ssym;
7431           symp->name = bfd_elf_string_from_elf_section (bfd2,
7432                                                         hdr2->sh_link,
7433                                                         ssym->st_name);
7434         }
7435
7436       /* Sort symbol by name.  */
7437       qsort (symtable1, count1, sizeof (struct elf_symbol),
7438              elf_sym_name_compare);
7439       qsort (symtable2, count1, sizeof (struct elf_symbol),
7440              elf_sym_name_compare);
7441
7442       for (i = 0; i < count1; i++)
7443         /* Two symbols must have the same binding, type and name.  */
7444         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7445             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7446             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7447           goto done;
7448
7449       result = TRUE;
7450       goto done;
7451     }
7452
7453   symtable1 = (struct elf_symbol *)
7454       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7455   symtable2 = (struct elf_symbol *)
7456       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7457   if (symtable1 == NULL || symtable2 == NULL)
7458     goto done;
7459
7460   /* Count definitions in the section.  */
7461   count1 = 0;
7462   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7463     if (isym->st_shndx == shndx1)
7464       symtable1[count1++].u.isym = isym;
7465
7466   count2 = 0;
7467   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7468     if (isym->st_shndx == shndx2)
7469       symtable2[count2++].u.isym = isym;
7470
7471   if (count1 == 0 || count2 == 0 || count1 != count2)
7472     goto done;
7473
7474   for (i = 0; i < count1; i++)
7475     symtable1[i].name
7476       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7477                                          symtable1[i].u.isym->st_name);
7478
7479   for (i = 0; i < count2; i++)
7480     symtable2[i].name
7481       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7482                                          symtable2[i].u.isym->st_name);
7483
7484   /* Sort symbol by name.  */
7485   qsort (symtable1, count1, sizeof (struct elf_symbol),
7486          elf_sym_name_compare);
7487   qsort (symtable2, count1, sizeof (struct elf_symbol),
7488          elf_sym_name_compare);
7489
7490   for (i = 0; i < count1; i++)
7491     /* Two symbols must have the same binding, type and name.  */
7492     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7493         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7494         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7495       goto done;
7496
7497   result = TRUE;
7498
7499 done:
7500   if (symtable1)
7501     free (symtable1);
7502   if (symtable2)
7503     free (symtable2);
7504   if (isymbuf1)
7505     free (isymbuf1);
7506   if (isymbuf2)
7507     free (isymbuf2);
7508
7509   return result;
7510 }
7511
7512 /* Return TRUE if 2 section types are compatible.  */
7513
7514 bfd_boolean
7515 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7516                                  bfd *bbfd, const asection *bsec)
7517 {
7518   if (asec == NULL
7519       || bsec == NULL
7520       || abfd->xvec->flavour != bfd_target_elf_flavour
7521       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7522     return TRUE;
7523
7524   return elf_section_type (asec) == elf_section_type (bsec);
7525 }
7526 \f
7527 /* Final phase of ELF linker.  */
7528
7529 /* A structure we use to avoid passing large numbers of arguments.  */
7530
7531 struct elf_final_link_info
7532 {
7533   /* General link information.  */
7534   struct bfd_link_info *info;
7535   /* Output BFD.  */
7536   bfd *output_bfd;
7537   /* Symbol string table.  */
7538   struct elf_strtab_hash *symstrtab;
7539   /* .dynsym section.  */
7540   asection *dynsym_sec;
7541   /* .hash section.  */
7542   asection *hash_sec;
7543   /* symbol version section (.gnu.version).  */
7544   asection *symver_sec;
7545   /* Buffer large enough to hold contents of any section.  */
7546   bfd_byte *contents;
7547   /* Buffer large enough to hold external relocs of any section.  */
7548   void *external_relocs;
7549   /* Buffer large enough to hold internal relocs of any section.  */
7550   Elf_Internal_Rela *internal_relocs;
7551   /* Buffer large enough to hold external local symbols of any input
7552      BFD.  */
7553   bfd_byte *external_syms;
7554   /* And a buffer for symbol section indices.  */
7555   Elf_External_Sym_Shndx *locsym_shndx;
7556   /* Buffer large enough to hold internal local symbols of any input
7557      BFD.  */
7558   Elf_Internal_Sym *internal_syms;
7559   /* Array large enough to hold a symbol index for each local symbol
7560      of any input BFD.  */
7561   long *indices;
7562   /* Array large enough to hold a section pointer for each local
7563      symbol of any input BFD.  */
7564   asection **sections;
7565   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7566   Elf_External_Sym_Shndx *symshndxbuf;
7567   /* Number of STT_FILE syms seen.  */
7568   size_t filesym_count;
7569 };
7570
7571 /* This struct is used to pass information to elf_link_output_extsym.  */
7572
7573 struct elf_outext_info
7574 {
7575   bfd_boolean failed;
7576   bfd_boolean localsyms;
7577   bfd_boolean file_sym_done;
7578   struct elf_final_link_info *flinfo;
7579 };
7580
7581
7582 /* Support for evaluating a complex relocation.
7583
7584    Complex relocations are generalized, self-describing relocations.  The
7585    implementation of them consists of two parts: complex symbols, and the
7586    relocations themselves.
7587
7588    The relocations are use a reserved elf-wide relocation type code (R_RELC
7589    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7590    information (start bit, end bit, word width, etc) into the addend.  This
7591    information is extracted from CGEN-generated operand tables within gas.
7592
7593    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7594    internal) representing prefix-notation expressions, including but not
7595    limited to those sorts of expressions normally encoded as addends in the
7596    addend field.  The symbol mangling format is:
7597
7598    <node> := <literal>
7599           |  <unary-operator> ':' <node>
7600           |  <binary-operator> ':' <node> ':' <node>
7601           ;
7602
7603    <literal> := 's' <digits=N> ':' <N character symbol name>
7604              |  'S' <digits=N> ':' <N character section name>
7605              |  '#' <hexdigits>
7606              ;
7607
7608    <binary-operator> := as in C
7609    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7610
7611 static void
7612 set_symbol_value (bfd *bfd_with_globals,
7613                   Elf_Internal_Sym *isymbuf,
7614                   size_t locsymcount,
7615                   size_t symidx,
7616                   bfd_vma val)
7617 {
7618   struct elf_link_hash_entry **sym_hashes;
7619   struct elf_link_hash_entry *h;
7620   size_t extsymoff = locsymcount;
7621
7622   if (symidx < locsymcount)
7623     {
7624       Elf_Internal_Sym *sym;
7625
7626       sym = isymbuf + symidx;
7627       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7628         {
7629           /* It is a local symbol: move it to the
7630              "absolute" section and give it a value.  */
7631           sym->st_shndx = SHN_ABS;
7632           sym->st_value = val;
7633           return;
7634         }
7635       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7636       extsymoff = 0;
7637     }
7638
7639   /* It is a global symbol: set its link type
7640      to "defined" and give it a value.  */
7641
7642   sym_hashes = elf_sym_hashes (bfd_with_globals);
7643   h = sym_hashes [symidx - extsymoff];
7644   while (h->root.type == bfd_link_hash_indirect
7645          || h->root.type == bfd_link_hash_warning)
7646     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7647   h->root.type = bfd_link_hash_defined;
7648   h->root.u.def.value = val;
7649   h->root.u.def.section = bfd_abs_section_ptr;
7650 }
7651
7652 static bfd_boolean
7653 resolve_symbol (const char *name,
7654                 bfd *input_bfd,
7655                 struct elf_final_link_info *flinfo,
7656                 bfd_vma *result,
7657                 Elf_Internal_Sym *isymbuf,
7658                 size_t locsymcount)
7659 {
7660   Elf_Internal_Sym *sym;
7661   struct bfd_link_hash_entry *global_entry;
7662   const char *candidate = NULL;
7663   Elf_Internal_Shdr *symtab_hdr;
7664   size_t i;
7665
7666   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7667
7668   for (i = 0; i < locsymcount; ++ i)
7669     {
7670       sym = isymbuf + i;
7671
7672       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7673         continue;
7674
7675       candidate = bfd_elf_string_from_elf_section (input_bfd,
7676                                                    symtab_hdr->sh_link,
7677                                                    sym->st_name);
7678 #ifdef DEBUG
7679       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7680               name, candidate, (unsigned long) sym->st_value);
7681 #endif
7682       if (candidate && strcmp (candidate, name) == 0)
7683         {
7684           asection *sec = flinfo->sections [i];
7685
7686           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7687           *result += sec->output_offset + sec->output_section->vma;
7688 #ifdef DEBUG
7689           printf ("Found symbol with value %8.8lx\n",
7690                   (unsigned long) *result);
7691 #endif
7692           return TRUE;
7693         }
7694     }
7695
7696   /* Hmm, haven't found it yet. perhaps it is a global.  */
7697   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7698                                        FALSE, FALSE, TRUE);
7699   if (!global_entry)
7700     return FALSE;
7701
7702   if (global_entry->type == bfd_link_hash_defined
7703       || global_entry->type == bfd_link_hash_defweak)
7704     {
7705       *result = (global_entry->u.def.value
7706                  + global_entry->u.def.section->output_section->vma
7707                  + global_entry->u.def.section->output_offset);
7708 #ifdef DEBUG
7709       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7710               global_entry->root.string, (unsigned long) *result);
7711 #endif
7712       return TRUE;
7713     }
7714
7715   return FALSE;
7716 }
7717
7718 static bfd_boolean
7719 resolve_section (const char *name,
7720                  asection *sections,
7721                  bfd_vma *result)
7722 {
7723   asection *curr;
7724   unsigned int len;
7725
7726   for (curr = sections; curr; curr = curr->next)
7727     if (strcmp (curr->name, name) == 0)
7728       {
7729         *result = curr->vma;
7730         return TRUE;
7731       }
7732
7733   /* Hmm. still haven't found it. try pseudo-section names.  */
7734   for (curr = sections; curr; curr = curr->next)
7735     {
7736       len = strlen (curr->name);
7737       if (len > strlen (name))
7738         continue;
7739
7740       if (strncmp (curr->name, name, len) == 0)
7741         {
7742           if (strncmp (".end", name + len, 4) == 0)
7743             {
7744               *result = curr->vma + curr->size;
7745               return TRUE;
7746             }
7747
7748           /* Insert more pseudo-section names here, if you like.  */
7749         }
7750     }
7751
7752   return FALSE;
7753 }
7754
7755 static void
7756 undefined_reference (const char *reftype, const char *name)
7757 {
7758   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7759                       reftype, name);
7760 }
7761
7762 static bfd_boolean
7763 eval_symbol (bfd_vma *result,
7764              const char **symp,
7765              bfd *input_bfd,
7766              struct elf_final_link_info *flinfo,
7767              bfd_vma dot,
7768              Elf_Internal_Sym *isymbuf,
7769              size_t locsymcount,
7770              int signed_p)
7771 {
7772   size_t len;
7773   size_t symlen;
7774   bfd_vma a;
7775   bfd_vma b;
7776   char symbuf[4096];
7777   const char *sym = *symp;
7778   const char *symend;
7779   bfd_boolean symbol_is_section = FALSE;
7780
7781   len = strlen (sym);
7782   symend = sym + len;
7783
7784   if (len < 1 || len > sizeof (symbuf))
7785     {
7786       bfd_set_error (bfd_error_invalid_operation);
7787       return FALSE;
7788     }
7789
7790   switch (* sym)
7791     {
7792     case '.':
7793       *result = dot;
7794       *symp = sym + 1;
7795       return TRUE;
7796
7797     case '#':
7798       ++sym;
7799       *result = strtoul (sym, (char **) symp, 16);
7800       return TRUE;
7801
7802     case 'S':
7803       symbol_is_section = TRUE;
7804     case 's':
7805       ++sym;
7806       symlen = strtol (sym, (char **) symp, 10);
7807       sym = *symp + 1; /* Skip the trailing ':'.  */
7808
7809       if (symend < sym || symlen + 1 > sizeof (symbuf))
7810         {
7811           bfd_set_error (bfd_error_invalid_operation);
7812           return FALSE;
7813         }
7814
7815       memcpy (symbuf, sym, symlen);
7816       symbuf[symlen] = '\0';
7817       *symp = sym + symlen;
7818
7819       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7820          the symbol as a section, or vice-versa. so we're pretty liberal in our
7821          interpretation here; section means "try section first", not "must be a
7822          section", and likewise with symbol.  */
7823
7824       if (symbol_is_section)
7825         {
7826           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7827               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7828                                   isymbuf, locsymcount))
7829             {
7830               undefined_reference ("section", symbuf);
7831               return FALSE;
7832             }
7833         }
7834       else
7835         {
7836           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7837                                isymbuf, locsymcount)
7838               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7839                                    result))
7840             {
7841               undefined_reference ("symbol", symbuf);
7842               return FALSE;
7843             }
7844         }
7845
7846       return TRUE;
7847
7848       /* All that remains are operators.  */
7849
7850 #define UNARY_OP(op)                                            \
7851   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7852     {                                                           \
7853       sym += strlen (#op);                                      \
7854       if (*sym == ':')                                          \
7855         ++sym;                                                  \
7856       *symp = sym;                                              \
7857       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7858                         isymbuf, locsymcount, signed_p))        \
7859         return FALSE;                                           \
7860       if (signed_p)                                             \
7861         *result = op ((bfd_signed_vma) a);                      \
7862       else                                                      \
7863         *result = op a;                                         \
7864       return TRUE;                                              \
7865     }
7866
7867 #define BINARY_OP(op)                                           \
7868   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7869     {                                                           \
7870       sym += strlen (#op);                                      \
7871       if (*sym == ':')                                          \
7872         ++sym;                                                  \
7873       *symp = sym;                                              \
7874       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7875                         isymbuf, locsymcount, signed_p))        \
7876         return FALSE;                                           \
7877       ++*symp;                                                  \
7878       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7879                         isymbuf, locsymcount, signed_p))        \
7880         return FALSE;                                           \
7881       if (signed_p)                                             \
7882         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7883       else                                                      \
7884         *result = a op b;                                       \
7885       return TRUE;                                              \
7886     }
7887
7888     default:
7889       UNARY_OP  (0-);
7890       BINARY_OP (<<);
7891       BINARY_OP (>>);
7892       BINARY_OP (==);
7893       BINARY_OP (!=);
7894       BINARY_OP (<=);
7895       BINARY_OP (>=);
7896       BINARY_OP (&&);
7897       BINARY_OP (||);
7898       UNARY_OP  (~);
7899       UNARY_OP  (!);
7900       BINARY_OP (*);
7901       BINARY_OP (/);
7902       BINARY_OP (%);
7903       BINARY_OP (^);
7904       BINARY_OP (|);
7905       BINARY_OP (&);
7906       BINARY_OP (+);
7907       BINARY_OP (-);
7908       BINARY_OP (<);
7909       BINARY_OP (>);
7910 #undef UNARY_OP
7911 #undef BINARY_OP
7912       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7913       bfd_set_error (bfd_error_invalid_operation);
7914       return FALSE;
7915     }
7916 }
7917
7918 static void
7919 put_value (bfd_vma size,
7920            unsigned long chunksz,
7921            bfd *input_bfd,
7922            bfd_vma x,
7923            bfd_byte *location)
7924 {
7925   location += (size - chunksz);
7926
7927   for (; size; size -= chunksz, location -= chunksz)
7928     {
7929       switch (chunksz)
7930         {
7931         case 1:
7932           bfd_put_8 (input_bfd, x, location);
7933           x >>= 8;
7934           break;
7935         case 2:
7936           bfd_put_16 (input_bfd, x, location);
7937           x >>= 16;
7938           break;
7939         case 4:
7940           bfd_put_32 (input_bfd, x, location);
7941           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
7942           x >>= 16;
7943           x >>= 16;
7944           break;
7945 #ifdef BFD64
7946         case 8:
7947           bfd_put_64 (input_bfd, x, location);
7948           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
7949           x >>= 32;
7950           x >>= 32;
7951           break;
7952 #endif
7953         default:
7954           abort ();
7955           break;
7956         }
7957     }
7958 }
7959
7960 static bfd_vma
7961 get_value (bfd_vma size,
7962            unsigned long chunksz,
7963            bfd *input_bfd,
7964            bfd_byte *location)
7965 {
7966   int shift;
7967   bfd_vma x = 0;
7968
7969   /* Sanity checks.  */
7970   BFD_ASSERT (chunksz <= sizeof (x)
7971               && size >= chunksz
7972               && chunksz != 0
7973               && (size % chunksz) == 0
7974               && input_bfd != NULL
7975               && location != NULL);
7976
7977   if (chunksz == sizeof (x))
7978     {
7979       BFD_ASSERT (size == chunksz);
7980
7981       /* Make sure that we do not perform an undefined shift operation.
7982          We know that size == chunksz so there will only be one iteration
7983          of the loop below.  */
7984       shift = 0;
7985     }
7986   else
7987     shift = 8 * chunksz;
7988
7989   for (; size; size -= chunksz, location += chunksz)
7990     {
7991       switch (chunksz)
7992         {
7993         case 1:
7994           x = (x << shift) | bfd_get_8 (input_bfd, location);
7995           break;
7996         case 2:
7997           x = (x << shift) | bfd_get_16 (input_bfd, location);
7998           break;
7999         case 4:
8000           x = (x << shift) | bfd_get_32 (input_bfd, location);
8001           break;
8002 #ifdef BFD64
8003         case 8:
8004           x = (x << shift) | bfd_get_64 (input_bfd, location);
8005           break;
8006 #endif
8007         default:
8008           abort ();
8009         }
8010     }
8011   return x;
8012 }
8013
8014 static void
8015 decode_complex_addend (unsigned long *start,   /* in bits */
8016                        unsigned long *oplen,   /* in bits */
8017                        unsigned long *len,     /* in bits */
8018                        unsigned long *wordsz,  /* in bytes */
8019                        unsigned long *chunksz, /* in bytes */
8020                        unsigned long *lsb0_p,
8021                        unsigned long *signed_p,
8022                        unsigned long *trunc_p,
8023                        unsigned long encoded)
8024 {
8025   * start     =  encoded        & 0x3F;
8026   * len       = (encoded >>  6) & 0x3F;
8027   * oplen     = (encoded >> 12) & 0x3F;
8028   * wordsz    = (encoded >> 18) & 0xF;
8029   * chunksz   = (encoded >> 22) & 0xF;
8030   * lsb0_p    = (encoded >> 27) & 1;
8031   * signed_p  = (encoded >> 28) & 1;
8032   * trunc_p   = (encoded >> 29) & 1;
8033 }
8034
8035 bfd_reloc_status_type
8036 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8037                                     asection *input_section ATTRIBUTE_UNUSED,
8038                                     bfd_byte *contents,
8039                                     Elf_Internal_Rela *rel,
8040                                     bfd_vma relocation)
8041 {
8042   bfd_vma shift, x, mask;
8043   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8044   bfd_reloc_status_type r;
8045
8046   /*  Perform this reloc, since it is complex.
8047       (this is not to say that it necessarily refers to a complex
8048       symbol; merely that it is a self-describing CGEN based reloc.
8049       i.e. the addend has the complete reloc information (bit start, end,
8050       word size, etc) encoded within it.).  */
8051
8052   decode_complex_addend (&start, &oplen, &len, &wordsz,
8053                          &chunksz, &lsb0_p, &signed_p,
8054                          &trunc_p, rel->r_addend);
8055
8056   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8057
8058   if (lsb0_p)
8059     shift = (start + 1) - len;
8060   else
8061     shift = (8 * wordsz) - (start + len);
8062
8063   /* FIXME: octets_per_byte.  */
8064   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
8065
8066 #ifdef DEBUG
8067   printf ("Doing complex reloc: "
8068           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8069           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8070           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8071           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8072           oplen, (unsigned long) x, (unsigned long) mask,
8073           (unsigned long) relocation);
8074 #endif
8075
8076   r = bfd_reloc_ok;
8077   if (! trunc_p)
8078     /* Now do an overflow check.  */
8079     r = bfd_check_overflow ((signed_p
8080                              ? complain_overflow_signed
8081                              : complain_overflow_unsigned),
8082                             len, 0, (8 * wordsz),
8083                             relocation);
8084
8085   /* Do the deed.  */
8086   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8087
8088 #ifdef DEBUG
8089   printf ("           relocation: %8.8lx\n"
8090           "         shifted mask: %8.8lx\n"
8091           " shifted/masked reloc: %8.8lx\n"
8092           "               result: %8.8lx\n",
8093           (unsigned long) relocation, (unsigned long) (mask << shift),
8094           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8095 #endif
8096   /* FIXME: octets_per_byte.  */
8097   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
8098   return r;
8099 }
8100
8101 /* qsort comparison functions sorting external relocs by r_offset.  */
8102
8103 static int
8104 cmp_ext32l_r_offset (const void *p, const void *q)
8105 {
8106   union aligned32
8107   {
8108     uint32_t v;
8109     unsigned char c[4];
8110   };
8111   const union aligned32 *a
8112     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8113   const union aligned32 *b
8114     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8115
8116   uint32_t aval = (  (uint32_t) a->c[0]
8117                    | (uint32_t) a->c[1] << 8
8118                    | (uint32_t) a->c[2] << 16
8119                    | (uint32_t) a->c[3] << 24);
8120   uint32_t bval = (  (uint32_t) b->c[0]
8121                    | (uint32_t) b->c[1] << 8
8122                    | (uint32_t) b->c[2] << 16
8123                    | (uint32_t) b->c[3] << 24);
8124   if (aval < bval)
8125     return -1;
8126   else if (aval > bval)
8127     return 1;
8128   return 0;
8129 }
8130
8131 static int
8132 cmp_ext32b_r_offset (const void *p, const void *q)
8133 {
8134   union aligned32
8135   {
8136     uint32_t v;
8137     unsigned char c[4];
8138   };
8139   const union aligned32 *a
8140     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8141   const union aligned32 *b
8142     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8143
8144   uint32_t aval = (  (uint32_t) a->c[0] << 24
8145                    | (uint32_t) a->c[1] << 16
8146                    | (uint32_t) a->c[2] << 8
8147                    | (uint32_t) a->c[3]);
8148   uint32_t bval = (  (uint32_t) b->c[0] << 24
8149                    | (uint32_t) b->c[1] << 16
8150                    | (uint32_t) b->c[2] << 8
8151                    | (uint32_t) b->c[3]);
8152   if (aval < bval)
8153     return -1;
8154   else if (aval > bval)
8155     return 1;
8156   return 0;
8157 }
8158
8159 #ifdef BFD_HOST_64_BIT
8160 static int
8161 cmp_ext64l_r_offset (const void *p, const void *q)
8162 {
8163   union aligned64
8164   {
8165     uint64_t v;
8166     unsigned char c[8];
8167   };
8168   const union aligned64 *a
8169     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8170   const union aligned64 *b
8171     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8172
8173   uint64_t aval = (  (uint64_t) a->c[0]
8174                    | (uint64_t) a->c[1] << 8
8175                    | (uint64_t) a->c[2] << 16
8176                    | (uint64_t) a->c[3] << 24
8177                    | (uint64_t) a->c[4] << 32
8178                    | (uint64_t) a->c[5] << 40
8179                    | (uint64_t) a->c[6] << 48
8180                    | (uint64_t) a->c[7] << 56);
8181   uint64_t bval = (  (uint64_t) b->c[0]
8182                    | (uint64_t) b->c[1] << 8
8183                    | (uint64_t) b->c[2] << 16
8184                    | (uint64_t) b->c[3] << 24
8185                    | (uint64_t) b->c[4] << 32
8186                    | (uint64_t) b->c[5] << 40
8187                    | (uint64_t) b->c[6] << 48
8188                    | (uint64_t) b->c[7] << 56);
8189   if (aval < bval)
8190     return -1;
8191   else if (aval > bval)
8192     return 1;
8193   return 0;
8194 }
8195
8196 static int
8197 cmp_ext64b_r_offset (const void *p, const void *q)
8198 {
8199   union aligned64
8200   {
8201     uint64_t v;
8202     unsigned char c[8];
8203   };
8204   const union aligned64 *a
8205     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8206   const union aligned64 *b
8207     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8208
8209   uint64_t aval = (  (uint64_t) a->c[0] << 56
8210                    | (uint64_t) a->c[1] << 48
8211                    | (uint64_t) a->c[2] << 40
8212                    | (uint64_t) a->c[3] << 32
8213                    | (uint64_t) a->c[4] << 24
8214                    | (uint64_t) a->c[5] << 16
8215                    | (uint64_t) a->c[6] << 8
8216                    | (uint64_t) a->c[7]);
8217   uint64_t bval = (  (uint64_t) b->c[0] << 56
8218                    | (uint64_t) b->c[1] << 48
8219                    | (uint64_t) b->c[2] << 40
8220                    | (uint64_t) b->c[3] << 32
8221                    | (uint64_t) b->c[4] << 24
8222                    | (uint64_t) b->c[5] << 16
8223                    | (uint64_t) b->c[6] << 8
8224                    | (uint64_t) b->c[7]);
8225   if (aval < bval)
8226     return -1;
8227   else if (aval > bval)
8228     return 1;
8229   return 0;
8230 }
8231 #endif
8232
8233 /* When performing a relocatable link, the input relocations are
8234    preserved.  But, if they reference global symbols, the indices
8235    referenced must be updated.  Update all the relocations found in
8236    RELDATA.  */
8237
8238 static void
8239 elf_link_adjust_relocs (bfd *abfd,
8240                         struct bfd_elf_section_reloc_data *reldata,
8241                         bfd_boolean sort)
8242 {
8243   unsigned int i;
8244   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8245   bfd_byte *erela;
8246   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8247   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8248   bfd_vma r_type_mask;
8249   int r_sym_shift;
8250   unsigned int count = reldata->count;
8251   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8252
8253   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8254     {
8255       swap_in = bed->s->swap_reloc_in;
8256       swap_out = bed->s->swap_reloc_out;
8257     }
8258   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8259     {
8260       swap_in = bed->s->swap_reloca_in;
8261       swap_out = bed->s->swap_reloca_out;
8262     }
8263   else
8264     abort ();
8265
8266   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8267     abort ();
8268
8269   if (bed->s->arch_size == 32)
8270     {
8271       r_type_mask = 0xff;
8272       r_sym_shift = 8;
8273     }
8274   else
8275     {
8276       r_type_mask = 0xffffffff;
8277       r_sym_shift = 32;
8278     }
8279
8280   erela = reldata->hdr->contents;
8281   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8282     {
8283       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8284       unsigned int j;
8285
8286       if (*rel_hash == NULL)
8287         continue;
8288
8289       BFD_ASSERT ((*rel_hash)->indx >= 0);
8290
8291       (*swap_in) (abfd, erela, irela);
8292       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8293         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8294                            | (irela[j].r_info & r_type_mask));
8295       (*swap_out) (abfd, irela, erela);
8296     }
8297
8298   if (sort)
8299     {
8300       int (*compare) (const void *, const void *);
8301
8302       if (bed->s->arch_size == 32)
8303         {
8304           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8305             compare = cmp_ext32l_r_offset;
8306           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8307             compare = cmp_ext32b_r_offset;
8308           else
8309             abort ();
8310         }
8311       else
8312         {
8313 #ifdef BFD_HOST_64_BIT
8314           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8315             compare = cmp_ext64l_r_offset;
8316           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8317             compare = cmp_ext64b_r_offset;
8318           else
8319 #endif
8320             abort ();
8321         }
8322       qsort (reldata->hdr->contents, count, reldata->hdr->sh_entsize, compare);
8323       free (reldata->hashes);
8324       reldata->hashes = NULL;
8325     }
8326 }
8327
8328 struct elf_link_sort_rela
8329 {
8330   union {
8331     bfd_vma offset;
8332     bfd_vma sym_mask;
8333   } u;
8334   enum elf_reloc_type_class type;
8335   /* We use this as an array of size int_rels_per_ext_rel.  */
8336   Elf_Internal_Rela rela[1];
8337 };
8338
8339 static int
8340 elf_link_sort_cmp1 (const void *A, const void *B)
8341 {
8342   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8343   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8344   int relativea, relativeb;
8345
8346   relativea = a->type == reloc_class_relative;
8347   relativeb = b->type == reloc_class_relative;
8348
8349   if (relativea < relativeb)
8350     return 1;
8351   if (relativea > relativeb)
8352     return -1;
8353   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8354     return -1;
8355   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8356     return 1;
8357   if (a->rela->r_offset < b->rela->r_offset)
8358     return -1;
8359   if (a->rela->r_offset > b->rela->r_offset)
8360     return 1;
8361   return 0;
8362 }
8363
8364 static int
8365 elf_link_sort_cmp2 (const void *A, const void *B)
8366 {
8367   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8368   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8369
8370   if (a->type < b->type)
8371     return -1;
8372   if (a->type > b->type)
8373     return 1;
8374   if (a->u.offset < b->u.offset)
8375     return -1;
8376   if (a->u.offset > b->u.offset)
8377     return 1;
8378   if (a->rela->r_offset < b->rela->r_offset)
8379     return -1;
8380   if (a->rela->r_offset > b->rela->r_offset)
8381     return 1;
8382   return 0;
8383 }
8384
8385 static size_t
8386 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8387 {
8388   asection *dynamic_relocs;
8389   asection *rela_dyn;
8390   asection *rel_dyn;
8391   bfd_size_type count, size;
8392   size_t i, ret, sort_elt, ext_size;
8393   bfd_byte *sort, *s_non_relative, *p;
8394   struct elf_link_sort_rela *sq;
8395   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8396   int i2e = bed->s->int_rels_per_ext_rel;
8397   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8398   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8399   struct bfd_link_order *lo;
8400   bfd_vma r_sym_mask;
8401   bfd_boolean use_rela;
8402
8403   /* Find a dynamic reloc section.  */
8404   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8405   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8406   if (rela_dyn != NULL && rela_dyn->size > 0
8407       && rel_dyn != NULL && rel_dyn->size > 0)
8408     {
8409       bfd_boolean use_rela_initialised = FALSE;
8410
8411       /* This is just here to stop gcc from complaining.
8412          It's initialization checking code is not perfect.  */
8413       use_rela = TRUE;
8414
8415       /* Both sections are present.  Examine the sizes
8416          of the indirect sections to help us choose.  */
8417       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8418         if (lo->type == bfd_indirect_link_order)
8419           {
8420             asection *o = lo->u.indirect.section;
8421
8422             if ((o->size % bed->s->sizeof_rela) == 0)
8423               {
8424                 if ((o->size % bed->s->sizeof_rel) == 0)
8425                   /* Section size is divisible by both rel and rela sizes.
8426                      It is of no help to us.  */
8427                   ;
8428                 else
8429                   {
8430                     /* Section size is only divisible by rela.  */
8431                     if (use_rela_initialised && (use_rela == FALSE))
8432                       {
8433                         _bfd_error_handler
8434                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8435                         bfd_set_error (bfd_error_invalid_operation);
8436                         return 0;
8437                       }
8438                     else
8439                       {
8440                         use_rela = TRUE;
8441                         use_rela_initialised = TRUE;
8442                       }
8443                   }
8444               }
8445             else if ((o->size % bed->s->sizeof_rel) == 0)
8446               {
8447                 /* Section size is only divisible by rel.  */
8448                 if (use_rela_initialised && (use_rela == TRUE))
8449                   {
8450                     _bfd_error_handler
8451                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8452                     bfd_set_error (bfd_error_invalid_operation);
8453                     return 0;
8454                   }
8455                 else
8456                   {
8457                     use_rela = FALSE;
8458                     use_rela_initialised = TRUE;
8459                   }
8460               }
8461             else
8462               {
8463                 /* The section size is not divisible by either - something is wrong.  */
8464                 _bfd_error_handler
8465                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8466                 bfd_set_error (bfd_error_invalid_operation);
8467                 return 0;
8468               }
8469           }
8470
8471       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8472         if (lo->type == bfd_indirect_link_order)
8473           {
8474             asection *o = lo->u.indirect.section;
8475
8476             if ((o->size % bed->s->sizeof_rela) == 0)
8477               {
8478                 if ((o->size % bed->s->sizeof_rel) == 0)
8479                   /* Section size is divisible by both rel and rela sizes.
8480                      It is of no help to us.  */
8481                   ;
8482                 else
8483                   {
8484                     /* Section size is only divisible by rela.  */
8485                     if (use_rela_initialised && (use_rela == FALSE))
8486                       {
8487                         _bfd_error_handler
8488                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8489                         bfd_set_error (bfd_error_invalid_operation);
8490                         return 0;
8491                       }
8492                     else
8493                       {
8494                         use_rela = TRUE;
8495                         use_rela_initialised = TRUE;
8496                       }
8497                   }
8498               }
8499             else if ((o->size % bed->s->sizeof_rel) == 0)
8500               {
8501                 /* Section size is only divisible by rel.  */
8502                 if (use_rela_initialised && (use_rela == TRUE))
8503                   {
8504                     _bfd_error_handler
8505                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8506                     bfd_set_error (bfd_error_invalid_operation);
8507                     return 0;
8508                   }
8509                 else
8510                   {
8511                     use_rela = FALSE;
8512                     use_rela_initialised = TRUE;
8513                   }
8514               }
8515             else
8516               {
8517                 /* The section size is not divisible by either - something is wrong.  */
8518                 _bfd_error_handler
8519                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8520                 bfd_set_error (bfd_error_invalid_operation);
8521                 return 0;
8522               }
8523           }
8524
8525       if (! use_rela_initialised)
8526         /* Make a guess.  */
8527         use_rela = TRUE;
8528     }
8529   else if (rela_dyn != NULL && rela_dyn->size > 0)
8530     use_rela = TRUE;
8531   else if (rel_dyn != NULL && rel_dyn->size > 0)
8532     use_rela = FALSE;
8533   else
8534     return 0;
8535
8536   if (use_rela)
8537     {
8538       dynamic_relocs = rela_dyn;
8539       ext_size = bed->s->sizeof_rela;
8540       swap_in = bed->s->swap_reloca_in;
8541       swap_out = bed->s->swap_reloca_out;
8542     }
8543   else
8544     {
8545       dynamic_relocs = rel_dyn;
8546       ext_size = bed->s->sizeof_rel;
8547       swap_in = bed->s->swap_reloc_in;
8548       swap_out = bed->s->swap_reloc_out;
8549     }
8550
8551   size = 0;
8552   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8553     if (lo->type == bfd_indirect_link_order)
8554       size += lo->u.indirect.section->size;
8555
8556   if (size != dynamic_relocs->size)
8557     return 0;
8558
8559   sort_elt = (sizeof (struct elf_link_sort_rela)
8560               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8561
8562   count = dynamic_relocs->size / ext_size;
8563   if (count == 0)
8564     return 0;
8565   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8566
8567   if (sort == NULL)
8568     {
8569       (*info->callbacks->warning)
8570         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8571       return 0;
8572     }
8573
8574   if (bed->s->arch_size == 32)
8575     r_sym_mask = ~(bfd_vma) 0xff;
8576   else
8577     r_sym_mask = ~(bfd_vma) 0xffffffff;
8578
8579   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8580     if (lo->type == bfd_indirect_link_order)
8581       {
8582         bfd_byte *erel, *erelend;
8583         asection *o = lo->u.indirect.section;
8584
8585         if (o->contents == NULL && o->size != 0)
8586           {
8587             /* This is a reloc section that is being handled as a normal
8588                section.  See bfd_section_from_shdr.  We can't combine
8589                relocs in this case.  */
8590             free (sort);
8591             return 0;
8592           }
8593         erel = o->contents;
8594         erelend = o->contents + o->size;
8595         /* FIXME: octets_per_byte.  */
8596         p = sort + o->output_offset / ext_size * sort_elt;
8597
8598         while (erel < erelend)
8599           {
8600             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8601
8602             (*swap_in) (abfd, erel, s->rela);
8603             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8604             s->u.sym_mask = r_sym_mask;
8605             p += sort_elt;
8606             erel += ext_size;
8607           }
8608       }
8609
8610   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8611
8612   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8613     {
8614       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8615       if (s->type != reloc_class_relative)
8616         break;
8617     }
8618   ret = i;
8619   s_non_relative = p;
8620
8621   sq = (struct elf_link_sort_rela *) s_non_relative;
8622   for (; i < count; i++, p += sort_elt)
8623     {
8624       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8625       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8626         sq = sp;
8627       sp->u.offset = sq->rela->r_offset;
8628     }
8629
8630   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8631
8632   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8633     if (lo->type == bfd_indirect_link_order)
8634       {
8635         bfd_byte *erel, *erelend;
8636         asection *o = lo->u.indirect.section;
8637
8638         erel = o->contents;
8639         erelend = o->contents + o->size;
8640         /* FIXME: octets_per_byte.  */
8641         p = sort + o->output_offset / ext_size * sort_elt;
8642         while (erel < erelend)
8643           {
8644             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8645             (*swap_out) (abfd, s->rela, erel);
8646             p += sort_elt;
8647             erel += ext_size;
8648           }
8649       }
8650
8651   free (sort);
8652   *psec = dynamic_relocs;
8653   return ret;
8654 }
8655
8656 /* Add a symbol to the output symbol string table.  */
8657
8658 static int
8659 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8660                            const char *name,
8661                            Elf_Internal_Sym *elfsym,
8662                            asection *input_sec,
8663                            struct elf_link_hash_entry *h)
8664 {
8665   int (*output_symbol_hook)
8666     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8667      struct elf_link_hash_entry *);
8668   struct elf_link_hash_table *hash_table;
8669   const struct elf_backend_data *bed;
8670   bfd_size_type strtabsize;
8671
8672   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8673
8674   bed = get_elf_backend_data (flinfo->output_bfd);
8675   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8676   if (output_symbol_hook != NULL)
8677     {
8678       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8679       if (ret != 1)
8680         return ret;
8681     }
8682
8683   if (name == NULL
8684       || *name == '\0'
8685       || (input_sec->flags & SEC_EXCLUDE))
8686     elfsym->st_name = (unsigned long) -1;
8687   else
8688     {
8689       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8690          to get the final offset for st_name.  */
8691       elfsym->st_name
8692         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8693                                                name, FALSE);
8694       if (elfsym->st_name == (unsigned long) -1)
8695         return 0;
8696     }
8697
8698   hash_table = elf_hash_table (flinfo->info);
8699   strtabsize = hash_table->strtabsize;
8700   if (strtabsize <= hash_table->strtabcount)
8701     {
8702       strtabsize += strtabsize;
8703       hash_table->strtabsize = strtabsize;
8704       strtabsize *= sizeof (*hash_table->strtab);
8705       hash_table->strtab
8706         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8707                                                  strtabsize);
8708       if (hash_table->strtab == NULL)
8709         return 0;
8710     }
8711   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8712   hash_table->strtab[hash_table->strtabcount].dest_index
8713     = hash_table->strtabcount;
8714   hash_table->strtab[hash_table->strtabcount].destshndx_index
8715     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8716
8717   bfd_get_symcount (flinfo->output_bfd) += 1;
8718   hash_table->strtabcount += 1;
8719
8720   return 1;
8721 }
8722
8723 /* Swap symbols out to the symbol table and flush the output symbols to
8724    the file.  */
8725
8726 static bfd_boolean
8727 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8728 {
8729   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8730   bfd_size_type amt, i;
8731   const struct elf_backend_data *bed;
8732   bfd_byte *symbuf;
8733   Elf_Internal_Shdr *hdr;
8734   file_ptr pos;
8735   bfd_boolean ret;
8736
8737   if (!hash_table->strtabcount)
8738     return TRUE;
8739
8740   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8741
8742   bed = get_elf_backend_data (flinfo->output_bfd);
8743
8744   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8745   symbuf = (bfd_byte *) bfd_malloc (amt);
8746   if (symbuf == NULL)
8747     return FALSE;
8748
8749   if (flinfo->symshndxbuf)
8750     {
8751       amt = (sizeof (Elf_External_Sym_Shndx)
8752              * (bfd_get_symcount (flinfo->output_bfd)));
8753       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8754       if (flinfo->symshndxbuf == NULL)
8755         {
8756           free (symbuf);
8757           return FALSE;
8758         }
8759     }
8760
8761   for (i = 0; i < hash_table->strtabcount; i++)
8762     {
8763       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8764       if (elfsym->sym.st_name == (unsigned long) -1)
8765         elfsym->sym.st_name = 0;
8766       else
8767         elfsym->sym.st_name
8768           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8769                                                     elfsym->sym.st_name);
8770       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8771                                ((bfd_byte *) symbuf
8772                                 + (elfsym->dest_index
8773                                    * bed->s->sizeof_sym)),
8774                                (flinfo->symshndxbuf
8775                                 + elfsym->destshndx_index));
8776     }
8777
8778   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8779   pos = hdr->sh_offset + hdr->sh_size;
8780   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8781   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8782       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8783     {
8784       hdr->sh_size += amt;
8785       ret = TRUE;
8786     }
8787   else
8788     ret = FALSE;
8789
8790   free (symbuf);
8791
8792   free (hash_table->strtab);
8793   hash_table->strtab = NULL;
8794
8795   return ret;
8796 }
8797
8798 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8799
8800 static bfd_boolean
8801 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8802 {
8803   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8804       && sym->st_shndx < SHN_LORESERVE)
8805     {
8806       /* The gABI doesn't support dynamic symbols in output sections
8807          beyond 64k.  */
8808       (*_bfd_error_handler)
8809         (_("%B: Too many sections: %d (>= %d)"),
8810          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8811       bfd_set_error (bfd_error_nonrepresentable_section);
8812       return FALSE;
8813     }
8814   return TRUE;
8815 }
8816
8817 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8818    allowing an unsatisfied unversioned symbol in the DSO to match a
8819    versioned symbol that would normally require an explicit version.
8820    We also handle the case that a DSO references a hidden symbol
8821    which may be satisfied by a versioned symbol in another DSO.  */
8822
8823 static bfd_boolean
8824 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8825                                  const struct elf_backend_data *bed,
8826                                  struct elf_link_hash_entry *h)
8827 {
8828   bfd *abfd;
8829   struct elf_link_loaded_list *loaded;
8830
8831   if (!is_elf_hash_table (info->hash))
8832     return FALSE;
8833
8834   /* Check indirect symbol.  */
8835   while (h->root.type == bfd_link_hash_indirect)
8836     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8837
8838   switch (h->root.type)
8839     {
8840     default:
8841       abfd = NULL;
8842       break;
8843
8844     case bfd_link_hash_undefined:
8845     case bfd_link_hash_undefweak:
8846       abfd = h->root.u.undef.abfd;
8847       if ((abfd->flags & DYNAMIC) == 0
8848           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8849         return FALSE;
8850       break;
8851
8852     case bfd_link_hash_defined:
8853     case bfd_link_hash_defweak:
8854       abfd = h->root.u.def.section->owner;
8855       break;
8856
8857     case bfd_link_hash_common:
8858       abfd = h->root.u.c.p->section->owner;
8859       break;
8860     }
8861   BFD_ASSERT (abfd != NULL);
8862
8863   for (loaded = elf_hash_table (info)->loaded;
8864        loaded != NULL;
8865        loaded = loaded->next)
8866     {
8867       bfd *input;
8868       Elf_Internal_Shdr *hdr;
8869       bfd_size_type symcount;
8870       bfd_size_type extsymcount;
8871       bfd_size_type extsymoff;
8872       Elf_Internal_Shdr *versymhdr;
8873       Elf_Internal_Sym *isym;
8874       Elf_Internal_Sym *isymend;
8875       Elf_Internal_Sym *isymbuf;
8876       Elf_External_Versym *ever;
8877       Elf_External_Versym *extversym;
8878
8879       input = loaded->abfd;
8880
8881       /* We check each DSO for a possible hidden versioned definition.  */
8882       if (input == abfd
8883           || (input->flags & DYNAMIC) == 0
8884           || elf_dynversym (input) == 0)
8885         continue;
8886
8887       hdr = &elf_tdata (input)->dynsymtab_hdr;
8888
8889       symcount = hdr->sh_size / bed->s->sizeof_sym;
8890       if (elf_bad_symtab (input))
8891         {
8892           extsymcount = symcount;
8893           extsymoff = 0;
8894         }
8895       else
8896         {
8897           extsymcount = symcount - hdr->sh_info;
8898           extsymoff = hdr->sh_info;
8899         }
8900
8901       if (extsymcount == 0)
8902         continue;
8903
8904       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8905                                       NULL, NULL, NULL);
8906       if (isymbuf == NULL)
8907         return FALSE;
8908
8909       /* Read in any version definitions.  */
8910       versymhdr = &elf_tdata (input)->dynversym_hdr;
8911       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8912       if (extversym == NULL)
8913         goto error_ret;
8914
8915       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8916           || (bfd_bread (extversym, versymhdr->sh_size, input)
8917               != versymhdr->sh_size))
8918         {
8919           free (extversym);
8920         error_ret:
8921           free (isymbuf);
8922           return FALSE;
8923         }
8924
8925       ever = extversym + extsymoff;
8926       isymend = isymbuf + extsymcount;
8927       for (isym = isymbuf; isym < isymend; isym++, ever++)
8928         {
8929           const char *name;
8930           Elf_Internal_Versym iver;
8931           unsigned short version_index;
8932
8933           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8934               || isym->st_shndx == SHN_UNDEF)
8935             continue;
8936
8937           name = bfd_elf_string_from_elf_section (input,
8938                                                   hdr->sh_link,
8939                                                   isym->st_name);
8940           if (strcmp (name, h->root.root.string) != 0)
8941             continue;
8942
8943           _bfd_elf_swap_versym_in (input, ever, &iver);
8944
8945           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8946               && !(h->def_regular
8947                    && h->forced_local))
8948             {
8949               /* If we have a non-hidden versioned sym, then it should
8950                  have provided a definition for the undefined sym unless
8951                  it is defined in a non-shared object and forced local.
8952                */
8953               abort ();
8954             }
8955
8956           version_index = iver.vs_vers & VERSYM_VERSION;
8957           if (version_index == 1 || version_index == 2)
8958             {
8959               /* This is the base or first version.  We can use it.  */
8960               free (extversym);
8961               free (isymbuf);
8962               return TRUE;
8963             }
8964         }
8965
8966       free (extversym);
8967       free (isymbuf);
8968     }
8969
8970   return FALSE;
8971 }
8972
8973 /* Add an external symbol to the symbol table.  This is called from
8974    the hash table traversal routine.  When generating a shared object,
8975    we go through the symbol table twice.  The first time we output
8976    anything that might have been forced to local scope in a version
8977    script.  The second time we output the symbols that are still
8978    global symbols.  */
8979
8980 static bfd_boolean
8981 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8982 {
8983   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8984   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8985   struct elf_final_link_info *flinfo = eoinfo->flinfo;
8986   bfd_boolean strip;
8987   Elf_Internal_Sym sym;
8988   asection *input_sec;
8989   const struct elf_backend_data *bed;
8990   long indx;
8991   int ret;
8992   /* A symbol is bound locally if it is forced local or it is locally
8993      defined, hidden versioned, not referenced by shared library and
8994      not exported when linking executable.  */
8995   bfd_boolean local_bind = (h->forced_local
8996                             || (flinfo->info->executable
8997                                 && !flinfo->info->export_dynamic
8998                                 && !h->dynamic
8999                                 && !h->ref_dynamic
9000                                 && h->def_regular
9001                                 && h->versioned == versioned_hidden));
9002
9003   if (h->root.type == bfd_link_hash_warning)
9004     {
9005       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9006       if (h->root.type == bfd_link_hash_new)
9007         return TRUE;
9008     }
9009
9010   /* Decide whether to output this symbol in this pass.  */
9011   if (eoinfo->localsyms)
9012     {
9013       if (!local_bind)
9014         return TRUE;
9015     }
9016   else
9017     {
9018       if (local_bind)
9019         return TRUE;
9020     }
9021
9022   bed = get_elf_backend_data (flinfo->output_bfd);
9023
9024   if (h->root.type == bfd_link_hash_undefined)
9025     {
9026       /* If we have an undefined symbol reference here then it must have
9027          come from a shared library that is being linked in.  (Undefined
9028          references in regular files have already been handled unless
9029          they are in unreferenced sections which are removed by garbage
9030          collection).  */
9031       bfd_boolean ignore_undef = FALSE;
9032
9033       /* Some symbols may be special in that the fact that they're
9034          undefined can be safely ignored - let backend determine that.  */
9035       if (bed->elf_backend_ignore_undef_symbol)
9036         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9037
9038       /* If we are reporting errors for this situation then do so now.  */
9039       if (!ignore_undef
9040           && h->ref_dynamic
9041           && (!h->ref_regular || flinfo->info->gc_sections)
9042           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9043           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9044         {
9045           if (!(flinfo->info->callbacks->undefined_symbol
9046                 (flinfo->info, h->root.root.string,
9047                  h->ref_regular ? NULL : h->root.u.undef.abfd,
9048                  NULL, 0,
9049                  (flinfo->info->unresolved_syms_in_shared_libs
9050                   == RM_GENERATE_ERROR))))
9051             {
9052               bfd_set_error (bfd_error_bad_value);
9053               eoinfo->failed = TRUE;
9054               return FALSE;
9055             }
9056         }
9057     }
9058
9059   /* We should also warn if a forced local symbol is referenced from
9060      shared libraries.  */
9061   if (flinfo->info->executable
9062       && h->forced_local
9063       && h->ref_dynamic
9064       && h->def_regular
9065       && !h->dynamic_def
9066       && h->ref_dynamic_nonweak
9067       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9068     {
9069       bfd *def_bfd;
9070       const char *msg;
9071       struct elf_link_hash_entry *hi = h;
9072
9073       /* Check indirect symbol.  */
9074       while (hi->root.type == bfd_link_hash_indirect)
9075         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9076
9077       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9078         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9079       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9080         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9081       else
9082         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9083       def_bfd = flinfo->output_bfd;
9084       if (hi->root.u.def.section != bfd_abs_section_ptr)
9085         def_bfd = hi->root.u.def.section->owner;
9086       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9087                              h->root.root.string);
9088       bfd_set_error (bfd_error_bad_value);
9089       eoinfo->failed = TRUE;
9090       return FALSE;
9091     }
9092
9093   /* We don't want to output symbols that have never been mentioned by
9094      a regular file, or that we have been told to strip.  However, if
9095      h->indx is set to -2, the symbol is used by a reloc and we must
9096      output it.  */
9097   strip = FALSE;
9098   if (h->indx == -2)
9099     ;
9100   else if ((h->def_dynamic
9101             || h->ref_dynamic
9102             || h->root.type == bfd_link_hash_new)
9103            && !h->def_regular
9104            && !h->ref_regular)
9105     strip = TRUE;
9106   else if (flinfo->info->strip == strip_all)
9107     strip = TRUE;
9108   else if (flinfo->info->strip == strip_some
9109            && bfd_hash_lookup (flinfo->info->keep_hash,
9110                                h->root.root.string, FALSE, FALSE) == NULL)
9111     strip = TRUE;
9112   else if ((h->root.type == bfd_link_hash_defined
9113             || h->root.type == bfd_link_hash_defweak)
9114            && ((flinfo->info->strip_discarded
9115                 && discarded_section (h->root.u.def.section))
9116                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9117                    && h->root.u.def.section->owner != NULL
9118                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9119     strip = TRUE;
9120   else if ((h->root.type == bfd_link_hash_undefined
9121             || h->root.type == bfd_link_hash_undefweak)
9122            && h->root.u.undef.abfd != NULL
9123            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9124     strip = TRUE;
9125
9126   /* If we're stripping it, and it's not a dynamic symbol, there's
9127      nothing else to do.   However, if it is a forced local symbol or
9128      an ifunc symbol we need to give the backend finish_dynamic_symbol
9129      function a chance to make it dynamic.  */
9130   if (strip
9131       && h->dynindx == -1
9132       && h->type != STT_GNU_IFUNC
9133       && !h->forced_local)
9134     return TRUE;
9135
9136   sym.st_value = 0;
9137   sym.st_size = h->size;
9138   sym.st_other = h->other;
9139   if (local_bind)
9140     {
9141       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
9142       /* Turn off visibility on local symbol.  */
9143       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9144     }
9145   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9146   else if (h->unique_global && h->def_regular)
9147     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
9148   else if (h->root.type == bfd_link_hash_undefweak
9149            || h->root.type == bfd_link_hash_defweak)
9150     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
9151   else
9152     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
9153   sym.st_target_internal = h->target_internal;
9154
9155   switch (h->root.type)
9156     {
9157     default:
9158     case bfd_link_hash_new:
9159     case bfd_link_hash_warning:
9160       abort ();
9161       return FALSE;
9162
9163     case bfd_link_hash_undefined:
9164     case bfd_link_hash_undefweak:
9165       input_sec = bfd_und_section_ptr;
9166       sym.st_shndx = SHN_UNDEF;
9167       break;
9168
9169     case bfd_link_hash_defined:
9170     case bfd_link_hash_defweak:
9171       {
9172         input_sec = h->root.u.def.section;
9173         if (input_sec->output_section != NULL)
9174           {
9175             sym.st_shndx =
9176               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9177                                                  input_sec->output_section);
9178             if (sym.st_shndx == SHN_BAD)
9179               {
9180                 (*_bfd_error_handler)
9181                   (_("%B: could not find output section %A for input section %A"),
9182                    flinfo->output_bfd, input_sec->output_section, input_sec);
9183                 bfd_set_error (bfd_error_nonrepresentable_section);
9184                 eoinfo->failed = TRUE;
9185                 return FALSE;
9186               }
9187
9188             /* ELF symbols in relocatable files are section relative,
9189                but in nonrelocatable files they are virtual
9190                addresses.  */
9191             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9192             if (!flinfo->info->relocatable)
9193               {
9194                 sym.st_value += input_sec->output_section->vma;
9195                 if (h->type == STT_TLS)
9196                   {
9197                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9198                     if (tls_sec != NULL)
9199                       sym.st_value -= tls_sec->vma;
9200                   }
9201               }
9202           }
9203         else
9204           {
9205             BFD_ASSERT (input_sec->owner == NULL
9206                         || (input_sec->owner->flags & DYNAMIC) != 0);
9207             sym.st_shndx = SHN_UNDEF;
9208             input_sec = bfd_und_section_ptr;
9209           }
9210       }
9211       break;
9212
9213     case bfd_link_hash_common:
9214       input_sec = h->root.u.c.p->section;
9215       sym.st_shndx = bed->common_section_index (input_sec);
9216       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9217       break;
9218
9219     case bfd_link_hash_indirect:
9220       /* These symbols are created by symbol versioning.  They point
9221          to the decorated version of the name.  For example, if the
9222          symbol foo@@GNU_1.2 is the default, which should be used when
9223          foo is used with no version, then we add an indirect symbol
9224          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9225          since the indirected symbol is already in the hash table.  */
9226       return TRUE;
9227     }
9228
9229   /* Give the processor backend a chance to tweak the symbol value,
9230      and also to finish up anything that needs to be done for this
9231      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9232      forced local syms when non-shared is due to a historical quirk.
9233      STT_GNU_IFUNC symbol must go through PLT.  */
9234   if ((h->type == STT_GNU_IFUNC
9235        && h->def_regular
9236        && !flinfo->info->relocatable)
9237       || ((h->dynindx != -1
9238            || h->forced_local)
9239           && ((flinfo->info->shared
9240                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9241                    || h->root.type != bfd_link_hash_undefweak))
9242               || !h->forced_local)
9243           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9244     {
9245       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9246              (flinfo->output_bfd, flinfo->info, h, &sym)))
9247         {
9248           eoinfo->failed = TRUE;
9249           return FALSE;
9250         }
9251     }
9252
9253   /* If we are marking the symbol as undefined, and there are no
9254      non-weak references to this symbol from a regular object, then
9255      mark the symbol as weak undefined; if there are non-weak
9256      references, mark the symbol as strong.  We can't do this earlier,
9257      because it might not be marked as undefined until the
9258      finish_dynamic_symbol routine gets through with it.  */
9259   if (sym.st_shndx == SHN_UNDEF
9260       && h->ref_regular
9261       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9262           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9263     {
9264       int bindtype;
9265       unsigned int type = ELF_ST_TYPE (sym.st_info);
9266
9267       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9268       if (type == STT_GNU_IFUNC)
9269         type = STT_FUNC;
9270
9271       if (h->ref_regular_nonweak)
9272         bindtype = STB_GLOBAL;
9273       else
9274         bindtype = STB_WEAK;
9275       sym.st_info = ELF_ST_INFO (bindtype, type);
9276     }
9277
9278   /* If this is a symbol defined in a dynamic library, don't use the
9279      symbol size from the dynamic library.  Relinking an executable
9280      against a new library may introduce gratuitous changes in the
9281      executable's symbols if we keep the size.  */
9282   if (sym.st_shndx == SHN_UNDEF
9283       && !h->def_regular
9284       && h->def_dynamic)
9285     sym.st_size = 0;
9286
9287   /* If a non-weak symbol with non-default visibility is not defined
9288      locally, it is a fatal error.  */
9289   if (!flinfo->info->relocatable
9290       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9291       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9292       && h->root.type == bfd_link_hash_undefined
9293       && !h->def_regular)
9294     {
9295       const char *msg;
9296
9297       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9298         msg = _("%B: protected symbol `%s' isn't defined");
9299       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9300         msg = _("%B: internal symbol `%s' isn't defined");
9301       else
9302         msg = _("%B: hidden symbol `%s' isn't defined");
9303       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9304       bfd_set_error (bfd_error_bad_value);
9305       eoinfo->failed = TRUE;
9306       return FALSE;
9307     }
9308
9309   /* If this symbol should be put in the .dynsym section, then put it
9310      there now.  We already know the symbol index.  We also fill in
9311      the entry in the .hash section.  */
9312   if (flinfo->dynsym_sec != NULL
9313       && h->dynindx != -1
9314       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9315     {
9316       bfd_byte *esym;
9317
9318       /* Since there is no version information in the dynamic string,
9319          if there is no version info in symbol version section, we will
9320          have a run-time problem if not linking executable, referenced
9321          by shared library, not locally defined, or not bound locally.
9322       */
9323       if (h->verinfo.verdef == NULL
9324           && !local_bind
9325           && (!flinfo->info->executable
9326               || h->ref_dynamic
9327               || !h->def_regular))
9328         {
9329           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9330
9331           if (p && p [1] != '\0')
9332             {
9333               (*_bfd_error_handler)
9334                 (_("%B: No symbol version section for versioned symbol `%s'"),
9335                  flinfo->output_bfd, h->root.root.string);
9336               eoinfo->failed = TRUE;
9337               return FALSE;
9338             }
9339         }
9340
9341       sym.st_name = h->dynstr_index;
9342       esym = flinfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
9343       if (!check_dynsym (flinfo->output_bfd, &sym))
9344         {
9345           eoinfo->failed = TRUE;
9346           return FALSE;
9347         }
9348       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9349
9350       if (flinfo->hash_sec != NULL)
9351         {
9352           size_t hash_entry_size;
9353           bfd_byte *bucketpos;
9354           bfd_vma chain;
9355           size_t bucketcount;
9356           size_t bucket;
9357
9358           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9359           bucket = h->u.elf_hash_value % bucketcount;
9360
9361           hash_entry_size
9362             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9363           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9364                        + (bucket + 2) * hash_entry_size);
9365           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9366           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9367                    bucketpos);
9368           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9369                    ((bfd_byte *) flinfo->hash_sec->contents
9370                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9371         }
9372
9373       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9374         {
9375           Elf_Internal_Versym iversym;
9376           Elf_External_Versym *eversym;
9377
9378           if (!h->def_regular)
9379             {
9380               if (h->verinfo.verdef == NULL
9381                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9382                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9383                 iversym.vs_vers = 0;
9384               else
9385                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9386             }
9387           else
9388             {
9389               if (h->verinfo.vertree == NULL)
9390                 iversym.vs_vers = 1;
9391               else
9392                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9393               if (flinfo->info->create_default_symver)
9394                 iversym.vs_vers++;
9395             }
9396
9397           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9398              defined locally.  */
9399           if (h->versioned == versioned_hidden && h->def_regular)
9400             iversym.vs_vers |= VERSYM_HIDDEN;
9401
9402           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9403           eversym += h->dynindx;
9404           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9405         }
9406     }
9407
9408   /* If the symbol is undefined, and we didn't output it to .dynsym,
9409      strip it from .symtab too.  Obviously we can't do this for
9410      relocatable output or when needed for --emit-relocs.  */
9411   else if (input_sec == bfd_und_section_ptr
9412            && h->indx != -2
9413            && !flinfo->info->relocatable)
9414     return TRUE;
9415   /* Also strip others that we couldn't earlier due to dynamic symbol
9416      processing.  */
9417   if (strip)
9418     return TRUE;
9419   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9420     return TRUE;
9421
9422   /* Output a FILE symbol so that following locals are not associated
9423      with the wrong input file.  We need one for forced local symbols
9424      if we've seen more than one FILE symbol or when we have exactly
9425      one FILE symbol but global symbols are present in a file other
9426      than the one with the FILE symbol.  We also need one if linker
9427      defined symbols are present.  In practice these conditions are
9428      always met, so just emit the FILE symbol unconditionally.  */
9429   if (eoinfo->localsyms
9430       && !eoinfo->file_sym_done
9431       && eoinfo->flinfo->filesym_count != 0)
9432     {
9433       Elf_Internal_Sym fsym;
9434
9435       memset (&fsym, 0, sizeof (fsym));
9436       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9437       fsym.st_shndx = SHN_ABS;
9438       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9439                                       bfd_und_section_ptr, NULL))
9440         return FALSE;
9441
9442       eoinfo->file_sym_done = TRUE;
9443     }
9444
9445   indx = bfd_get_symcount (flinfo->output_bfd);
9446   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9447                                    input_sec, h);
9448   if (ret == 0)
9449     {
9450       eoinfo->failed = TRUE;
9451       return FALSE;
9452     }
9453   else if (ret == 1)
9454     h->indx = indx;
9455   else if (h->indx == -2)
9456     abort();
9457
9458   return TRUE;
9459 }
9460
9461 /* Return TRUE if special handling is done for relocs in SEC against
9462    symbols defined in discarded sections.  */
9463
9464 static bfd_boolean
9465 elf_section_ignore_discarded_relocs (asection *sec)
9466 {
9467   const struct elf_backend_data *bed;
9468
9469   switch (sec->sec_info_type)
9470     {
9471     case SEC_INFO_TYPE_STABS:
9472     case SEC_INFO_TYPE_EH_FRAME:
9473     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9474       return TRUE;
9475     default:
9476       break;
9477     }
9478
9479   bed = get_elf_backend_data (sec->owner);
9480   if (bed->elf_backend_ignore_discarded_relocs != NULL
9481       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9482     return TRUE;
9483
9484   return FALSE;
9485 }
9486
9487 /* Return a mask saying how ld should treat relocations in SEC against
9488    symbols defined in discarded sections.  If this function returns
9489    COMPLAIN set, ld will issue a warning message.  If this function
9490    returns PRETEND set, and the discarded section was link-once and the
9491    same size as the kept link-once section, ld will pretend that the
9492    symbol was actually defined in the kept section.  Otherwise ld will
9493    zero the reloc (at least that is the intent, but some cooperation by
9494    the target dependent code is needed, particularly for REL targets).  */
9495
9496 unsigned int
9497 _bfd_elf_default_action_discarded (asection *sec)
9498 {
9499   if (sec->flags & SEC_DEBUGGING)
9500     return PRETEND;
9501
9502   if (strcmp (".eh_frame", sec->name) == 0)
9503     return 0;
9504
9505   if (strcmp (".gcc_except_table", sec->name) == 0)
9506     return 0;
9507
9508   return COMPLAIN | PRETEND;
9509 }
9510
9511 /* Find a match between a section and a member of a section group.  */
9512
9513 static asection *
9514 match_group_member (asection *sec, asection *group,
9515                     struct bfd_link_info *info)
9516 {
9517   asection *first = elf_next_in_group (group);
9518   asection *s = first;
9519
9520   while (s != NULL)
9521     {
9522       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9523         return s;
9524
9525       s = elf_next_in_group (s);
9526       if (s == first)
9527         break;
9528     }
9529
9530   return NULL;
9531 }
9532
9533 /* Check if the kept section of a discarded section SEC can be used
9534    to replace it.  Return the replacement if it is OK.  Otherwise return
9535    NULL.  */
9536
9537 asection *
9538 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9539 {
9540   asection *kept;
9541
9542   kept = sec->kept_section;
9543   if (kept != NULL)
9544     {
9545       if ((kept->flags & SEC_GROUP) != 0)
9546         kept = match_group_member (sec, kept, info);
9547       if (kept != NULL
9548           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9549               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9550         kept = NULL;
9551       sec->kept_section = kept;
9552     }
9553   return kept;
9554 }
9555
9556 /* Link an input file into the linker output file.  This function
9557    handles all the sections and relocations of the input file at once.
9558    This is so that we only have to read the local symbols once, and
9559    don't have to keep them in memory.  */
9560
9561 static bfd_boolean
9562 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9563 {
9564   int (*relocate_section)
9565     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9566      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9567   bfd *output_bfd;
9568   Elf_Internal_Shdr *symtab_hdr;
9569   size_t locsymcount;
9570   size_t extsymoff;
9571   Elf_Internal_Sym *isymbuf;
9572   Elf_Internal_Sym *isym;
9573   Elf_Internal_Sym *isymend;
9574   long *pindex;
9575   asection **ppsection;
9576   asection *o;
9577   const struct elf_backend_data *bed;
9578   struct elf_link_hash_entry **sym_hashes;
9579   bfd_size_type address_size;
9580   bfd_vma r_type_mask;
9581   int r_sym_shift;
9582   bfd_boolean have_file_sym = FALSE;
9583
9584   output_bfd = flinfo->output_bfd;
9585   bed = get_elf_backend_data (output_bfd);
9586   relocate_section = bed->elf_backend_relocate_section;
9587
9588   /* If this is a dynamic object, we don't want to do anything here:
9589      we don't want the local symbols, and we don't want the section
9590      contents.  */
9591   if ((input_bfd->flags & DYNAMIC) != 0)
9592     return TRUE;
9593
9594   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9595   if (elf_bad_symtab (input_bfd))
9596     {
9597       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9598       extsymoff = 0;
9599     }
9600   else
9601     {
9602       locsymcount = symtab_hdr->sh_info;
9603       extsymoff = symtab_hdr->sh_info;
9604     }
9605
9606   /* Read the local symbols.  */
9607   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9608   if (isymbuf == NULL && locsymcount != 0)
9609     {
9610       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9611                                       flinfo->internal_syms,
9612                                       flinfo->external_syms,
9613                                       flinfo->locsym_shndx);
9614       if (isymbuf == NULL)
9615         return FALSE;
9616     }
9617
9618   /* Find local symbol sections and adjust values of symbols in
9619      SEC_MERGE sections.  Write out those local symbols we know are
9620      going into the output file.  */
9621   isymend = isymbuf + locsymcount;
9622   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9623        isym < isymend;
9624        isym++, pindex++, ppsection++)
9625     {
9626       asection *isec;
9627       const char *name;
9628       Elf_Internal_Sym osym;
9629       long indx;
9630       int ret;
9631
9632       *pindex = -1;
9633
9634       if (elf_bad_symtab (input_bfd))
9635         {
9636           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9637             {
9638               *ppsection = NULL;
9639               continue;
9640             }
9641         }
9642
9643       if (isym->st_shndx == SHN_UNDEF)
9644         isec = bfd_und_section_ptr;
9645       else if (isym->st_shndx == SHN_ABS)
9646         isec = bfd_abs_section_ptr;
9647       else if (isym->st_shndx == SHN_COMMON)
9648         isec = bfd_com_section_ptr;
9649       else
9650         {
9651           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9652           if (isec == NULL)
9653             {
9654               /* Don't attempt to output symbols with st_shnx in the
9655                  reserved range other than SHN_ABS and SHN_COMMON.  */
9656               *ppsection = NULL;
9657               continue;
9658             }
9659           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9660                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9661             isym->st_value =
9662               _bfd_merged_section_offset (output_bfd, &isec,
9663                                           elf_section_data (isec)->sec_info,
9664                                           isym->st_value);
9665         }
9666
9667       *ppsection = isec;
9668
9669       /* Don't output the first, undefined, symbol.  In fact, don't
9670          output any undefined local symbol.  */
9671       if (isec == bfd_und_section_ptr)
9672         continue;
9673
9674       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9675         {
9676           /* We never output section symbols.  Instead, we use the
9677              section symbol of the corresponding section in the output
9678              file.  */
9679           continue;
9680         }
9681
9682       /* If we are stripping all symbols, we don't want to output this
9683          one.  */
9684       if (flinfo->info->strip == strip_all)
9685         continue;
9686
9687       /* If we are discarding all local symbols, we don't want to
9688          output this one.  If we are generating a relocatable output
9689          file, then some of the local symbols may be required by
9690          relocs; we output them below as we discover that they are
9691          needed.  */
9692       if (flinfo->info->discard == discard_all)
9693         continue;
9694
9695       /* If this symbol is defined in a section which we are
9696          discarding, we don't need to keep it.  */
9697       if (isym->st_shndx != SHN_UNDEF
9698           && isym->st_shndx < SHN_LORESERVE
9699           && bfd_section_removed_from_list (output_bfd,
9700                                             isec->output_section))
9701         continue;
9702
9703       /* Get the name of the symbol.  */
9704       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9705                                               isym->st_name);
9706       if (name == NULL)
9707         return FALSE;
9708
9709       /* See if we are discarding symbols with this name.  */
9710       if ((flinfo->info->strip == strip_some
9711            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9712                == NULL))
9713           || (((flinfo->info->discard == discard_sec_merge
9714                 && (isec->flags & SEC_MERGE) && !flinfo->info->relocatable)
9715                || flinfo->info->discard == discard_l)
9716               && bfd_is_local_label_name (input_bfd, name)))
9717         continue;
9718
9719       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9720         {
9721           if (input_bfd->lto_output)
9722             /* -flto puts a temp file name here.  This means builds
9723                are not reproducible.  Discard the symbol.  */
9724             continue;
9725           have_file_sym = TRUE;
9726           flinfo->filesym_count += 1;
9727         }
9728       if (!have_file_sym)
9729         {
9730           /* In the absence of debug info, bfd_find_nearest_line uses
9731              FILE symbols to determine the source file for local
9732              function symbols.  Provide a FILE symbol here if input
9733              files lack such, so that their symbols won't be
9734              associated with a previous input file.  It's not the
9735              source file, but the best we can do.  */
9736           have_file_sym = TRUE;
9737           flinfo->filesym_count += 1;
9738           memset (&osym, 0, sizeof (osym));
9739           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9740           osym.st_shndx = SHN_ABS;
9741           if (!elf_link_output_symstrtab (flinfo,
9742                                           (input_bfd->lto_output ? NULL
9743                                            : input_bfd->filename),
9744                                           &osym, bfd_abs_section_ptr,
9745                                           NULL))
9746             return FALSE;
9747         }
9748
9749       osym = *isym;
9750
9751       /* Adjust the section index for the output file.  */
9752       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9753                                                          isec->output_section);
9754       if (osym.st_shndx == SHN_BAD)
9755         return FALSE;
9756
9757       /* ELF symbols in relocatable files are section relative, but
9758          in executable files they are virtual addresses.  Note that
9759          this code assumes that all ELF sections have an associated
9760          BFD section with a reasonable value for output_offset; below
9761          we assume that they also have a reasonable value for
9762          output_section.  Any special sections must be set up to meet
9763          these requirements.  */
9764       osym.st_value += isec->output_offset;
9765       if (!flinfo->info->relocatable)
9766         {
9767           osym.st_value += isec->output_section->vma;
9768           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9769             {
9770               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9771               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9772               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9773             }
9774         }
9775
9776       indx = bfd_get_symcount (output_bfd);
9777       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
9778       if (ret == 0)
9779         return FALSE;
9780       else if (ret == 1)
9781         *pindex = indx;
9782     }
9783
9784   if (bed->s->arch_size == 32)
9785     {
9786       r_type_mask = 0xff;
9787       r_sym_shift = 8;
9788       address_size = 4;
9789     }
9790   else
9791     {
9792       r_type_mask = 0xffffffff;
9793       r_sym_shift = 32;
9794       address_size = 8;
9795     }
9796
9797   /* Relocate the contents of each section.  */
9798   sym_hashes = elf_sym_hashes (input_bfd);
9799   for (o = input_bfd->sections; o != NULL; o = o->next)
9800     {
9801       bfd_byte *contents;
9802
9803       if (! o->linker_mark)
9804         {
9805           /* This section was omitted from the link.  */
9806           continue;
9807         }
9808
9809       if (flinfo->info->relocatable
9810           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9811         {
9812           /* Deal with the group signature symbol.  */
9813           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9814           unsigned long symndx = sec_data->this_hdr.sh_info;
9815           asection *osec = o->output_section;
9816
9817           if (symndx >= locsymcount
9818               || (elf_bad_symtab (input_bfd)
9819                   && flinfo->sections[symndx] == NULL))
9820             {
9821               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9822               while (h->root.type == bfd_link_hash_indirect
9823                      || h->root.type == bfd_link_hash_warning)
9824                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9825               /* Arrange for symbol to be output.  */
9826               h->indx = -2;
9827               elf_section_data (osec)->this_hdr.sh_info = -2;
9828             }
9829           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9830             {
9831               /* We'll use the output section target_index.  */
9832               asection *sec = flinfo->sections[symndx]->output_section;
9833               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9834             }
9835           else
9836             {
9837               if (flinfo->indices[symndx] == -1)
9838                 {
9839                   /* Otherwise output the local symbol now.  */
9840                   Elf_Internal_Sym sym = isymbuf[symndx];
9841                   asection *sec = flinfo->sections[symndx]->output_section;
9842                   const char *name;
9843                   long indx;
9844                   int ret;
9845
9846                   name = bfd_elf_string_from_elf_section (input_bfd,
9847                                                           symtab_hdr->sh_link,
9848                                                           sym.st_name);
9849                   if (name == NULL)
9850                     return FALSE;
9851
9852                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9853                                                                     sec);
9854                   if (sym.st_shndx == SHN_BAD)
9855                     return FALSE;
9856
9857                   sym.st_value += o->output_offset;
9858
9859                   indx = bfd_get_symcount (output_bfd);
9860                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
9861                                                    NULL);
9862                   if (ret == 0)
9863                     return FALSE;
9864                   else if (ret == 1)
9865                     flinfo->indices[symndx] = indx;
9866                   else
9867                     abort ();
9868                 }
9869               elf_section_data (osec)->this_hdr.sh_info
9870                 = flinfo->indices[symndx];
9871             }
9872         }
9873
9874       if ((o->flags & SEC_HAS_CONTENTS) == 0
9875           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9876         continue;
9877
9878       if ((o->flags & SEC_LINKER_CREATED) != 0)
9879         {
9880           /* Section was created by _bfd_elf_link_create_dynamic_sections
9881              or somesuch.  */
9882           continue;
9883         }
9884
9885       /* Get the contents of the section.  They have been cached by a
9886          relaxation routine.  Note that o is a section in an input
9887          file, so the contents field will not have been set by any of
9888          the routines which work on output files.  */
9889       if (elf_section_data (o)->this_hdr.contents != NULL)
9890         {
9891           contents = elf_section_data (o)->this_hdr.contents;
9892           if (bed->caches_rawsize
9893               && o->rawsize != 0
9894               && o->rawsize < o->size)
9895             {
9896               memcpy (flinfo->contents, contents, o->rawsize);
9897               contents = flinfo->contents;
9898             }
9899         }
9900       else
9901         {
9902           contents = flinfo->contents;
9903           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9904             return FALSE;
9905         }
9906
9907       if ((o->flags & SEC_RELOC) != 0)
9908         {
9909           Elf_Internal_Rela *internal_relocs;
9910           Elf_Internal_Rela *rel, *relend;
9911           int action_discarded;
9912           int ret;
9913
9914           /* Get the swapped relocs.  */
9915           internal_relocs
9916             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
9917                                          flinfo->internal_relocs, FALSE);
9918           if (internal_relocs == NULL
9919               && o->reloc_count > 0)
9920             return FALSE;
9921
9922           /* We need to reverse-copy input .ctors/.dtors sections if
9923              they are placed in .init_array/.finit_array for output.  */
9924           if (o->size > address_size
9925               && ((strncmp (o->name, ".ctors", 6) == 0
9926                    && strcmp (o->output_section->name,
9927                               ".init_array") == 0)
9928                   || (strncmp (o->name, ".dtors", 6) == 0
9929                       && strcmp (o->output_section->name,
9930                                  ".fini_array") == 0))
9931               && (o->name[6] == 0 || o->name[6] == '.'))
9932             {
9933               if (o->size != o->reloc_count * address_size)
9934                 {
9935                   (*_bfd_error_handler)
9936                     (_("error: %B: size of section %A is not "
9937                        "multiple of address size"),
9938                      input_bfd, o);
9939                   bfd_set_error (bfd_error_on_input);
9940                   return FALSE;
9941                 }
9942               o->flags |= SEC_ELF_REVERSE_COPY;
9943             }
9944
9945           action_discarded = -1;
9946           if (!elf_section_ignore_discarded_relocs (o))
9947             action_discarded = (*bed->action_discarded) (o);
9948
9949           /* Run through the relocs evaluating complex reloc symbols and
9950              looking for relocs against symbols from discarded sections
9951              or section symbols from removed link-once sections.
9952              Complain about relocs against discarded sections.  Zero
9953              relocs against removed link-once sections.  */
9954
9955           rel = internal_relocs;
9956           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9957           for ( ; rel < relend; rel++)
9958             {
9959               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9960               unsigned int s_type;
9961               asection **ps, *sec;
9962               struct elf_link_hash_entry *h = NULL;
9963               const char *sym_name;
9964
9965               if (r_symndx == STN_UNDEF)
9966                 continue;
9967
9968               if (r_symndx >= locsymcount
9969                   || (elf_bad_symtab (input_bfd)
9970                       && flinfo->sections[r_symndx] == NULL))
9971                 {
9972                   h = sym_hashes[r_symndx - extsymoff];
9973
9974                   /* Badly formatted input files can contain relocs that
9975                      reference non-existant symbols.  Check here so that
9976                      we do not seg fault.  */
9977                   if (h == NULL)
9978                     {
9979                       char buffer [32];
9980
9981                       sprintf_vma (buffer, rel->r_info);
9982                       (*_bfd_error_handler)
9983                         (_("error: %B contains a reloc (0x%s) for section %A "
9984                            "that references a non-existent global symbol"),
9985                          input_bfd, o, buffer);
9986                       bfd_set_error (bfd_error_bad_value);
9987                       return FALSE;
9988                     }
9989
9990                   while (h->root.type == bfd_link_hash_indirect
9991                          || h->root.type == bfd_link_hash_warning)
9992                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9993
9994                   s_type = h->type;
9995
9996                   /* If a plugin symbol is referenced from a non-IR file,
9997                      mark the symbol as undefined.  Note that the
9998                      linker may attach linker created dynamic sections
9999                      to the plugin bfd.  Symbols defined in linker
10000                      created sections are not plugin symbols.  */
10001                   if (h->root.non_ir_ref
10002                       && (h->root.type == bfd_link_hash_defined
10003                           || h->root.type == bfd_link_hash_defweak)
10004                       && (h->root.u.def.section->flags
10005                           & SEC_LINKER_CREATED) == 0
10006                       && h->root.u.def.section->owner != NULL
10007                       && (h->root.u.def.section->owner->flags
10008                           & BFD_PLUGIN) != 0)
10009                     {
10010                       h->root.type = bfd_link_hash_undefined;
10011                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10012                     }
10013
10014                   ps = NULL;
10015                   if (h->root.type == bfd_link_hash_defined
10016                       || h->root.type == bfd_link_hash_defweak)
10017                     ps = &h->root.u.def.section;
10018
10019                   sym_name = h->root.root.string;
10020                 }
10021               else
10022                 {
10023                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10024
10025                   s_type = ELF_ST_TYPE (sym->st_info);
10026                   ps = &flinfo->sections[r_symndx];
10027                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10028                                                sym, *ps);
10029                 }
10030
10031               if ((s_type == STT_RELC || s_type == STT_SRELC)
10032                   && !flinfo->info->relocatable)
10033                 {
10034                   bfd_vma val;
10035                   bfd_vma dot = (rel->r_offset
10036                                  + o->output_offset + o->output_section->vma);
10037 #ifdef DEBUG
10038                   printf ("Encountered a complex symbol!");
10039                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10040                           input_bfd->filename, o->name,
10041                           (long) (rel - internal_relocs));
10042                   printf (" symbol: idx  %8.8lx, name %s\n",
10043                           r_symndx, sym_name);
10044                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10045                           (unsigned long) rel->r_info,
10046                           (unsigned long) rel->r_offset);
10047 #endif
10048                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10049                                     isymbuf, locsymcount, s_type == STT_SRELC))
10050                     return FALSE;
10051
10052                   /* Symbol evaluated OK.  Update to absolute value.  */
10053                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10054                                     r_symndx, val);
10055                   continue;
10056                 }
10057
10058               if (action_discarded != -1 && ps != NULL)
10059                 {
10060                   /* Complain if the definition comes from a
10061                      discarded section.  */
10062                   if ((sec = *ps) != NULL && discarded_section (sec))
10063                     {
10064                       BFD_ASSERT (r_symndx != STN_UNDEF);
10065                       if (action_discarded & COMPLAIN)
10066                         (*flinfo->info->callbacks->einfo)
10067                           (_("%X`%s' referenced in section `%A' of %B: "
10068                              "defined in discarded section `%A' of %B\n"),
10069                            sym_name, o, input_bfd, sec, sec->owner);
10070
10071                       /* Try to do the best we can to support buggy old
10072                          versions of gcc.  Pretend that the symbol is
10073                          really defined in the kept linkonce section.
10074                          FIXME: This is quite broken.  Modifying the
10075                          symbol here means we will be changing all later
10076                          uses of the symbol, not just in this section.  */
10077                       if (action_discarded & PRETEND)
10078                         {
10079                           asection *kept;
10080
10081                           kept = _bfd_elf_check_kept_section (sec,
10082                                                               flinfo->info);
10083                           if (kept != NULL)
10084                             {
10085                               *ps = kept;
10086                               continue;
10087                             }
10088                         }
10089                     }
10090                 }
10091             }
10092
10093           /* Relocate the section by invoking a back end routine.
10094
10095              The back end routine is responsible for adjusting the
10096              section contents as necessary, and (if using Rela relocs
10097              and generating a relocatable output file) adjusting the
10098              reloc addend as necessary.
10099
10100              The back end routine does not have to worry about setting
10101              the reloc address or the reloc symbol index.
10102
10103              The back end routine is given a pointer to the swapped in
10104              internal symbols, and can access the hash table entries
10105              for the external symbols via elf_sym_hashes (input_bfd).
10106
10107              When generating relocatable output, the back end routine
10108              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10109              output symbol is going to be a section symbol
10110              corresponding to the output section, which will require
10111              the addend to be adjusted.  */
10112
10113           ret = (*relocate_section) (output_bfd, flinfo->info,
10114                                      input_bfd, o, contents,
10115                                      internal_relocs,
10116                                      isymbuf,
10117                                      flinfo->sections);
10118           if (!ret)
10119             return FALSE;
10120
10121           if (ret == 2
10122               || flinfo->info->relocatable
10123               || flinfo->info->emitrelocations)
10124             {
10125               Elf_Internal_Rela *irela;
10126               Elf_Internal_Rela *irelaend, *irelamid;
10127               bfd_vma last_offset;
10128               struct elf_link_hash_entry **rel_hash;
10129               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10130               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10131               unsigned int next_erel;
10132               bfd_boolean rela_normal;
10133               struct bfd_elf_section_data *esdi, *esdo;
10134
10135               esdi = elf_section_data (o);
10136               esdo = elf_section_data (o->output_section);
10137               rela_normal = FALSE;
10138
10139               /* Adjust the reloc addresses and symbol indices.  */
10140
10141               irela = internal_relocs;
10142               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10143               rel_hash = esdo->rel.hashes + esdo->rel.count;
10144               /* We start processing the REL relocs, if any.  When we reach
10145                  IRELAMID in the loop, we switch to the RELA relocs.  */
10146               irelamid = irela;
10147               if (esdi->rel.hdr != NULL)
10148                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10149                              * bed->s->int_rels_per_ext_rel);
10150               rel_hash_list = rel_hash;
10151               rela_hash_list = NULL;
10152               last_offset = o->output_offset;
10153               if (!flinfo->info->relocatable)
10154                 last_offset += o->output_section->vma;
10155               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10156                 {
10157                   unsigned long r_symndx;
10158                   asection *sec;
10159                   Elf_Internal_Sym sym;
10160
10161                   if (next_erel == bed->s->int_rels_per_ext_rel)
10162                     {
10163                       rel_hash++;
10164                       next_erel = 0;
10165                     }
10166
10167                   if (irela == irelamid)
10168                     {
10169                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10170                       rela_hash_list = rel_hash;
10171                       rela_normal = bed->rela_normal;
10172                     }
10173
10174                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10175                                                              flinfo->info, o,
10176                                                              irela->r_offset);
10177                   if (irela->r_offset >= (bfd_vma) -2)
10178                     {
10179                       /* This is a reloc for a deleted entry or somesuch.
10180                          Turn it into an R_*_NONE reloc, at the same
10181                          offset as the last reloc.  elf_eh_frame.c and
10182                          bfd_elf_discard_info rely on reloc offsets
10183                          being ordered.  */
10184                       irela->r_offset = last_offset;
10185                       irela->r_info = 0;
10186                       irela->r_addend = 0;
10187                       continue;
10188                     }
10189
10190                   irela->r_offset += o->output_offset;
10191
10192                   /* Relocs in an executable have to be virtual addresses.  */
10193                   if (!flinfo->info->relocatable)
10194                     irela->r_offset += o->output_section->vma;
10195
10196                   last_offset = irela->r_offset;
10197
10198                   r_symndx = irela->r_info >> r_sym_shift;
10199                   if (r_symndx == STN_UNDEF)
10200                     continue;
10201
10202                   if (r_symndx >= locsymcount
10203                       || (elf_bad_symtab (input_bfd)
10204                           && flinfo->sections[r_symndx] == NULL))
10205                     {
10206                       struct elf_link_hash_entry *rh;
10207                       unsigned long indx;
10208
10209                       /* This is a reloc against a global symbol.  We
10210                          have not yet output all the local symbols, so
10211                          we do not know the symbol index of any global
10212                          symbol.  We set the rel_hash entry for this
10213                          reloc to point to the global hash table entry
10214                          for this symbol.  The symbol index is then
10215                          set at the end of bfd_elf_final_link.  */
10216                       indx = r_symndx - extsymoff;
10217                       rh = elf_sym_hashes (input_bfd)[indx];
10218                       while (rh->root.type == bfd_link_hash_indirect
10219                              || rh->root.type == bfd_link_hash_warning)
10220                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10221
10222                       /* Setting the index to -2 tells
10223                          elf_link_output_extsym that this symbol is
10224                          used by a reloc.  */
10225                       BFD_ASSERT (rh->indx < 0);
10226                       rh->indx = -2;
10227
10228                       *rel_hash = rh;
10229
10230                       continue;
10231                     }
10232
10233                   /* This is a reloc against a local symbol.  */
10234
10235                   *rel_hash = NULL;
10236                   sym = isymbuf[r_symndx];
10237                   sec = flinfo->sections[r_symndx];
10238                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10239                     {
10240                       /* I suppose the backend ought to fill in the
10241                          section of any STT_SECTION symbol against a
10242                          processor specific section.  */
10243                       r_symndx = STN_UNDEF;
10244                       if (bfd_is_abs_section (sec))
10245                         ;
10246                       else if (sec == NULL || sec->owner == NULL)
10247                         {
10248                           bfd_set_error (bfd_error_bad_value);
10249                           return FALSE;
10250                         }
10251                       else
10252                         {
10253                           asection *osec = sec->output_section;
10254
10255                           /* If we have discarded a section, the output
10256                              section will be the absolute section.  In
10257                              case of discarded SEC_MERGE sections, use
10258                              the kept section.  relocate_section should
10259                              have already handled discarded linkonce
10260                              sections.  */
10261                           if (bfd_is_abs_section (osec)
10262                               && sec->kept_section != NULL
10263                               && sec->kept_section->output_section != NULL)
10264                             {
10265                               osec = sec->kept_section->output_section;
10266                               irela->r_addend -= osec->vma;
10267                             }
10268
10269                           if (!bfd_is_abs_section (osec))
10270                             {
10271                               r_symndx = osec->target_index;
10272                               if (r_symndx == STN_UNDEF)
10273                                 {
10274                                   irela->r_addend += osec->vma;
10275                                   osec = _bfd_nearby_section (output_bfd, osec,
10276                                                               osec->vma);
10277                                   irela->r_addend -= osec->vma;
10278                                   r_symndx = osec->target_index;
10279                                 }
10280                             }
10281                         }
10282
10283                       /* Adjust the addend according to where the
10284                          section winds up in the output section.  */
10285                       if (rela_normal)
10286                         irela->r_addend += sec->output_offset;
10287                     }
10288                   else
10289                     {
10290                       if (flinfo->indices[r_symndx] == -1)
10291                         {
10292                           unsigned long shlink;
10293                           const char *name;
10294                           asection *osec;
10295                           long indx;
10296
10297                           if (flinfo->info->strip == strip_all)
10298                             {
10299                               /* You can't do ld -r -s.  */
10300                               bfd_set_error (bfd_error_invalid_operation);
10301                               return FALSE;
10302                             }
10303
10304                           /* This symbol was skipped earlier, but
10305                              since it is needed by a reloc, we
10306                              must output it now.  */
10307                           shlink = symtab_hdr->sh_link;
10308                           name = (bfd_elf_string_from_elf_section
10309                                   (input_bfd, shlink, sym.st_name));
10310                           if (name == NULL)
10311                             return FALSE;
10312
10313                           osec = sec->output_section;
10314                           sym.st_shndx =
10315                             _bfd_elf_section_from_bfd_section (output_bfd,
10316                                                                osec);
10317                           if (sym.st_shndx == SHN_BAD)
10318                             return FALSE;
10319
10320                           sym.st_value += sec->output_offset;
10321                           if (!flinfo->info->relocatable)
10322                             {
10323                               sym.st_value += osec->vma;
10324                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10325                                 {
10326                                   /* STT_TLS symbols are relative to PT_TLS
10327                                      segment base.  */
10328                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10329                                               ->tls_sec != NULL);
10330                                   sym.st_value -= (elf_hash_table (flinfo->info)
10331                                                    ->tls_sec->vma);
10332                                 }
10333                             }
10334
10335                           indx = bfd_get_symcount (output_bfd);
10336                           ret = elf_link_output_symstrtab (flinfo, name,
10337                                                            &sym, sec,
10338                                                            NULL);
10339                           if (ret == 0)
10340                             return FALSE;
10341                           else if (ret == 1)
10342                             flinfo->indices[r_symndx] = indx;
10343                           else
10344                             abort ();
10345                         }
10346
10347                       r_symndx = flinfo->indices[r_symndx];
10348                     }
10349
10350                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10351                                    | (irela->r_info & r_type_mask));
10352                 }
10353
10354               /* Swap out the relocs.  */
10355               input_rel_hdr = esdi->rel.hdr;
10356               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10357                 {
10358                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10359                                                      input_rel_hdr,
10360                                                      internal_relocs,
10361                                                      rel_hash_list))
10362                     return FALSE;
10363                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10364                                       * bed->s->int_rels_per_ext_rel);
10365                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10366                 }
10367
10368               input_rela_hdr = esdi->rela.hdr;
10369               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10370                 {
10371                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10372                                                      input_rela_hdr,
10373                                                      internal_relocs,
10374                                                      rela_hash_list))
10375                     return FALSE;
10376                 }
10377             }
10378         }
10379
10380       /* Write out the modified section contents.  */
10381       if (bed->elf_backend_write_section
10382           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10383                                                 contents))
10384         {
10385           /* Section written out.  */
10386         }
10387       else switch (o->sec_info_type)
10388         {
10389         case SEC_INFO_TYPE_STABS:
10390           if (! (_bfd_write_section_stabs
10391                  (output_bfd,
10392                   &elf_hash_table (flinfo->info)->stab_info,
10393                   o, &elf_section_data (o)->sec_info, contents)))
10394             return FALSE;
10395           break;
10396         case SEC_INFO_TYPE_MERGE:
10397           if (! _bfd_write_merged_section (output_bfd, o,
10398                                            elf_section_data (o)->sec_info))
10399             return FALSE;
10400           break;
10401         case SEC_INFO_TYPE_EH_FRAME:
10402           {
10403             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10404                                                    o, contents))
10405               return FALSE;
10406           }
10407           break;
10408         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10409           {
10410             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10411                                                          flinfo->info,
10412                                                          o, contents))
10413               return FALSE;
10414           }
10415           break;
10416         default:
10417           {
10418             /* FIXME: octets_per_byte.  */
10419             if (! (o->flags & SEC_EXCLUDE))
10420               {
10421                 file_ptr offset = (file_ptr) o->output_offset;
10422                 bfd_size_type todo = o->size;
10423                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10424                   {
10425                     /* Reverse-copy input section to output.  */
10426                     do
10427                       {
10428                         todo -= address_size;
10429                         if (! bfd_set_section_contents (output_bfd,
10430                                                         o->output_section,
10431                                                         contents + todo,
10432                                                         offset,
10433                                                         address_size))
10434                           return FALSE;
10435                         if (todo == 0)
10436                           break;
10437                         offset += address_size;
10438                       }
10439                     while (1);
10440                   }
10441                 else if (! bfd_set_section_contents (output_bfd,
10442                                                      o->output_section,
10443                                                      contents,
10444                                                      offset, todo))
10445                   return FALSE;
10446               }
10447           }
10448           break;
10449         }
10450     }
10451
10452   return TRUE;
10453 }
10454
10455 /* Generate a reloc when linking an ELF file.  This is a reloc
10456    requested by the linker, and does not come from any input file.  This
10457    is used to build constructor and destructor tables when linking
10458    with -Ur.  */
10459
10460 static bfd_boolean
10461 elf_reloc_link_order (bfd *output_bfd,
10462                       struct bfd_link_info *info,
10463                       asection *output_section,
10464                       struct bfd_link_order *link_order)
10465 {
10466   reloc_howto_type *howto;
10467   long indx;
10468   bfd_vma offset;
10469   bfd_vma addend;
10470   struct bfd_elf_section_reloc_data *reldata;
10471   struct elf_link_hash_entry **rel_hash_ptr;
10472   Elf_Internal_Shdr *rel_hdr;
10473   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10474   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10475   bfd_byte *erel;
10476   unsigned int i;
10477   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10478
10479   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10480   if (howto == NULL)
10481     {
10482       bfd_set_error (bfd_error_bad_value);
10483       return FALSE;
10484     }
10485
10486   addend = link_order->u.reloc.p->addend;
10487
10488   if (esdo->rel.hdr)
10489     reldata = &esdo->rel;
10490   else if (esdo->rela.hdr)
10491     reldata = &esdo->rela;
10492   else
10493     {
10494       reldata = NULL;
10495       BFD_ASSERT (0);
10496     }
10497
10498   /* Figure out the symbol index.  */
10499   rel_hash_ptr = reldata->hashes + reldata->count;
10500   if (link_order->type == bfd_section_reloc_link_order)
10501     {
10502       indx = link_order->u.reloc.p->u.section->target_index;
10503       BFD_ASSERT (indx != 0);
10504       *rel_hash_ptr = NULL;
10505     }
10506   else
10507     {
10508       struct elf_link_hash_entry *h;
10509
10510       /* Treat a reloc against a defined symbol as though it were
10511          actually against the section.  */
10512       h = ((struct elf_link_hash_entry *)
10513            bfd_wrapped_link_hash_lookup (output_bfd, info,
10514                                          link_order->u.reloc.p->u.name,
10515                                          FALSE, FALSE, TRUE));
10516       if (h != NULL
10517           && (h->root.type == bfd_link_hash_defined
10518               || h->root.type == bfd_link_hash_defweak))
10519         {
10520           asection *section;
10521
10522           section = h->root.u.def.section;
10523           indx = section->output_section->target_index;
10524           *rel_hash_ptr = NULL;
10525           /* It seems that we ought to add the symbol value to the
10526              addend here, but in practice it has already been added
10527              because it was passed to constructor_callback.  */
10528           addend += section->output_section->vma + section->output_offset;
10529         }
10530       else if (h != NULL)
10531         {
10532           /* Setting the index to -2 tells elf_link_output_extsym that
10533              this symbol is used by a reloc.  */
10534           h->indx = -2;
10535           *rel_hash_ptr = h;
10536           indx = 0;
10537         }
10538       else
10539         {
10540           if (! ((*info->callbacks->unattached_reloc)
10541                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10542             return FALSE;
10543           indx = 0;
10544         }
10545     }
10546
10547   /* If this is an inplace reloc, we must write the addend into the
10548      object file.  */
10549   if (howto->partial_inplace && addend != 0)
10550     {
10551       bfd_size_type size;
10552       bfd_reloc_status_type rstat;
10553       bfd_byte *buf;
10554       bfd_boolean ok;
10555       const char *sym_name;
10556
10557       size = (bfd_size_type) bfd_get_reloc_size (howto);
10558       buf = (bfd_byte *) bfd_zmalloc (size);
10559       if (buf == NULL && size != 0)
10560         return FALSE;
10561       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10562       switch (rstat)
10563         {
10564         case bfd_reloc_ok:
10565           break;
10566
10567         default:
10568         case bfd_reloc_outofrange:
10569           abort ();
10570
10571         case bfd_reloc_overflow:
10572           if (link_order->type == bfd_section_reloc_link_order)
10573             sym_name = bfd_section_name (output_bfd,
10574                                          link_order->u.reloc.p->u.section);
10575           else
10576             sym_name = link_order->u.reloc.p->u.name;
10577           if (! ((*info->callbacks->reloc_overflow)
10578                  (info, NULL, sym_name, howto->name, addend, NULL,
10579                   NULL, (bfd_vma) 0)))
10580             {
10581               free (buf);
10582               return FALSE;
10583             }
10584           break;
10585         }
10586       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10587                                      link_order->offset, size);
10588       free (buf);
10589       if (! ok)
10590         return FALSE;
10591     }
10592
10593   /* The address of a reloc is relative to the section in a
10594      relocatable file, and is a virtual address in an executable
10595      file.  */
10596   offset = link_order->offset;
10597   if (! info->relocatable)
10598     offset += output_section->vma;
10599
10600   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10601     {
10602       irel[i].r_offset = offset;
10603       irel[i].r_info = 0;
10604       irel[i].r_addend = 0;
10605     }
10606   if (bed->s->arch_size == 32)
10607     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10608   else
10609     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10610
10611   rel_hdr = reldata->hdr;
10612   erel = rel_hdr->contents;
10613   if (rel_hdr->sh_type == SHT_REL)
10614     {
10615       erel += reldata->count * bed->s->sizeof_rel;
10616       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10617     }
10618   else
10619     {
10620       irel[0].r_addend = addend;
10621       erel += reldata->count * bed->s->sizeof_rela;
10622       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10623     }
10624
10625   ++reldata->count;
10626
10627   return TRUE;
10628 }
10629
10630
10631 /* Get the output vma of the section pointed to by the sh_link field.  */
10632
10633 static bfd_vma
10634 elf_get_linked_section_vma (struct bfd_link_order *p)
10635 {
10636   Elf_Internal_Shdr **elf_shdrp;
10637   asection *s;
10638   int elfsec;
10639
10640   s = p->u.indirect.section;
10641   elf_shdrp = elf_elfsections (s->owner);
10642   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10643   elfsec = elf_shdrp[elfsec]->sh_link;
10644   /* PR 290:
10645      The Intel C compiler generates SHT_IA_64_UNWIND with
10646      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10647      sh_info fields.  Hence we could get the situation
10648      where elfsec is 0.  */
10649   if (elfsec == 0)
10650     {
10651       const struct elf_backend_data *bed
10652         = get_elf_backend_data (s->owner);
10653       if (bed->link_order_error_handler)
10654         bed->link_order_error_handler
10655           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10656       return 0;
10657     }
10658   else
10659     {
10660       s = elf_shdrp[elfsec]->bfd_section;
10661       return s->output_section->vma + s->output_offset;
10662     }
10663 }
10664
10665
10666 /* Compare two sections based on the locations of the sections they are
10667    linked to.  Used by elf_fixup_link_order.  */
10668
10669 static int
10670 compare_link_order (const void * a, const void * b)
10671 {
10672   bfd_vma apos;
10673   bfd_vma bpos;
10674
10675   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10676   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10677   if (apos < bpos)
10678     return -1;
10679   return apos > bpos;
10680 }
10681
10682
10683 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10684    order as their linked sections.  Returns false if this could not be done
10685    because an output section includes both ordered and unordered
10686    sections.  Ideally we'd do this in the linker proper.  */
10687
10688 static bfd_boolean
10689 elf_fixup_link_order (bfd *abfd, asection *o)
10690 {
10691   int seen_linkorder;
10692   int seen_other;
10693   int n;
10694   struct bfd_link_order *p;
10695   bfd *sub;
10696   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10697   unsigned elfsec;
10698   struct bfd_link_order **sections;
10699   asection *s, *other_sec, *linkorder_sec;
10700   bfd_vma offset;
10701
10702   other_sec = NULL;
10703   linkorder_sec = NULL;
10704   seen_other = 0;
10705   seen_linkorder = 0;
10706   for (p = o->map_head.link_order; p != NULL; p = p->next)
10707     {
10708       if (p->type == bfd_indirect_link_order)
10709         {
10710           s = p->u.indirect.section;
10711           sub = s->owner;
10712           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10713               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10714               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10715               && elfsec < elf_numsections (sub)
10716               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10717               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10718             {
10719               seen_linkorder++;
10720               linkorder_sec = s;
10721             }
10722           else
10723             {
10724               seen_other++;
10725               other_sec = s;
10726             }
10727         }
10728       else
10729         seen_other++;
10730
10731       if (seen_other && seen_linkorder)
10732         {
10733           if (other_sec && linkorder_sec)
10734             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10735                                    o, linkorder_sec,
10736                                    linkorder_sec->owner, other_sec,
10737                                    other_sec->owner);
10738           else
10739             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10740                                    o);
10741           bfd_set_error (bfd_error_bad_value);
10742           return FALSE;
10743         }
10744     }
10745
10746   if (!seen_linkorder)
10747     return TRUE;
10748
10749   sections = (struct bfd_link_order **)
10750     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10751   if (sections == NULL)
10752     return FALSE;
10753   seen_linkorder = 0;
10754
10755   for (p = o->map_head.link_order; p != NULL; p = p->next)
10756     {
10757       sections[seen_linkorder++] = p;
10758     }
10759   /* Sort the input sections in the order of their linked section.  */
10760   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10761          compare_link_order);
10762
10763   /* Change the offsets of the sections.  */
10764   offset = 0;
10765   for (n = 0; n < seen_linkorder; n++)
10766     {
10767       s = sections[n]->u.indirect.section;
10768       offset &= ~(bfd_vma) 0 << s->alignment_power;
10769       s->output_offset = offset;
10770       sections[n]->offset = offset;
10771       /* FIXME: octets_per_byte.  */
10772       offset += sections[n]->size;
10773     }
10774
10775   free (sections);
10776   return TRUE;
10777 }
10778
10779 static void
10780 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10781 {
10782   asection *o;
10783
10784   if (flinfo->symstrtab != NULL)
10785     _bfd_elf_strtab_free (flinfo->symstrtab);
10786   if (flinfo->contents != NULL)
10787     free (flinfo->contents);
10788   if (flinfo->external_relocs != NULL)
10789     free (flinfo->external_relocs);
10790   if (flinfo->internal_relocs != NULL)
10791     free (flinfo->internal_relocs);
10792   if (flinfo->external_syms != NULL)
10793     free (flinfo->external_syms);
10794   if (flinfo->locsym_shndx != NULL)
10795     free (flinfo->locsym_shndx);
10796   if (flinfo->internal_syms != NULL)
10797     free (flinfo->internal_syms);
10798   if (flinfo->indices != NULL)
10799     free (flinfo->indices);
10800   if (flinfo->sections != NULL)
10801     free (flinfo->sections);
10802   if (flinfo->symshndxbuf != NULL)
10803     free (flinfo->symshndxbuf);
10804   for (o = obfd->sections; o != NULL; o = o->next)
10805     {
10806       struct bfd_elf_section_data *esdo = elf_section_data (o);
10807       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10808         free (esdo->rel.hashes);
10809       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10810         free (esdo->rela.hashes);
10811     }
10812 }
10813
10814 /* Do the final step of an ELF link.  */
10815
10816 bfd_boolean
10817 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10818 {
10819   bfd_boolean dynamic;
10820   bfd_boolean emit_relocs;
10821   bfd *dynobj;
10822   struct elf_final_link_info flinfo;
10823   asection *o;
10824   struct bfd_link_order *p;
10825   bfd *sub;
10826   bfd_size_type max_contents_size;
10827   bfd_size_type max_external_reloc_size;
10828   bfd_size_type max_internal_reloc_count;
10829   bfd_size_type max_sym_count;
10830   bfd_size_type max_sym_shndx_count;
10831   Elf_Internal_Sym elfsym;
10832   unsigned int i;
10833   Elf_Internal_Shdr *symtab_hdr;
10834   Elf_Internal_Shdr *symtab_shndx_hdr;
10835   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10836   struct elf_outext_info eoinfo;
10837   bfd_boolean merged;
10838   size_t relativecount = 0;
10839   asection *reldyn = 0;
10840   bfd_size_type amt;
10841   asection *attr_section = NULL;
10842   bfd_vma attr_size = 0;
10843   const char *std_attrs_section;
10844
10845   if (! is_elf_hash_table (info->hash))
10846     return FALSE;
10847
10848   if (info->shared)
10849     abfd->flags |= DYNAMIC;
10850
10851   dynamic = elf_hash_table (info)->dynamic_sections_created;
10852   dynobj = elf_hash_table (info)->dynobj;
10853
10854   emit_relocs = (info->relocatable
10855                  || info->emitrelocations);
10856
10857   flinfo.info = info;
10858   flinfo.output_bfd = abfd;
10859   flinfo.symstrtab = _bfd_elf_strtab_init ();
10860   if (flinfo.symstrtab == NULL)
10861     return FALSE;
10862
10863   if (! dynamic)
10864     {
10865       flinfo.dynsym_sec = NULL;
10866       flinfo.hash_sec = NULL;
10867       flinfo.symver_sec = NULL;
10868     }
10869   else
10870     {
10871       flinfo.dynsym_sec = bfd_get_linker_section (dynobj, ".dynsym");
10872       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
10873       /* Note that dynsym_sec can be NULL (on VMS).  */
10874       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
10875       /* Note that it is OK if symver_sec is NULL.  */
10876     }
10877
10878   flinfo.contents = NULL;
10879   flinfo.external_relocs = NULL;
10880   flinfo.internal_relocs = NULL;
10881   flinfo.external_syms = NULL;
10882   flinfo.locsym_shndx = NULL;
10883   flinfo.internal_syms = NULL;
10884   flinfo.indices = NULL;
10885   flinfo.sections = NULL;
10886   flinfo.symshndxbuf = NULL;
10887   flinfo.filesym_count = 0;
10888
10889   /* The object attributes have been merged.  Remove the input
10890      sections from the link, and set the contents of the output
10891      secton.  */
10892   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10893   for (o = abfd->sections; o != NULL; o = o->next)
10894     {
10895       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10896           || strcmp (o->name, ".gnu.attributes") == 0)
10897         {
10898           for (p = o->map_head.link_order; p != NULL; p = p->next)
10899             {
10900               asection *input_section;
10901
10902               if (p->type != bfd_indirect_link_order)
10903                 continue;
10904               input_section = p->u.indirect.section;
10905               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10906                  elf_link_input_bfd ignores this section.  */
10907               input_section->flags &= ~SEC_HAS_CONTENTS;
10908             }
10909
10910           attr_size = bfd_elf_obj_attr_size (abfd);
10911           if (attr_size)
10912             {
10913               bfd_set_section_size (abfd, o, attr_size);
10914               attr_section = o;
10915               /* Skip this section later on.  */
10916               o->map_head.link_order = NULL;
10917             }
10918           else
10919             o->flags |= SEC_EXCLUDE;
10920         }
10921     }
10922
10923   /* Count up the number of relocations we will output for each output
10924      section, so that we know the sizes of the reloc sections.  We
10925      also figure out some maximum sizes.  */
10926   max_contents_size = 0;
10927   max_external_reloc_size = 0;
10928   max_internal_reloc_count = 0;
10929   max_sym_count = 0;
10930   max_sym_shndx_count = 0;
10931   merged = FALSE;
10932   for (o = abfd->sections; o != NULL; o = o->next)
10933     {
10934       struct bfd_elf_section_data *esdo = elf_section_data (o);
10935       o->reloc_count = 0;
10936
10937       for (p = o->map_head.link_order; p != NULL; p = p->next)
10938         {
10939           unsigned int reloc_count = 0;
10940           struct bfd_elf_section_data *esdi = NULL;
10941
10942           if (p->type == bfd_section_reloc_link_order
10943               || p->type == bfd_symbol_reloc_link_order)
10944             reloc_count = 1;
10945           else if (p->type == bfd_indirect_link_order)
10946             {
10947               asection *sec;
10948
10949               sec = p->u.indirect.section;
10950               esdi = elf_section_data (sec);
10951
10952               /* Mark all sections which are to be included in the
10953                  link.  This will normally be every section.  We need
10954                  to do this so that we can identify any sections which
10955                  the linker has decided to not include.  */
10956               sec->linker_mark = TRUE;
10957
10958               if (sec->flags & SEC_MERGE)
10959                 merged = TRUE;
10960
10961               if (esdo->this_hdr.sh_type == SHT_REL
10962                   || esdo->this_hdr.sh_type == SHT_RELA)
10963                 /* Some backends use reloc_count in relocation sections
10964                    to count particular types of relocs.  Of course,
10965                    reloc sections themselves can't have relocations.  */
10966                 reloc_count = 0;
10967               else if (info->relocatable || info->emitrelocations)
10968                 reloc_count = sec->reloc_count;
10969               else if (bed->elf_backend_count_relocs)
10970                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10971
10972               if (sec->rawsize > max_contents_size)
10973                 max_contents_size = sec->rawsize;
10974               if (sec->size > max_contents_size)
10975                 max_contents_size = sec->size;
10976
10977               /* We are interested in just local symbols, not all
10978                  symbols.  */
10979               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10980                   && (sec->owner->flags & DYNAMIC) == 0)
10981                 {
10982                   size_t sym_count;
10983
10984                   if (elf_bad_symtab (sec->owner))
10985                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10986                                  / bed->s->sizeof_sym);
10987                   else
10988                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10989
10990                   if (sym_count > max_sym_count)
10991                     max_sym_count = sym_count;
10992
10993                   if (sym_count > max_sym_shndx_count
10994                       && elf_symtab_shndx (sec->owner) != 0)
10995                     max_sym_shndx_count = sym_count;
10996
10997                   if ((sec->flags & SEC_RELOC) != 0)
10998                     {
10999                       size_t ext_size = 0;
11000
11001                       if (esdi->rel.hdr != NULL)
11002                         ext_size = esdi->rel.hdr->sh_size;
11003                       if (esdi->rela.hdr != NULL)
11004                         ext_size += esdi->rela.hdr->sh_size;
11005
11006                       if (ext_size > max_external_reloc_size)
11007                         max_external_reloc_size = ext_size;
11008                       if (sec->reloc_count > max_internal_reloc_count)
11009                         max_internal_reloc_count = sec->reloc_count;
11010                     }
11011                 }
11012             }
11013
11014           if (reloc_count == 0)
11015             continue;
11016
11017           o->reloc_count += reloc_count;
11018
11019           if (p->type == bfd_indirect_link_order
11020               && (info->relocatable || info->emitrelocations))
11021             {
11022               if (esdi->rel.hdr)
11023                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11024               if (esdi->rela.hdr)
11025                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11026             }
11027           else
11028             {
11029               if (o->use_rela_p)
11030                 esdo->rela.count += reloc_count;
11031               else
11032                 esdo->rel.count += reloc_count;
11033             }
11034         }
11035
11036       if (o->reloc_count > 0)
11037         o->flags |= SEC_RELOC;
11038       else
11039         {
11040           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11041              set it (this is probably a bug) and if it is set
11042              assign_section_numbers will create a reloc section.  */
11043           o->flags &=~ SEC_RELOC;
11044         }
11045
11046       /* If the SEC_ALLOC flag is not set, force the section VMA to
11047          zero.  This is done in elf_fake_sections as well, but forcing
11048          the VMA to 0 here will ensure that relocs against these
11049          sections are handled correctly.  */
11050       if ((o->flags & SEC_ALLOC) == 0
11051           && ! o->user_set_vma)
11052         o->vma = 0;
11053     }
11054
11055   if (! info->relocatable && merged)
11056     elf_link_hash_traverse (elf_hash_table (info),
11057                             _bfd_elf_link_sec_merge_syms, abfd);
11058
11059   /* Figure out the file positions for everything but the symbol table
11060      and the relocs.  We set symcount to force assign_section_numbers
11061      to create a symbol table.  */
11062   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11063   BFD_ASSERT (! abfd->output_has_begun);
11064   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11065     goto error_return;
11066
11067   /* Set sizes, and assign file positions for reloc sections.  */
11068   for (o = abfd->sections; o != NULL; o = o->next)
11069     {
11070       struct bfd_elf_section_data *esdo = elf_section_data (o);
11071       if ((o->flags & SEC_RELOC) != 0)
11072         {
11073           if (esdo->rel.hdr
11074               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11075             goto error_return;
11076
11077           if (esdo->rela.hdr
11078               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11079             goto error_return;
11080         }
11081
11082       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11083          to count upwards while actually outputting the relocations.  */
11084       esdo->rel.count = 0;
11085       esdo->rela.count = 0;
11086
11087       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11088         {
11089           /* Cache the section contents so that they can be compressed
11090              later.  Use bfd_malloc since it will be freed by
11091              bfd_compress_section_contents.  */
11092           unsigned char *contents = esdo->this_hdr.contents;
11093           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11094             abort ();
11095           contents
11096             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11097           if (contents == NULL)
11098             goto error_return;
11099           esdo->this_hdr.contents = contents;
11100         }
11101     }
11102
11103   /* We have now assigned file positions for all the sections except
11104      .symtab, .strtab, and non-loaded reloc sections.  We start the
11105      .symtab section at the current file position, and write directly
11106      to it.  We build the .strtab section in memory.  */
11107   bfd_get_symcount (abfd) = 0;
11108   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11109   /* sh_name is set in prep_headers.  */
11110   symtab_hdr->sh_type = SHT_SYMTAB;
11111   /* sh_flags, sh_addr and sh_size all start off zero.  */
11112   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11113   /* sh_link is set in assign_section_numbers.  */
11114   /* sh_info is set below.  */
11115   /* sh_offset is set just below.  */
11116   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11117
11118   if (max_sym_count < 20)
11119     max_sym_count = 20;
11120   elf_hash_table (info)->strtabsize = max_sym_count;
11121   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11122   elf_hash_table (info)->strtab
11123     = (struct elf_sym_strtab *) bfd_malloc (amt);
11124   if (elf_hash_table (info)->strtab == NULL)
11125     goto error_return;
11126   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11127   flinfo.symshndxbuf
11128     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11129        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11130
11131   if (info->strip != strip_all || emit_relocs)
11132     {
11133       file_ptr off = elf_next_file_pos (abfd);
11134
11135       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11136
11137       /* Note that at this point elf_next_file_pos (abfd) is
11138          incorrect.  We do not yet know the size of the .symtab section.
11139          We correct next_file_pos below, after we do know the size.  */
11140
11141       /* Start writing out the symbol table.  The first symbol is always a
11142          dummy symbol.  */
11143       elfsym.st_value = 0;
11144       elfsym.st_size = 0;
11145       elfsym.st_info = 0;
11146       elfsym.st_other = 0;
11147       elfsym.st_shndx = SHN_UNDEF;
11148       elfsym.st_target_internal = 0;
11149       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11150                                      bfd_und_section_ptr, NULL) != 1)
11151         goto error_return;
11152
11153       /* Output a symbol for each section.  We output these even if we are
11154          discarding local symbols, since they are used for relocs.  These
11155          symbols have no names.  We store the index of each one in the
11156          index field of the section, so that we can find it again when
11157          outputting relocs.  */
11158
11159       elfsym.st_size = 0;
11160       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11161       elfsym.st_other = 0;
11162       elfsym.st_value = 0;
11163       elfsym.st_target_internal = 0;
11164       for (i = 1; i < elf_numsections (abfd); i++)
11165         {
11166           o = bfd_section_from_elf_index (abfd, i);
11167           if (o != NULL)
11168             {
11169               o->target_index = bfd_get_symcount (abfd);
11170               elfsym.st_shndx = i;
11171               if (!info->relocatable)
11172                 elfsym.st_value = o->vma;
11173               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11174                                              NULL) != 1)
11175                 goto error_return;
11176             }
11177         }
11178     }
11179
11180   /* Allocate some memory to hold information read in from the input
11181      files.  */
11182   if (max_contents_size != 0)
11183     {
11184       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11185       if (flinfo.contents == NULL)
11186         goto error_return;
11187     }
11188
11189   if (max_external_reloc_size != 0)
11190     {
11191       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11192       if (flinfo.external_relocs == NULL)
11193         goto error_return;
11194     }
11195
11196   if (max_internal_reloc_count != 0)
11197     {
11198       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11199       amt *= sizeof (Elf_Internal_Rela);
11200       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11201       if (flinfo.internal_relocs == NULL)
11202         goto error_return;
11203     }
11204
11205   if (max_sym_count != 0)
11206     {
11207       amt = max_sym_count * bed->s->sizeof_sym;
11208       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11209       if (flinfo.external_syms == NULL)
11210         goto error_return;
11211
11212       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11213       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11214       if (flinfo.internal_syms == NULL)
11215         goto error_return;
11216
11217       amt = max_sym_count * sizeof (long);
11218       flinfo.indices = (long int *) bfd_malloc (amt);
11219       if (flinfo.indices == NULL)
11220         goto error_return;
11221
11222       amt = max_sym_count * sizeof (asection *);
11223       flinfo.sections = (asection **) bfd_malloc (amt);
11224       if (flinfo.sections == NULL)
11225         goto error_return;
11226     }
11227
11228   if (max_sym_shndx_count != 0)
11229     {
11230       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11231       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11232       if (flinfo.locsym_shndx == NULL)
11233         goto error_return;
11234     }
11235
11236   if (elf_hash_table (info)->tls_sec)
11237     {
11238       bfd_vma base, end = 0;
11239       asection *sec;
11240
11241       for (sec = elf_hash_table (info)->tls_sec;
11242            sec && (sec->flags & SEC_THREAD_LOCAL);
11243            sec = sec->next)
11244         {
11245           bfd_size_type size = sec->size;
11246
11247           if (size == 0
11248               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11249             {
11250               struct bfd_link_order *ord = sec->map_tail.link_order;
11251
11252               if (ord != NULL)
11253                 size = ord->offset + ord->size;
11254             }
11255           end = sec->vma + size;
11256         }
11257       base = elf_hash_table (info)->tls_sec->vma;
11258       /* Only align end of TLS section if static TLS doesn't have special
11259          alignment requirements.  */
11260       if (bed->static_tls_alignment == 1)
11261         end = align_power (end,
11262                            elf_hash_table (info)->tls_sec->alignment_power);
11263       elf_hash_table (info)->tls_size = end - base;
11264     }
11265
11266   /* Reorder SHF_LINK_ORDER sections.  */
11267   for (o = abfd->sections; o != NULL; o = o->next)
11268     {
11269       if (!elf_fixup_link_order (abfd, o))
11270         return FALSE;
11271     }
11272
11273   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11274     return FALSE;
11275
11276   /* Since ELF permits relocations to be against local symbols, we
11277      must have the local symbols available when we do the relocations.
11278      Since we would rather only read the local symbols once, and we
11279      would rather not keep them in memory, we handle all the
11280      relocations for a single input file at the same time.
11281
11282      Unfortunately, there is no way to know the total number of local
11283      symbols until we have seen all of them, and the local symbol
11284      indices precede the global symbol indices.  This means that when
11285      we are generating relocatable output, and we see a reloc against
11286      a global symbol, we can not know the symbol index until we have
11287      finished examining all the local symbols to see which ones we are
11288      going to output.  To deal with this, we keep the relocations in
11289      memory, and don't output them until the end of the link.  This is
11290      an unfortunate waste of memory, but I don't see a good way around
11291      it.  Fortunately, it only happens when performing a relocatable
11292      link, which is not the common case.  FIXME: If keep_memory is set
11293      we could write the relocs out and then read them again; I don't
11294      know how bad the memory loss will be.  */
11295
11296   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11297     sub->output_has_begun = FALSE;
11298   for (o = abfd->sections; o != NULL; o = o->next)
11299     {
11300       for (p = o->map_head.link_order; p != NULL; p = p->next)
11301         {
11302           if (p->type == bfd_indirect_link_order
11303               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11304                   == bfd_target_elf_flavour)
11305               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11306             {
11307               if (! sub->output_has_begun)
11308                 {
11309                   if (! elf_link_input_bfd (&flinfo, sub))
11310                     goto error_return;
11311                   sub->output_has_begun = TRUE;
11312                 }
11313             }
11314           else if (p->type == bfd_section_reloc_link_order
11315                    || p->type == bfd_symbol_reloc_link_order)
11316             {
11317               if (! elf_reloc_link_order (abfd, info, o, p))
11318                 goto error_return;
11319             }
11320           else
11321             {
11322               if (! _bfd_default_link_order (abfd, info, o, p))
11323                 {
11324                   if (p->type == bfd_indirect_link_order
11325                       && (bfd_get_flavour (sub)
11326                           == bfd_target_elf_flavour)
11327                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11328                           != bed->s->elfclass))
11329                     {
11330                       const char *iclass, *oclass;
11331
11332                       if (bed->s->elfclass == ELFCLASS64)
11333                         {
11334                           iclass = "ELFCLASS32";
11335                           oclass = "ELFCLASS64";
11336                         }
11337                       else
11338                         {
11339                           iclass = "ELFCLASS64";
11340                           oclass = "ELFCLASS32";
11341                         }
11342
11343                       bfd_set_error (bfd_error_wrong_format);
11344                       (*_bfd_error_handler)
11345                         (_("%B: file class %s incompatible with %s"),
11346                          sub, iclass, oclass);
11347                     }
11348
11349                   goto error_return;
11350                 }
11351             }
11352         }
11353     }
11354
11355   /* Free symbol buffer if needed.  */
11356   if (!info->reduce_memory_overheads)
11357     {
11358       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11359         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11360             && elf_tdata (sub)->symbuf)
11361           {
11362             free (elf_tdata (sub)->symbuf);
11363             elf_tdata (sub)->symbuf = NULL;
11364           }
11365     }
11366
11367   /* Output any global symbols that got converted to local in a
11368      version script or due to symbol visibility.  We do this in a
11369      separate step since ELF requires all local symbols to appear
11370      prior to any global symbols.  FIXME: We should only do this if
11371      some global symbols were, in fact, converted to become local.
11372      FIXME: Will this work correctly with the Irix 5 linker?  */
11373   eoinfo.failed = FALSE;
11374   eoinfo.flinfo = &flinfo;
11375   eoinfo.localsyms = TRUE;
11376   eoinfo.file_sym_done = FALSE;
11377   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11378   if (eoinfo.failed)
11379     return FALSE;
11380
11381   /* If backend needs to output some local symbols not present in the hash
11382      table, do it now.  */
11383   if (bed->elf_backend_output_arch_local_syms
11384       && (info->strip != strip_all || emit_relocs))
11385     {
11386       typedef int (*out_sym_func)
11387         (void *, const char *, Elf_Internal_Sym *, asection *,
11388          struct elf_link_hash_entry *);
11389
11390       if (! ((*bed->elf_backend_output_arch_local_syms)
11391              (abfd, info, &flinfo,
11392               (out_sym_func) elf_link_output_symstrtab)))
11393         return FALSE;
11394     }
11395
11396   /* That wrote out all the local symbols.  Finish up the symbol table
11397      with the global symbols. Even if we want to strip everything we
11398      can, we still need to deal with those global symbols that got
11399      converted to local in a version script.  */
11400
11401   /* The sh_info field records the index of the first non local symbol.  */
11402   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11403
11404   if (dynamic
11405       && flinfo.dynsym_sec != NULL
11406       && flinfo.dynsym_sec->output_section != bfd_abs_section_ptr)
11407     {
11408       Elf_Internal_Sym sym;
11409       bfd_byte *dynsym = flinfo.dynsym_sec->contents;
11410       long last_local = 0;
11411
11412       /* Write out the section symbols for the output sections.  */
11413       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
11414         {
11415           asection *s;
11416
11417           sym.st_size = 0;
11418           sym.st_name = 0;
11419           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11420           sym.st_other = 0;
11421           sym.st_target_internal = 0;
11422
11423           for (s = abfd->sections; s != NULL; s = s->next)
11424             {
11425               int indx;
11426               bfd_byte *dest;
11427               long dynindx;
11428
11429               dynindx = elf_section_data (s)->dynindx;
11430               if (dynindx <= 0)
11431                 continue;
11432               indx = elf_section_data (s)->this_idx;
11433               BFD_ASSERT (indx > 0);
11434               sym.st_shndx = indx;
11435               if (! check_dynsym (abfd, &sym))
11436                 return FALSE;
11437               sym.st_value = s->vma;
11438               dest = dynsym + dynindx * bed->s->sizeof_sym;
11439               if (last_local < dynindx)
11440                 last_local = dynindx;
11441               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11442             }
11443         }
11444
11445       /* Write out the local dynsyms.  */
11446       if (elf_hash_table (info)->dynlocal)
11447         {
11448           struct elf_link_local_dynamic_entry *e;
11449           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11450             {
11451               asection *s;
11452               bfd_byte *dest;
11453
11454               /* Copy the internal symbol and turn off visibility.
11455                  Note that we saved a word of storage and overwrote
11456                  the original st_name with the dynstr_index.  */
11457               sym = e->isym;
11458               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11459
11460               s = bfd_section_from_elf_index (e->input_bfd,
11461                                               e->isym.st_shndx);
11462               if (s != NULL)
11463                 {
11464                   sym.st_shndx =
11465                     elf_section_data (s->output_section)->this_idx;
11466                   if (! check_dynsym (abfd, &sym))
11467                     return FALSE;
11468                   sym.st_value = (s->output_section->vma
11469                                   + s->output_offset
11470                                   + e->isym.st_value);
11471                 }
11472
11473               if (last_local < e->dynindx)
11474                 last_local = e->dynindx;
11475
11476               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11477               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11478             }
11479         }
11480
11481       elf_section_data (flinfo.dynsym_sec->output_section)->this_hdr.sh_info =
11482         last_local + 1;
11483     }
11484
11485   /* We get the global symbols from the hash table.  */
11486   eoinfo.failed = FALSE;
11487   eoinfo.localsyms = FALSE;
11488   eoinfo.flinfo = &flinfo;
11489   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11490   if (eoinfo.failed)
11491     return FALSE;
11492
11493   /* If backend needs to output some symbols not present in the hash
11494      table, do it now.  */
11495   if (bed->elf_backend_output_arch_syms
11496       && (info->strip != strip_all || emit_relocs))
11497     {
11498       typedef int (*out_sym_func)
11499         (void *, const char *, Elf_Internal_Sym *, asection *,
11500          struct elf_link_hash_entry *);
11501
11502       if (! ((*bed->elf_backend_output_arch_syms)
11503              (abfd, info, &flinfo,
11504               (out_sym_func) elf_link_output_symstrtab)))
11505         return FALSE;
11506     }
11507
11508   /* Finalize the .strtab section.  */
11509   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11510
11511   /* Swap out the .strtab section. */
11512   if (!elf_link_swap_symbols_out (&flinfo))
11513     return FALSE;
11514
11515   /* Now we know the size of the symtab section.  */
11516   if (bfd_get_symcount (abfd) > 0)
11517     {
11518       /* Finish up and write out the symbol string table (.strtab)
11519          section.  */
11520       Elf_Internal_Shdr *symstrtab_hdr;
11521       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11522
11523       symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
11524       if (symtab_shndx_hdr->sh_name != 0)
11525         {
11526           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11527           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11528           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11529           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11530           symtab_shndx_hdr->sh_size = amt;
11531
11532           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11533                                                            off, TRUE);
11534
11535           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11536               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11537             return FALSE;
11538         }
11539
11540       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11541       /* sh_name was set in prep_headers.  */
11542       symstrtab_hdr->sh_type = SHT_STRTAB;
11543       symstrtab_hdr->sh_flags = 0;
11544       symstrtab_hdr->sh_addr = 0;
11545       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11546       symstrtab_hdr->sh_entsize = 0;
11547       symstrtab_hdr->sh_link = 0;
11548       symstrtab_hdr->sh_info = 0;
11549       /* sh_offset is set just below.  */
11550       symstrtab_hdr->sh_addralign = 1;
11551
11552       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11553                                                        off, TRUE);
11554       elf_next_file_pos (abfd) = off;
11555
11556       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11557           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11558         return FALSE;
11559     }
11560
11561   /* Adjust the relocs to have the correct symbol indices.  */
11562   for (o = abfd->sections; o != NULL; o = o->next)
11563     {
11564       struct bfd_elf_section_data *esdo = elf_section_data (o);
11565       bfd_boolean sort;
11566       if ((o->flags & SEC_RELOC) == 0)
11567         continue;
11568
11569       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11570       if (esdo->rel.hdr != NULL)
11571         elf_link_adjust_relocs (abfd, &esdo->rel, sort);
11572       if (esdo->rela.hdr != NULL)
11573         elf_link_adjust_relocs (abfd, &esdo->rela, sort);
11574
11575       /* Set the reloc_count field to 0 to prevent write_relocs from
11576          trying to swap the relocs out itself.  */
11577       o->reloc_count = 0;
11578     }
11579
11580   if (dynamic && info->combreloc && dynobj != NULL)
11581     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11582
11583   /* If we are linking against a dynamic object, or generating a
11584      shared library, finish up the dynamic linking information.  */
11585   if (dynamic)
11586     {
11587       bfd_byte *dyncon, *dynconend;
11588
11589       /* Fix up .dynamic entries.  */
11590       o = bfd_get_linker_section (dynobj, ".dynamic");
11591       BFD_ASSERT (o != NULL);
11592
11593       dyncon = o->contents;
11594       dynconend = o->contents + o->size;
11595       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11596         {
11597           Elf_Internal_Dyn dyn;
11598           const char *name;
11599           unsigned int type;
11600
11601           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11602
11603           switch (dyn.d_tag)
11604             {
11605             default:
11606               continue;
11607             case DT_NULL:
11608               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11609                 {
11610                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11611                     {
11612                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11613                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11614                     default: continue;
11615                     }
11616                   dyn.d_un.d_val = relativecount;
11617                   relativecount = 0;
11618                   break;
11619                 }
11620               continue;
11621
11622             case DT_INIT:
11623               name = info->init_function;
11624               goto get_sym;
11625             case DT_FINI:
11626               name = info->fini_function;
11627             get_sym:
11628               {
11629                 struct elf_link_hash_entry *h;
11630
11631                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11632                                           FALSE, FALSE, TRUE);
11633                 if (h != NULL
11634                     && (h->root.type == bfd_link_hash_defined
11635                         || h->root.type == bfd_link_hash_defweak))
11636                   {
11637                     dyn.d_un.d_ptr = h->root.u.def.value;
11638                     o = h->root.u.def.section;
11639                     if (o->output_section != NULL)
11640                       dyn.d_un.d_ptr += (o->output_section->vma
11641                                          + o->output_offset);
11642                     else
11643                       {
11644                         /* The symbol is imported from another shared
11645                            library and does not apply to this one.  */
11646                         dyn.d_un.d_ptr = 0;
11647                       }
11648                     break;
11649                   }
11650               }
11651               continue;
11652
11653             case DT_PREINIT_ARRAYSZ:
11654               name = ".preinit_array";
11655               goto get_size;
11656             case DT_INIT_ARRAYSZ:
11657               name = ".init_array";
11658               goto get_size;
11659             case DT_FINI_ARRAYSZ:
11660               name = ".fini_array";
11661             get_size:
11662               o = bfd_get_section_by_name (abfd, name);
11663               if (o == NULL)
11664                 {
11665                   (*_bfd_error_handler)
11666                     (_("%B: could not find output section %s"), abfd, name);
11667                   goto error_return;
11668                 }
11669               if (o->size == 0)
11670                 (*_bfd_error_handler)
11671                   (_("warning: %s section has zero size"), name);
11672               dyn.d_un.d_val = o->size;
11673               break;
11674
11675             case DT_PREINIT_ARRAY:
11676               name = ".preinit_array";
11677               goto get_vma;
11678             case DT_INIT_ARRAY:
11679               name = ".init_array";
11680               goto get_vma;
11681             case DT_FINI_ARRAY:
11682               name = ".fini_array";
11683               goto get_vma;
11684
11685             case DT_HASH:
11686               name = ".hash";
11687               goto get_vma;
11688             case DT_GNU_HASH:
11689               name = ".gnu.hash";
11690               goto get_vma;
11691             case DT_STRTAB:
11692               name = ".dynstr";
11693               goto get_vma;
11694             case DT_SYMTAB:
11695               name = ".dynsym";
11696               goto get_vma;
11697             case DT_VERDEF:
11698               name = ".gnu.version_d";
11699               goto get_vma;
11700             case DT_VERNEED:
11701               name = ".gnu.version_r";
11702               goto get_vma;
11703             case DT_VERSYM:
11704               name = ".gnu.version";
11705             get_vma:
11706               o = bfd_get_section_by_name (abfd, name);
11707               if (o == NULL)
11708                 {
11709                   (*_bfd_error_handler)
11710                     (_("%B: could not find output section %s"), abfd, name);
11711                   goto error_return;
11712                 }
11713               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11714                 {
11715                   (*_bfd_error_handler)
11716                     (_("warning: section '%s' is being made into a note"), name);
11717                   bfd_set_error (bfd_error_nonrepresentable_section);
11718                   goto error_return;
11719                 }
11720               dyn.d_un.d_ptr = o->vma;
11721               break;
11722
11723             case DT_REL:
11724             case DT_RELA:
11725             case DT_RELSZ:
11726             case DT_RELASZ:
11727               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11728                 type = SHT_REL;
11729               else
11730                 type = SHT_RELA;
11731               dyn.d_un.d_val = 0;
11732               dyn.d_un.d_ptr = 0;
11733               for (i = 1; i < elf_numsections (abfd); i++)
11734                 {
11735                   Elf_Internal_Shdr *hdr;
11736
11737                   hdr = elf_elfsections (abfd)[i];
11738                   if (hdr->sh_type == type
11739                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11740                     {
11741                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11742                         dyn.d_un.d_val += hdr->sh_size;
11743                       else
11744                         {
11745                           if (dyn.d_un.d_ptr == 0
11746                               || hdr->sh_addr < dyn.d_un.d_ptr)
11747                             dyn.d_un.d_ptr = hdr->sh_addr;
11748                         }
11749                     }
11750                 }
11751               break;
11752             }
11753           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11754         }
11755     }
11756
11757   /* If we have created any dynamic sections, then output them.  */
11758   if (dynobj != NULL)
11759     {
11760       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11761         goto error_return;
11762
11763       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11764       if (((info->warn_shared_textrel && info->shared)
11765            || info->error_textrel)
11766           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11767         {
11768           bfd_byte *dyncon, *dynconend;
11769
11770           dyncon = o->contents;
11771           dynconend = o->contents + o->size;
11772           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11773             {
11774               Elf_Internal_Dyn dyn;
11775
11776               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11777
11778               if (dyn.d_tag == DT_TEXTREL)
11779                 {
11780                   if (info->error_textrel)
11781                     info->callbacks->einfo
11782                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11783                   else
11784                     info->callbacks->einfo
11785                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11786                   break;
11787                 }
11788             }
11789         }
11790
11791       for (o = dynobj->sections; o != NULL; o = o->next)
11792         {
11793           if ((o->flags & SEC_HAS_CONTENTS) == 0
11794               || o->size == 0
11795               || o->output_section == bfd_abs_section_ptr)
11796             continue;
11797           if ((o->flags & SEC_LINKER_CREATED) == 0)
11798             {
11799               /* At this point, we are only interested in sections
11800                  created by _bfd_elf_link_create_dynamic_sections.  */
11801               continue;
11802             }
11803           if (elf_hash_table (info)->stab_info.stabstr == o)
11804             continue;
11805           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11806             continue;
11807           if (strcmp (o->name, ".dynstr") != 0)
11808             {
11809               /* FIXME: octets_per_byte.  */
11810               if (! bfd_set_section_contents (abfd, o->output_section,
11811                                               o->contents,
11812                                               (file_ptr) o->output_offset,
11813                                               o->size))
11814                 goto error_return;
11815             }
11816           else
11817             {
11818               /* The contents of the .dynstr section are actually in a
11819                  stringtab.  */
11820               file_ptr off;
11821
11822               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11823               if (bfd_seek (abfd, off, SEEK_SET) != 0
11824                   || ! _bfd_elf_strtab_emit (abfd,
11825                                              elf_hash_table (info)->dynstr))
11826                 goto error_return;
11827             }
11828         }
11829     }
11830
11831   if (info->relocatable)
11832     {
11833       bfd_boolean failed = FALSE;
11834
11835       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11836       if (failed)
11837         goto error_return;
11838     }
11839
11840   /* If we have optimized stabs strings, output them.  */
11841   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11842     {
11843       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11844         goto error_return;
11845     }
11846
11847   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11848     goto error_return;
11849
11850   elf_final_link_free (abfd, &flinfo);
11851
11852   elf_linker (abfd) = TRUE;
11853
11854   if (attr_section)
11855     {
11856       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11857       if (contents == NULL)
11858         return FALSE;   /* Bail out and fail.  */
11859       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11860       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11861       free (contents);
11862     }
11863
11864   return TRUE;
11865
11866  error_return:
11867   elf_final_link_free (abfd, &flinfo);
11868   return FALSE;
11869 }
11870 \f
11871 /* Initialize COOKIE for input bfd ABFD.  */
11872
11873 static bfd_boolean
11874 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11875                    struct bfd_link_info *info, bfd *abfd)
11876 {
11877   Elf_Internal_Shdr *symtab_hdr;
11878   const struct elf_backend_data *bed;
11879
11880   bed = get_elf_backend_data (abfd);
11881   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11882
11883   cookie->abfd = abfd;
11884   cookie->sym_hashes = elf_sym_hashes (abfd);
11885   cookie->bad_symtab = elf_bad_symtab (abfd);
11886   if (cookie->bad_symtab)
11887     {
11888       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11889       cookie->extsymoff = 0;
11890     }
11891   else
11892     {
11893       cookie->locsymcount = symtab_hdr->sh_info;
11894       cookie->extsymoff = symtab_hdr->sh_info;
11895     }
11896
11897   if (bed->s->arch_size == 32)
11898     cookie->r_sym_shift = 8;
11899   else
11900     cookie->r_sym_shift = 32;
11901
11902   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11903   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11904     {
11905       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11906                                               cookie->locsymcount, 0,
11907                                               NULL, NULL, NULL);
11908       if (cookie->locsyms == NULL)
11909         {
11910           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11911           return FALSE;
11912         }
11913       if (info->keep_memory)
11914         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11915     }
11916   return TRUE;
11917 }
11918
11919 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11920
11921 static void
11922 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11923 {
11924   Elf_Internal_Shdr *symtab_hdr;
11925
11926   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11927   if (cookie->locsyms != NULL
11928       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11929     free (cookie->locsyms);
11930 }
11931
11932 /* Initialize the relocation information in COOKIE for input section SEC
11933    of input bfd ABFD.  */
11934
11935 static bfd_boolean
11936 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11937                         struct bfd_link_info *info, bfd *abfd,
11938                         asection *sec)
11939 {
11940   const struct elf_backend_data *bed;
11941
11942   if (sec->reloc_count == 0)
11943     {
11944       cookie->rels = NULL;
11945       cookie->relend = NULL;
11946     }
11947   else
11948     {
11949       bed = get_elf_backend_data (abfd);
11950
11951       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11952                                                 info->keep_memory);
11953       if (cookie->rels == NULL)
11954         return FALSE;
11955       cookie->rel = cookie->rels;
11956       cookie->relend = (cookie->rels
11957                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11958     }
11959   cookie->rel = cookie->rels;
11960   return TRUE;
11961 }
11962
11963 /* Free the memory allocated by init_reloc_cookie_rels,
11964    if appropriate.  */
11965
11966 static void
11967 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11968                         asection *sec)
11969 {
11970   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11971     free (cookie->rels);
11972 }
11973
11974 /* Initialize the whole of COOKIE for input section SEC.  */
11975
11976 static bfd_boolean
11977 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11978                                struct bfd_link_info *info,
11979                                asection *sec)
11980 {
11981   if (!init_reloc_cookie (cookie, info, sec->owner))
11982     goto error1;
11983   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11984     goto error2;
11985   return TRUE;
11986
11987  error2:
11988   fini_reloc_cookie (cookie, sec->owner);
11989  error1:
11990   return FALSE;
11991 }
11992
11993 /* Free the memory allocated by init_reloc_cookie_for_section,
11994    if appropriate.  */
11995
11996 static void
11997 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11998                                asection *sec)
11999 {
12000   fini_reloc_cookie_rels (cookie, sec);
12001   fini_reloc_cookie (cookie, sec->owner);
12002 }
12003 \f
12004 /* Garbage collect unused sections.  */
12005
12006 /* Default gc_mark_hook.  */
12007
12008 asection *
12009 _bfd_elf_gc_mark_hook (asection *sec,
12010                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12011                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12012                        struct elf_link_hash_entry *h,
12013                        Elf_Internal_Sym *sym)
12014 {
12015   const char *sec_name;
12016
12017   if (h != NULL)
12018     {
12019       switch (h->root.type)
12020         {
12021         case bfd_link_hash_defined:
12022         case bfd_link_hash_defweak:
12023           return h->root.u.def.section;
12024
12025         case bfd_link_hash_common:
12026           return h->root.u.c.p->section;
12027
12028         case bfd_link_hash_undefined:
12029         case bfd_link_hash_undefweak:
12030           /* To work around a glibc bug, keep all XXX input sections
12031              when there is an as yet undefined reference to __start_XXX
12032              or __stop_XXX symbols.  The linker will later define such
12033              symbols for orphan input sections that have a name
12034              representable as a C identifier.  */
12035           if (strncmp (h->root.root.string, "__start_", 8) == 0)
12036             sec_name = h->root.root.string + 8;
12037           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12038             sec_name = h->root.root.string + 7;
12039           else
12040             sec_name = NULL;
12041
12042           if (sec_name && *sec_name != '\0')
12043             {
12044               bfd *i;
12045
12046               for (i = info->input_bfds; i; i = i->link.next)
12047                 {
12048                   sec = bfd_get_section_by_name (i, sec_name);
12049                   if (sec)
12050                     sec->flags |= SEC_KEEP;
12051                 }
12052             }
12053           break;
12054
12055         default:
12056           break;
12057         }
12058     }
12059   else
12060     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12061
12062   return NULL;
12063 }
12064
12065 /* COOKIE->rel describes a relocation against section SEC, which is
12066    a section we've decided to keep.  Return the section that contains
12067    the relocation symbol, or NULL if no section contains it.  */
12068
12069 asection *
12070 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12071                        elf_gc_mark_hook_fn gc_mark_hook,
12072                        struct elf_reloc_cookie *cookie)
12073 {
12074   unsigned long r_symndx;
12075   struct elf_link_hash_entry *h;
12076
12077   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12078   if (r_symndx == STN_UNDEF)
12079     return NULL;
12080
12081   if (r_symndx >= cookie->locsymcount
12082       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12083     {
12084       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12085       if (h == NULL)
12086         {
12087           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12088                                   sec->owner);
12089           return NULL;
12090         }
12091       while (h->root.type == bfd_link_hash_indirect
12092              || h->root.type == bfd_link_hash_warning)
12093         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12094       h->mark = 1;
12095       /* If this symbol is weak and there is a non-weak definition, we
12096          keep the non-weak definition because many backends put
12097          dynamic reloc info on the non-weak definition for code
12098          handling copy relocs.  */
12099       if (h->u.weakdef != NULL)
12100         h->u.weakdef->mark = 1;
12101       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12102     }
12103
12104   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12105                           &cookie->locsyms[r_symndx]);
12106 }
12107
12108 /* COOKIE->rel describes a relocation against section SEC, which is
12109    a section we've decided to keep.  Mark the section that contains
12110    the relocation symbol.  */
12111
12112 bfd_boolean
12113 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12114                         asection *sec,
12115                         elf_gc_mark_hook_fn gc_mark_hook,
12116                         struct elf_reloc_cookie *cookie)
12117 {
12118   asection *rsec;
12119
12120   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
12121   if (rsec && !rsec->gc_mark)
12122     {
12123       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12124           || (rsec->owner->flags & DYNAMIC) != 0)
12125         rsec->gc_mark = 1;
12126       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12127         return FALSE;
12128     }
12129   return TRUE;
12130 }
12131
12132 /* The mark phase of garbage collection.  For a given section, mark
12133    it and any sections in this section's group, and all the sections
12134    which define symbols to which it refers.  */
12135
12136 bfd_boolean
12137 _bfd_elf_gc_mark (struct bfd_link_info *info,
12138                   asection *sec,
12139                   elf_gc_mark_hook_fn gc_mark_hook)
12140 {
12141   bfd_boolean ret;
12142   asection *group_sec, *eh_frame;
12143
12144   sec->gc_mark = 1;
12145
12146   /* Mark all the sections in the group.  */
12147   group_sec = elf_section_data (sec)->next_in_group;
12148   if (group_sec && !group_sec->gc_mark)
12149     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12150       return FALSE;
12151
12152   /* Look through the section relocs.  */
12153   ret = TRUE;
12154   eh_frame = elf_eh_frame_section (sec->owner);
12155   if ((sec->flags & SEC_RELOC) != 0
12156       && sec->reloc_count > 0
12157       && sec != eh_frame)
12158     {
12159       struct elf_reloc_cookie cookie;
12160
12161       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12162         ret = FALSE;
12163       else
12164         {
12165           for (; cookie.rel < cookie.relend; cookie.rel++)
12166             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12167               {
12168                 ret = FALSE;
12169                 break;
12170               }
12171           fini_reloc_cookie_for_section (&cookie, sec);
12172         }
12173     }
12174
12175   if (ret && eh_frame && elf_fde_list (sec))
12176     {
12177       struct elf_reloc_cookie cookie;
12178
12179       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12180         ret = FALSE;
12181       else
12182         {
12183           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12184                                       gc_mark_hook, &cookie))
12185             ret = FALSE;
12186           fini_reloc_cookie_for_section (&cookie, eh_frame);
12187         }
12188     }
12189
12190   eh_frame = elf_section_eh_frame_entry (sec);
12191   if (ret && eh_frame && !eh_frame->gc_mark)
12192     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12193       ret = FALSE;
12194
12195   return ret;
12196 }
12197
12198 /* Scan and mark sections in a special or debug section group.  */
12199
12200 static void
12201 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12202 {
12203   /* Point to first section of section group.  */
12204   asection *ssec;
12205   /* Used to iterate the section group.  */
12206   asection *msec;
12207
12208   bfd_boolean is_special_grp = TRUE;
12209   bfd_boolean is_debug_grp = TRUE;
12210
12211   /* First scan to see if group contains any section other than debug
12212      and special section.  */
12213   ssec = msec = elf_next_in_group (grp);
12214   do
12215     {
12216       if ((msec->flags & SEC_DEBUGGING) == 0)
12217         is_debug_grp = FALSE;
12218
12219       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12220         is_special_grp = FALSE;
12221
12222       msec = elf_next_in_group (msec);
12223     }
12224   while (msec != ssec);
12225
12226   /* If this is a pure debug section group or pure special section group,
12227      keep all sections in this group.  */
12228   if (is_debug_grp || is_special_grp)
12229     {
12230       do
12231         {
12232           msec->gc_mark = 1;
12233           msec = elf_next_in_group (msec);
12234         }
12235       while (msec != ssec);
12236     }
12237 }
12238
12239 /* Keep debug and special sections.  */
12240
12241 bfd_boolean
12242 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12243                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12244 {
12245   bfd *ibfd;
12246
12247   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12248     {
12249       asection *isec;
12250       bfd_boolean some_kept;
12251       bfd_boolean debug_frag_seen;
12252
12253       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12254         continue;
12255
12256       /* Ensure all linker created sections are kept,
12257          see if any other section is already marked,
12258          and note if we have any fragmented debug sections.  */
12259       debug_frag_seen = some_kept = FALSE;
12260       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12261         {
12262           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12263             isec->gc_mark = 1;
12264           else if (isec->gc_mark)
12265             some_kept = TRUE;
12266
12267           if (debug_frag_seen == FALSE
12268               && (isec->flags & SEC_DEBUGGING)
12269               && CONST_STRNEQ (isec->name, ".debug_line."))
12270             debug_frag_seen = TRUE;
12271         }
12272
12273       /* If no section in this file will be kept, then we can
12274          toss out the debug and special sections.  */
12275       if (!some_kept)
12276         continue;
12277
12278       /* Keep debug and special sections like .comment when they are
12279          not part of a group.  Also keep section groups that contain
12280          just debug sections or special sections.  */
12281       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12282         {
12283           if ((isec->flags & SEC_GROUP) != 0)
12284             _bfd_elf_gc_mark_debug_special_section_group (isec);
12285           else if (((isec->flags & SEC_DEBUGGING) != 0
12286                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12287                    && elf_next_in_group (isec) == NULL)
12288             isec->gc_mark = 1;
12289         }
12290
12291       if (! debug_frag_seen)
12292         continue;
12293
12294       /* Look for CODE sections which are going to be discarded,
12295          and find and discard any fragmented debug sections which
12296          are associated with that code section.  */
12297       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12298         if ((isec->flags & SEC_CODE) != 0
12299             && isec->gc_mark == 0)
12300           {
12301             unsigned int ilen;
12302             asection *dsec;
12303
12304             ilen = strlen (isec->name);
12305
12306             /* Association is determined by the name of the debug section
12307                containing the name of the code section as a suffix.  For
12308                example .debug_line.text.foo is a debug section associated
12309                with .text.foo.  */
12310             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12311               {
12312                 unsigned int dlen;
12313
12314                 if (dsec->gc_mark == 0
12315                     || (dsec->flags & SEC_DEBUGGING) == 0)
12316                   continue;
12317
12318                 dlen = strlen (dsec->name);
12319
12320                 if (dlen > ilen
12321                     && strncmp (dsec->name + (dlen - ilen),
12322                                 isec->name, ilen) == 0)
12323                   {
12324                     dsec->gc_mark = 0;
12325                   }
12326               }
12327           }
12328     }
12329   return TRUE;
12330 }
12331
12332 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12333
12334 struct elf_gc_sweep_symbol_info
12335 {
12336   struct bfd_link_info *info;
12337   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12338                        bfd_boolean);
12339 };
12340
12341 static bfd_boolean
12342 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12343 {
12344   if (!h->mark
12345       && (((h->root.type == bfd_link_hash_defined
12346             || h->root.type == bfd_link_hash_defweak)
12347            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12348                 && h->root.u.def.section->gc_mark))
12349           || h->root.type == bfd_link_hash_undefined
12350           || h->root.type == bfd_link_hash_undefweak))
12351     {
12352       struct elf_gc_sweep_symbol_info *inf;
12353
12354       inf = (struct elf_gc_sweep_symbol_info *) data;
12355       (*inf->hide_symbol) (inf->info, h, TRUE);
12356       h->def_regular = 0;
12357       h->ref_regular = 0;
12358       h->ref_regular_nonweak = 0;
12359     }
12360
12361   return TRUE;
12362 }
12363
12364 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12365
12366 typedef bfd_boolean (*gc_sweep_hook_fn)
12367   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12368
12369 static bfd_boolean
12370 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12371 {
12372   bfd *sub;
12373   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12374   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12375   unsigned long section_sym_count;
12376   struct elf_gc_sweep_symbol_info sweep_info;
12377
12378   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12379     {
12380       asection *o;
12381
12382       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12383           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12384         continue;
12385
12386       for (o = sub->sections; o != NULL; o = o->next)
12387         {
12388           /* When any section in a section group is kept, we keep all
12389              sections in the section group.  If the first member of
12390              the section group is excluded, we will also exclude the
12391              group section.  */
12392           if (o->flags & SEC_GROUP)
12393             {
12394               asection *first = elf_next_in_group (o);
12395               o->gc_mark = first->gc_mark;
12396             }
12397
12398           if (o->gc_mark)
12399             continue;
12400
12401           /* Skip sweeping sections already excluded.  */
12402           if (o->flags & SEC_EXCLUDE)
12403             continue;
12404
12405           /* Since this is early in the link process, it is simple
12406              to remove a section from the output.  */
12407           o->flags |= SEC_EXCLUDE;
12408
12409           if (info->print_gc_sections && o->size != 0)
12410             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12411
12412           /* But we also have to update some of the relocation
12413              info we collected before.  */
12414           if (gc_sweep_hook
12415               && (o->flags & SEC_RELOC) != 0
12416               && o->reloc_count != 0
12417               && !((info->strip == strip_all || info->strip == strip_debugger)
12418                    && (o->flags & SEC_DEBUGGING) != 0)
12419               && !bfd_is_abs_section (o->output_section))
12420             {
12421               Elf_Internal_Rela *internal_relocs;
12422               bfd_boolean r;
12423
12424               internal_relocs
12425                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12426                                              info->keep_memory);
12427               if (internal_relocs == NULL)
12428                 return FALSE;
12429
12430               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12431
12432               if (elf_section_data (o)->relocs != internal_relocs)
12433                 free (internal_relocs);
12434
12435               if (!r)
12436                 return FALSE;
12437             }
12438         }
12439     }
12440
12441   /* Remove the symbols that were in the swept sections from the dynamic
12442      symbol table.  GCFIXME: Anyone know how to get them out of the
12443      static symbol table as well?  */
12444   sweep_info.info = info;
12445   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12446   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12447                           &sweep_info);
12448
12449   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12450   return TRUE;
12451 }
12452
12453 /* Propagate collected vtable information.  This is called through
12454    elf_link_hash_traverse.  */
12455
12456 static bfd_boolean
12457 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12458 {
12459   /* Those that are not vtables.  */
12460   if (h->vtable == NULL || h->vtable->parent == NULL)
12461     return TRUE;
12462
12463   /* Those vtables that do not have parents, we cannot merge.  */
12464   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12465     return TRUE;
12466
12467   /* If we've already been done, exit.  */
12468   if (h->vtable->used && h->vtable->used[-1])
12469     return TRUE;
12470
12471   /* Make sure the parent's table is up to date.  */
12472   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12473
12474   if (h->vtable->used == NULL)
12475     {
12476       /* None of this table's entries were referenced.  Re-use the
12477          parent's table.  */
12478       h->vtable->used = h->vtable->parent->vtable->used;
12479       h->vtable->size = h->vtable->parent->vtable->size;
12480     }
12481   else
12482     {
12483       size_t n;
12484       bfd_boolean *cu, *pu;
12485
12486       /* Or the parent's entries into ours.  */
12487       cu = h->vtable->used;
12488       cu[-1] = TRUE;
12489       pu = h->vtable->parent->vtable->used;
12490       if (pu != NULL)
12491         {
12492           const struct elf_backend_data *bed;
12493           unsigned int log_file_align;
12494
12495           bed = get_elf_backend_data (h->root.u.def.section->owner);
12496           log_file_align = bed->s->log_file_align;
12497           n = h->vtable->parent->vtable->size >> log_file_align;
12498           while (n--)
12499             {
12500               if (*pu)
12501                 *cu = TRUE;
12502               pu++;
12503               cu++;
12504             }
12505         }
12506     }
12507
12508   return TRUE;
12509 }
12510
12511 static bfd_boolean
12512 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12513 {
12514   asection *sec;
12515   bfd_vma hstart, hend;
12516   Elf_Internal_Rela *relstart, *relend, *rel;
12517   const struct elf_backend_data *bed;
12518   unsigned int log_file_align;
12519
12520   /* Take care of both those symbols that do not describe vtables as
12521      well as those that are not loaded.  */
12522   if (h->vtable == NULL || h->vtable->parent == NULL)
12523     return TRUE;
12524
12525   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12526               || h->root.type == bfd_link_hash_defweak);
12527
12528   sec = h->root.u.def.section;
12529   hstart = h->root.u.def.value;
12530   hend = hstart + h->size;
12531
12532   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12533   if (!relstart)
12534     return *(bfd_boolean *) okp = FALSE;
12535   bed = get_elf_backend_data (sec->owner);
12536   log_file_align = bed->s->log_file_align;
12537
12538   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12539
12540   for (rel = relstart; rel < relend; ++rel)
12541     if (rel->r_offset >= hstart && rel->r_offset < hend)
12542       {
12543         /* If the entry is in use, do nothing.  */
12544         if (h->vtable->used
12545             && (rel->r_offset - hstart) < h->vtable->size)
12546           {
12547             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12548             if (h->vtable->used[entry])
12549               continue;
12550           }
12551         /* Otherwise, kill it.  */
12552         rel->r_offset = rel->r_info = rel->r_addend = 0;
12553       }
12554
12555   return TRUE;
12556 }
12557
12558 /* Mark sections containing dynamically referenced symbols.  When
12559    building shared libraries, we must assume that any visible symbol is
12560    referenced.  */
12561
12562 bfd_boolean
12563 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12564 {
12565   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12566   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12567
12568   if ((h->root.type == bfd_link_hash_defined
12569        || h->root.type == bfd_link_hash_defweak)
12570       && (h->ref_dynamic
12571           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12572               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12573               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12574               && (!info->executable
12575                   || info->export_dynamic
12576                   || (h->dynamic
12577                       && d != NULL
12578                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12579               && (h->versioned >= versioned
12580                   || !bfd_hide_sym_by_version (info->version_info,
12581                                                h->root.root.string)))))
12582     h->root.u.def.section->flags |= SEC_KEEP;
12583
12584   return TRUE;
12585 }
12586
12587 /* Keep all sections containing symbols undefined on the command-line,
12588    and the section containing the entry symbol.  */
12589
12590 void
12591 _bfd_elf_gc_keep (struct bfd_link_info *info)
12592 {
12593   struct bfd_sym_chain *sym;
12594
12595   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12596     {
12597       struct elf_link_hash_entry *h;
12598
12599       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12600                                 FALSE, FALSE, FALSE);
12601
12602       if (h != NULL
12603           && (h->root.type == bfd_link_hash_defined
12604               || h->root.type == bfd_link_hash_defweak)
12605           && !bfd_is_abs_section (h->root.u.def.section))
12606         h->root.u.def.section->flags |= SEC_KEEP;
12607     }
12608 }
12609
12610 bfd_boolean
12611 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
12612                                 struct bfd_link_info *info)
12613 {
12614   bfd *ibfd = info->input_bfds;
12615
12616   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12617     {
12618       asection *sec;
12619       struct elf_reloc_cookie cookie;
12620
12621       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12622         continue;
12623
12624       if (!init_reloc_cookie (&cookie, info, ibfd))
12625         return FALSE;
12626
12627       for (sec = ibfd->sections; sec; sec = sec->next)
12628         {
12629           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
12630               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
12631             {
12632               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
12633               fini_reloc_cookie_rels (&cookie, sec);
12634             }
12635         }
12636     }
12637   return TRUE;
12638 }
12639
12640 /* Do mark and sweep of unused sections.  */
12641
12642 bfd_boolean
12643 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12644 {
12645   bfd_boolean ok = TRUE;
12646   bfd *sub;
12647   elf_gc_mark_hook_fn gc_mark_hook;
12648   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12649   struct elf_link_hash_table *htab;
12650
12651   if (!bed->can_gc_sections
12652       || !is_elf_hash_table (info->hash))
12653     {
12654       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12655       return TRUE;
12656     }
12657
12658   bed->gc_keep (info);
12659   htab = elf_hash_table (info);
12660
12661   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12662      at the .eh_frame section if we can mark the FDEs individually.  */
12663   for (sub = info->input_bfds;
12664        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
12665        sub = sub->link.next)
12666     {
12667       asection *sec;
12668       struct elf_reloc_cookie cookie;
12669
12670       sec = bfd_get_section_by_name (sub, ".eh_frame");
12671       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12672         {
12673           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12674           if (elf_section_data (sec)->sec_info
12675               && (sec->flags & SEC_LINKER_CREATED) == 0)
12676             elf_eh_frame_section (sub) = sec;
12677           fini_reloc_cookie_for_section (&cookie, sec);
12678           sec = bfd_get_next_section_by_name (sec);
12679         }
12680     }
12681
12682   /* Apply transitive closure to the vtable entry usage info.  */
12683   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12684   if (!ok)
12685     return FALSE;
12686
12687   /* Kill the vtable relocations that were not used.  */
12688   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12689   if (!ok)
12690     return FALSE;
12691
12692   /* Mark dynamically referenced symbols.  */
12693   if (htab->dynamic_sections_created)
12694     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12695
12696   /* Grovel through relocs to find out who stays ...  */
12697   gc_mark_hook = bed->gc_mark_hook;
12698   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12699     {
12700       asection *o;
12701
12702       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12703           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12704         continue;
12705
12706       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12707          Also treat note sections as a root, if the section is not part
12708          of a group.  */
12709       for (o = sub->sections; o != NULL; o = o->next)
12710         if (!o->gc_mark
12711             && (o->flags & SEC_EXCLUDE) == 0
12712             && ((o->flags & SEC_KEEP) != 0
12713                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12714                     && elf_next_in_group (o) == NULL )))
12715           {
12716             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12717               return FALSE;
12718           }
12719     }
12720
12721   /* Allow the backend to mark additional target specific sections.  */
12722   bed->gc_mark_extra_sections (info, gc_mark_hook);
12723
12724   /* ... and mark SEC_EXCLUDE for those that go.  */
12725   return elf_gc_sweep (abfd, info);
12726 }
12727 \f
12728 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12729
12730 bfd_boolean
12731 bfd_elf_gc_record_vtinherit (bfd *abfd,
12732                              asection *sec,
12733                              struct elf_link_hash_entry *h,
12734                              bfd_vma offset)
12735 {
12736   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12737   struct elf_link_hash_entry **search, *child;
12738   bfd_size_type extsymcount;
12739   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12740
12741   /* The sh_info field of the symtab header tells us where the
12742      external symbols start.  We don't care about the local symbols at
12743      this point.  */
12744   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12745   if (!elf_bad_symtab (abfd))
12746     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12747
12748   sym_hashes = elf_sym_hashes (abfd);
12749   sym_hashes_end = sym_hashes + extsymcount;
12750
12751   /* Hunt down the child symbol, which is in this section at the same
12752      offset as the relocation.  */
12753   for (search = sym_hashes; search != sym_hashes_end; ++search)
12754     {
12755       if ((child = *search) != NULL
12756           && (child->root.type == bfd_link_hash_defined
12757               || child->root.type == bfd_link_hash_defweak)
12758           && child->root.u.def.section == sec
12759           && child->root.u.def.value == offset)
12760         goto win;
12761     }
12762
12763   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12764                          abfd, sec, (unsigned long) offset);
12765   bfd_set_error (bfd_error_invalid_operation);
12766   return FALSE;
12767
12768  win:
12769   if (!child->vtable)
12770     {
12771       child->vtable = ((struct elf_link_virtual_table_entry *)
12772                        bfd_zalloc (abfd, sizeof (*child->vtable)));
12773       if (!child->vtable)
12774         return FALSE;
12775     }
12776   if (!h)
12777     {
12778       /* This *should* only be the absolute section.  It could potentially
12779          be that someone has defined a non-global vtable though, which
12780          would be bad.  It isn't worth paging in the local symbols to be
12781          sure though; that case should simply be handled by the assembler.  */
12782
12783       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12784     }
12785   else
12786     child->vtable->parent = h;
12787
12788   return TRUE;
12789 }
12790
12791 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12792
12793 bfd_boolean
12794 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12795                            asection *sec ATTRIBUTE_UNUSED,
12796                            struct elf_link_hash_entry *h,
12797                            bfd_vma addend)
12798 {
12799   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12800   unsigned int log_file_align = bed->s->log_file_align;
12801
12802   if (!h->vtable)
12803     {
12804       h->vtable = ((struct elf_link_virtual_table_entry *)
12805                    bfd_zalloc (abfd, sizeof (*h->vtable)));
12806       if (!h->vtable)
12807         return FALSE;
12808     }
12809
12810   if (addend >= h->vtable->size)
12811     {
12812       size_t size, bytes, file_align;
12813       bfd_boolean *ptr = h->vtable->used;
12814
12815       /* While the symbol is undefined, we have to be prepared to handle
12816          a zero size.  */
12817       file_align = 1 << log_file_align;
12818       if (h->root.type == bfd_link_hash_undefined)
12819         size = addend + file_align;
12820       else
12821         {
12822           size = h->size;
12823           if (addend >= size)
12824             {
12825               /* Oops!  We've got a reference past the defined end of
12826                  the table.  This is probably a bug -- shall we warn?  */
12827               size = addend + file_align;
12828             }
12829         }
12830       size = (size + file_align - 1) & -file_align;
12831
12832       /* Allocate one extra entry for use as a "done" flag for the
12833          consolidation pass.  */
12834       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12835
12836       if (ptr)
12837         {
12838           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12839
12840           if (ptr != NULL)
12841             {
12842               size_t oldbytes;
12843
12844               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12845                           * sizeof (bfd_boolean));
12846               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12847             }
12848         }
12849       else
12850         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12851
12852       if (ptr == NULL)
12853         return FALSE;
12854
12855       /* And arrange for that done flag to be at index -1.  */
12856       h->vtable->used = ptr + 1;
12857       h->vtable->size = size;
12858     }
12859
12860   h->vtable->used[addend >> log_file_align] = TRUE;
12861
12862   return TRUE;
12863 }
12864
12865 /* Map an ELF section header flag to its corresponding string.  */
12866 typedef struct
12867 {
12868   char *flag_name;
12869   flagword flag_value;
12870 } elf_flags_to_name_table;
12871
12872 static elf_flags_to_name_table elf_flags_to_names [] =
12873 {
12874   { "SHF_WRITE", SHF_WRITE },
12875   { "SHF_ALLOC", SHF_ALLOC },
12876   { "SHF_EXECINSTR", SHF_EXECINSTR },
12877   { "SHF_MERGE", SHF_MERGE },
12878   { "SHF_STRINGS", SHF_STRINGS },
12879   { "SHF_INFO_LINK", SHF_INFO_LINK},
12880   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12881   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12882   { "SHF_GROUP", SHF_GROUP },
12883   { "SHF_TLS", SHF_TLS },
12884   { "SHF_MASKOS", SHF_MASKOS },
12885   { "SHF_EXCLUDE", SHF_EXCLUDE },
12886 };
12887
12888 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
12889 bfd_boolean
12890 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12891                               struct flag_info *flaginfo,
12892                               asection *section)
12893 {
12894   const bfd_vma sh_flags = elf_section_flags (section);
12895
12896   if (!flaginfo->flags_initialized)
12897     {
12898       bfd *obfd = info->output_bfd;
12899       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12900       struct flag_info_list *tf = flaginfo->flag_list;
12901       int with_hex = 0;
12902       int without_hex = 0;
12903
12904       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
12905         {
12906           unsigned i;
12907           flagword (*lookup) (char *);
12908
12909           lookup = bed->elf_backend_lookup_section_flags_hook;
12910           if (lookup != NULL)
12911             {
12912               flagword hexval = (*lookup) ((char *) tf->name);
12913
12914               if (hexval != 0)
12915                 {
12916                   if (tf->with == with_flags)
12917                     with_hex |= hexval;
12918                   else if (tf->with == without_flags)
12919                     without_hex |= hexval;
12920                   tf->valid = TRUE;
12921                   continue;
12922                 }
12923             }
12924           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
12925             {
12926               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
12927                 {
12928                   if (tf->with == with_flags)
12929                     with_hex |= elf_flags_to_names[i].flag_value;
12930                   else if (tf->with == without_flags)
12931                     without_hex |= elf_flags_to_names[i].flag_value;
12932                   tf->valid = TRUE;
12933                   break;
12934                 }
12935             }
12936           if (!tf->valid)
12937             {
12938               info->callbacks->einfo
12939                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12940               return FALSE;
12941             }
12942         }
12943       flaginfo->flags_initialized = TRUE;
12944       flaginfo->only_with_flags |= with_hex;
12945       flaginfo->not_with_flags |= without_hex;
12946     }
12947
12948   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
12949     return FALSE;
12950
12951   if ((flaginfo->not_with_flags & sh_flags) != 0)
12952     return FALSE;
12953
12954   return TRUE;
12955 }
12956
12957 struct alloc_got_off_arg {
12958   bfd_vma gotoff;
12959   struct bfd_link_info *info;
12960 };
12961
12962 /* We need a special top-level link routine to convert got reference counts
12963    to real got offsets.  */
12964
12965 static bfd_boolean
12966 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12967 {
12968   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12969   bfd *obfd = gofarg->info->output_bfd;
12970   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12971
12972   if (h->got.refcount > 0)
12973     {
12974       h->got.offset = gofarg->gotoff;
12975       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12976     }
12977   else
12978     h->got.offset = (bfd_vma) -1;
12979
12980   return TRUE;
12981 }
12982
12983 /* And an accompanying bit to work out final got entry offsets once
12984    we're done.  Should be called from final_link.  */
12985
12986 bfd_boolean
12987 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12988                                         struct bfd_link_info *info)
12989 {
12990   bfd *i;
12991   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12992   bfd_vma gotoff;
12993   struct alloc_got_off_arg gofarg;
12994
12995   BFD_ASSERT (abfd == info->output_bfd);
12996
12997   if (! is_elf_hash_table (info->hash))
12998     return FALSE;
12999
13000   /* The GOT offset is relative to the .got section, but the GOT header is
13001      put into the .got.plt section, if the backend uses it.  */
13002   if (bed->want_got_plt)
13003     gotoff = 0;
13004   else
13005     gotoff = bed->got_header_size;
13006
13007   /* Do the local .got entries first.  */
13008   for (i = info->input_bfds; i; i = i->link.next)
13009     {
13010       bfd_signed_vma *local_got;
13011       bfd_size_type j, locsymcount;
13012       Elf_Internal_Shdr *symtab_hdr;
13013
13014       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13015         continue;
13016
13017       local_got = elf_local_got_refcounts (i);
13018       if (!local_got)
13019         continue;
13020
13021       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13022       if (elf_bad_symtab (i))
13023         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13024       else
13025         locsymcount = symtab_hdr->sh_info;
13026
13027       for (j = 0; j < locsymcount; ++j)
13028         {
13029           if (local_got[j] > 0)
13030             {
13031               local_got[j] = gotoff;
13032               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13033             }
13034           else
13035             local_got[j] = (bfd_vma) -1;
13036         }
13037     }
13038
13039   /* Then the global .got entries.  .plt refcounts are handled by
13040      adjust_dynamic_symbol  */
13041   gofarg.gotoff = gotoff;
13042   gofarg.info = info;
13043   elf_link_hash_traverse (elf_hash_table (info),
13044                           elf_gc_allocate_got_offsets,
13045                           &gofarg);
13046   return TRUE;
13047 }
13048
13049 /* Many folk need no more in the way of final link than this, once
13050    got entry reference counting is enabled.  */
13051
13052 bfd_boolean
13053 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13054 {
13055   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13056     return FALSE;
13057
13058   /* Invoke the regular ELF backend linker to do all the work.  */
13059   return bfd_elf_final_link (abfd, info);
13060 }
13061
13062 bfd_boolean
13063 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13064 {
13065   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13066
13067   if (rcookie->bad_symtab)
13068     rcookie->rel = rcookie->rels;
13069
13070   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13071     {
13072       unsigned long r_symndx;
13073
13074       if (! rcookie->bad_symtab)
13075         if (rcookie->rel->r_offset > offset)
13076           return FALSE;
13077       if (rcookie->rel->r_offset != offset)
13078         continue;
13079
13080       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13081       if (r_symndx == STN_UNDEF)
13082         return TRUE;
13083
13084       if (r_symndx >= rcookie->locsymcount
13085           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13086         {
13087           struct elf_link_hash_entry *h;
13088
13089           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13090
13091           while (h->root.type == bfd_link_hash_indirect
13092                  || h->root.type == bfd_link_hash_warning)
13093             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13094
13095           if ((h->root.type == bfd_link_hash_defined
13096                || h->root.type == bfd_link_hash_defweak)
13097               && (h->root.u.def.section->owner != rcookie->abfd
13098                   || h->root.u.def.section->kept_section != NULL
13099                   || discarded_section (h->root.u.def.section)))
13100             return TRUE;
13101         }
13102       else
13103         {
13104           /* It's not a relocation against a global symbol,
13105              but it could be a relocation against a local
13106              symbol for a discarded section.  */
13107           asection *isec;
13108           Elf_Internal_Sym *isym;
13109
13110           /* Need to: get the symbol; get the section.  */
13111           isym = &rcookie->locsyms[r_symndx];
13112           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13113           if (isec != NULL
13114               && (isec->kept_section != NULL
13115                   || discarded_section (isec)))
13116             return TRUE;
13117         }
13118       return FALSE;
13119     }
13120   return FALSE;
13121 }
13122
13123 /* Discard unneeded references to discarded sections.
13124    Returns -1 on error, 1 if any section's size was changed, 0 if
13125    nothing changed.  This function assumes that the relocations are in
13126    sorted order, which is true for all known assemblers.  */
13127
13128 int
13129 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13130 {
13131   struct elf_reloc_cookie cookie;
13132   asection *o;
13133   bfd *abfd;
13134   int changed = 0;
13135
13136   if (info->traditional_format
13137       || !is_elf_hash_table (info->hash))
13138     return 0;
13139
13140   o = bfd_get_section_by_name (output_bfd, ".stab");
13141   if (o != NULL)
13142     {
13143       asection *i;
13144
13145       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13146         {
13147           if (i->size == 0
13148               || i->reloc_count == 0
13149               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13150             continue;
13151
13152           abfd = i->owner;
13153           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13154             continue;
13155
13156           if (!init_reloc_cookie_for_section (&cookie, info, i))
13157             return -1;
13158
13159           if (_bfd_discard_section_stabs (abfd, i,
13160                                           elf_section_data (i)->sec_info,
13161                                           bfd_elf_reloc_symbol_deleted_p,
13162                                           &cookie))
13163             changed = 1;
13164
13165           fini_reloc_cookie_for_section (&cookie, i);
13166         }
13167     }
13168
13169   o = NULL;
13170   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13171     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13172   if (o != NULL)
13173     {
13174       asection *i;
13175
13176       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13177         {
13178           if (i->size == 0)
13179             continue;
13180
13181           abfd = i->owner;
13182           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13183             continue;
13184
13185           if (!init_reloc_cookie_for_section (&cookie, info, i))
13186             return -1;
13187
13188           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13189           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13190                                                  bfd_elf_reloc_symbol_deleted_p,
13191                                                  &cookie))
13192             changed = 1;
13193
13194           fini_reloc_cookie_for_section (&cookie, i);
13195         }
13196     }
13197
13198   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13199     {
13200       const struct elf_backend_data *bed;
13201
13202       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13203         continue;
13204
13205       bed = get_elf_backend_data (abfd);
13206
13207       if (bed->elf_backend_discard_info != NULL)
13208         {
13209           if (!init_reloc_cookie (&cookie, info, abfd))
13210             return -1;
13211
13212           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13213             changed = 1;
13214
13215           fini_reloc_cookie (&cookie, abfd);
13216         }
13217     }
13218
13219   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13220     _bfd_elf_end_eh_frame_parsing (info);
13221
13222   if (info->eh_frame_hdr_type
13223       && !info->relocatable
13224       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13225     changed = 1;
13226
13227   return changed;
13228 }
13229
13230 bfd_boolean
13231 _bfd_elf_section_already_linked (bfd *abfd,
13232                                  asection *sec,
13233                                  struct bfd_link_info *info)
13234 {
13235   flagword flags;
13236   const char *name, *key;
13237   struct bfd_section_already_linked *l;
13238   struct bfd_section_already_linked_hash_entry *already_linked_list;
13239
13240   if (sec->output_section == bfd_abs_section_ptr)
13241     return FALSE;
13242
13243   flags = sec->flags;
13244
13245   /* Return if it isn't a linkonce section.  A comdat group section
13246      also has SEC_LINK_ONCE set.  */
13247   if ((flags & SEC_LINK_ONCE) == 0)
13248     return FALSE;
13249
13250   /* Don't put group member sections on our list of already linked
13251      sections.  They are handled as a group via their group section.  */
13252   if (elf_sec_group (sec) != NULL)
13253     return FALSE;
13254
13255   /* For a SHT_GROUP section, use the group signature as the key.  */
13256   name = sec->name;
13257   if ((flags & SEC_GROUP) != 0
13258       && elf_next_in_group (sec) != NULL
13259       && elf_group_name (elf_next_in_group (sec)) != NULL)
13260     key = elf_group_name (elf_next_in_group (sec));
13261   else
13262     {
13263       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13264       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13265           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13266         key++;
13267       else
13268         /* Must be a user linkonce section that doesn't follow gcc's
13269            naming convention.  In this case we won't be matching
13270            single member groups.  */
13271         key = name;
13272     }
13273
13274   already_linked_list = bfd_section_already_linked_table_lookup (key);
13275
13276   for (l = already_linked_list->entry; l != NULL; l = l->next)
13277     {
13278       /* We may have 2 different types of sections on the list: group
13279          sections with a signature of <key> (<key> is some string),
13280          and linkonce sections named .gnu.linkonce.<type>.<key>.
13281          Match like sections.  LTO plugin sections are an exception.
13282          They are always named .gnu.linkonce.t.<key> and match either
13283          type of section.  */
13284       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13285            && ((flags & SEC_GROUP) != 0
13286                || strcmp (name, l->sec->name) == 0))
13287           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13288         {
13289           /* The section has already been linked.  See if we should
13290              issue a warning.  */
13291           if (!_bfd_handle_already_linked (sec, l, info))
13292             return FALSE;
13293
13294           if (flags & SEC_GROUP)
13295             {
13296               asection *first = elf_next_in_group (sec);
13297               asection *s = first;
13298
13299               while (s != NULL)
13300                 {
13301                   s->output_section = bfd_abs_section_ptr;
13302                   /* Record which group discards it.  */
13303                   s->kept_section = l->sec;
13304                   s = elf_next_in_group (s);
13305                   /* These lists are circular.  */
13306                   if (s == first)
13307                     break;
13308                 }
13309             }
13310
13311           return TRUE;
13312         }
13313     }
13314
13315   /* A single member comdat group section may be discarded by a
13316      linkonce section and vice versa.  */
13317   if ((flags & SEC_GROUP) != 0)
13318     {
13319       asection *first = elf_next_in_group (sec);
13320
13321       if (first != NULL && elf_next_in_group (first) == first)
13322         /* Check this single member group against linkonce sections.  */
13323         for (l = already_linked_list->entry; l != NULL; l = l->next)
13324           if ((l->sec->flags & SEC_GROUP) == 0
13325               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13326             {
13327               first->output_section = bfd_abs_section_ptr;
13328               first->kept_section = l->sec;
13329               sec->output_section = bfd_abs_section_ptr;
13330               break;
13331             }
13332     }
13333   else
13334     /* Check this linkonce section against single member groups.  */
13335     for (l = already_linked_list->entry; l != NULL; l = l->next)
13336       if (l->sec->flags & SEC_GROUP)
13337         {
13338           asection *first = elf_next_in_group (l->sec);
13339
13340           if (first != NULL
13341               && elf_next_in_group (first) == first
13342               && bfd_elf_match_symbols_in_sections (first, sec, info))
13343             {
13344               sec->output_section = bfd_abs_section_ptr;
13345               sec->kept_section = first;
13346               break;
13347             }
13348         }
13349
13350   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13351      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13352      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13353      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13354      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13355      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13356      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13357      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13358      The reverse order cannot happen as there is never a bfd with only the
13359      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13360      matter as here were are looking only for cross-bfd sections.  */
13361
13362   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13363     for (l = already_linked_list->entry; l != NULL; l = l->next)
13364       if ((l->sec->flags & SEC_GROUP) == 0
13365           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13366         {
13367           if (abfd != l->sec->owner)
13368             sec->output_section = bfd_abs_section_ptr;
13369           break;
13370         }
13371
13372   /* This is the first section with this name.  Record it.  */
13373   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13374     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13375   return sec->output_section == bfd_abs_section_ptr;
13376 }
13377
13378 bfd_boolean
13379 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13380 {
13381   return sym->st_shndx == SHN_COMMON;
13382 }
13383
13384 unsigned int
13385 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13386 {
13387   return SHN_COMMON;
13388 }
13389
13390 asection *
13391 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13392 {
13393   return bfd_com_section_ptr;
13394 }
13395
13396 bfd_vma
13397 _bfd_elf_default_got_elt_size (bfd *abfd,
13398                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13399                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13400                                bfd *ibfd ATTRIBUTE_UNUSED,
13401                                unsigned long symndx ATTRIBUTE_UNUSED)
13402 {
13403   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13404   return bed->s->arch_size / 8;
13405 }
13406
13407 /* Routines to support the creation of dynamic relocs.  */
13408
13409 /* Returns the name of the dynamic reloc section associated with SEC.  */
13410
13411 static const char *
13412 get_dynamic_reloc_section_name (bfd *       abfd,
13413                                 asection *  sec,
13414                                 bfd_boolean is_rela)
13415 {
13416   char *name;
13417   const char *old_name = bfd_get_section_name (NULL, sec);
13418   const char *prefix = is_rela ? ".rela" : ".rel";
13419
13420   if (old_name == NULL)
13421     return NULL;
13422
13423   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13424   sprintf (name, "%s%s", prefix, old_name);
13425
13426   return name;
13427 }
13428
13429 /* Returns the dynamic reloc section associated with SEC.
13430    If necessary compute the name of the dynamic reloc section based
13431    on SEC's name (looked up in ABFD's string table) and the setting
13432    of IS_RELA.  */
13433
13434 asection *
13435 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13436                                     asection *  sec,
13437                                     bfd_boolean is_rela)
13438 {
13439   asection * reloc_sec = elf_section_data (sec)->sreloc;
13440
13441   if (reloc_sec == NULL)
13442     {
13443       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13444
13445       if (name != NULL)
13446         {
13447           reloc_sec = bfd_get_linker_section (abfd, name);
13448
13449           if (reloc_sec != NULL)
13450             elf_section_data (sec)->sreloc = reloc_sec;
13451         }
13452     }
13453
13454   return reloc_sec;
13455 }
13456
13457 /* Returns the dynamic reloc section associated with SEC.  If the
13458    section does not exist it is created and attached to the DYNOBJ
13459    bfd and stored in the SRELOC field of SEC's elf_section_data
13460    structure.
13461
13462    ALIGNMENT is the alignment for the newly created section and
13463    IS_RELA defines whether the name should be .rela.<SEC's name>
13464    or .rel.<SEC's name>.  The section name is looked up in the
13465    string table associated with ABFD.  */
13466
13467 asection *
13468 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13469                                      bfd *dynobj,
13470                                      unsigned int alignment,
13471                                      bfd *abfd,
13472                                      bfd_boolean is_rela)
13473 {
13474   asection * reloc_sec = elf_section_data (sec)->sreloc;
13475
13476   if (reloc_sec == NULL)
13477     {
13478       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13479
13480       if (name == NULL)
13481         return NULL;
13482
13483       reloc_sec = bfd_get_linker_section (dynobj, name);
13484
13485       if (reloc_sec == NULL)
13486         {
13487           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13488                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13489           if ((sec->flags & SEC_ALLOC) != 0)
13490             flags |= SEC_ALLOC | SEC_LOAD;
13491
13492           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13493           if (reloc_sec != NULL)
13494             {
13495               /* _bfd_elf_get_sec_type_attr chooses a section type by
13496                  name.  Override as it may be wrong, eg. for a user
13497                  section named "auto" we'll get ".relauto" which is
13498                  seen to be a .rela section.  */
13499               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13500               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13501                 reloc_sec = NULL;
13502             }
13503         }
13504
13505       elf_section_data (sec)->sreloc = reloc_sec;
13506     }
13507
13508   return reloc_sec;
13509 }
13510
13511 /* Copy the ELF symbol type and other attributes for a linker script
13512    assignment from HSRC to HDEST.  Generally this should be treated as
13513    if we found a strong non-dynamic definition for HDEST (except that
13514    ld ignores multiple definition errors).  */
13515 void
13516 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13517                                      struct bfd_link_hash_entry *hdest,
13518                                      struct bfd_link_hash_entry *hsrc)
13519 {
13520   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13521   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13522   Elf_Internal_Sym isym;
13523
13524   ehdest->type = ehsrc->type;
13525   ehdest->target_internal = ehsrc->target_internal;
13526
13527   isym.st_other = ehsrc->other;
13528   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13529 }
13530
13531 /* Append a RELA relocation REL to section S in BFD.  */
13532
13533 void
13534 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13535 {
13536   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13537   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13538   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13539   bed->s->swap_reloca_out (abfd, rel, loc);
13540 }
13541
13542 /* Append a REL relocation REL to section S in BFD.  */
13543
13544 void
13545 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13546 {
13547   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13548   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13549   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13550   bed->s->swap_reloc_out (abfd, rel, loc);
13551 }