Merge branch 'vendor/OPENSSL'
[dragonfly.git] / contrib / binutils-2.25 / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2014 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 /* Define a symbol in a dynamic linkage section.  */
58
59 struct elf_link_hash_entry *
60 _bfd_elf_define_linkage_sym (bfd *abfd,
61                              struct bfd_link_info *info,
62                              asection *sec,
63                              const char *name)
64 {
65   struct elf_link_hash_entry *h;
66   struct bfd_link_hash_entry *bh;
67   const struct elf_backend_data *bed;
68
69   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
70   if (h != NULL)
71     {
72       /* Zap symbol defined in an as-needed lib that wasn't linked.
73          This is a symptom of a larger problem:  Absolute symbols
74          defined in shared libraries can't be overridden, because we
75          lose the link to the bfd which is via the symbol section.  */
76       h->root.type = bfd_link_hash_new;
77     }
78
79   bh = &h->root;
80   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
81                                          sec, 0, NULL, FALSE,
82                                          get_elf_backend_data (abfd)->collect,
83                                          &bh))
84     return NULL;
85   h = (struct elf_link_hash_entry *) bh;
86   h->def_regular = 1;
87   h->non_elf = 0;
88   h->root.linker_def = 1;
89   h->type = STT_OBJECT;
90   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
91     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
92
93   bed = get_elf_backend_data (abfd);
94   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
95   return h;
96 }
97
98 bfd_boolean
99 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
100 {
101   flagword flags;
102   asection *s;
103   struct elf_link_hash_entry *h;
104   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
105   struct elf_link_hash_table *htab = elf_hash_table (info);
106
107   /* This function may be called more than once.  */
108   s = bfd_get_linker_section (abfd, ".got");
109   if (s != NULL)
110     return TRUE;
111
112   flags = bed->dynamic_sec_flags;
113
114   s = bfd_make_section_anyway_with_flags (abfd,
115                                           (bed->rela_plts_and_copies_p
116                                            ? ".rela.got" : ".rel.got"),
117                                           (bed->dynamic_sec_flags
118                                            | SEC_READONLY));
119   if (s == NULL
120       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
121     return FALSE;
122   htab->srelgot = s;
123
124   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
125   if (s == NULL
126       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
127     return FALSE;
128   htab->sgot = s;
129
130   if (bed->want_got_plt)
131     {
132       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
133       if (s == NULL
134           || !bfd_set_section_alignment (abfd, s,
135                                          bed->s->log_file_align))
136         return FALSE;
137       htab->sgotplt = s;
138     }
139
140   /* The first bit of the global offset table is the header.  */
141   s->size += bed->got_header_size;
142
143   if (bed->want_got_sym)
144     {
145       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
146          (or .got.plt) section.  We don't do this in the linker script
147          because we don't want to define the symbol if we are not creating
148          a global offset table.  */
149       h = _bfd_elf_define_linkage_sym (abfd, info, s,
150                                        "_GLOBAL_OFFSET_TABLE_");
151       elf_hash_table (info)->hgot = h;
152       if (h == NULL)
153         return FALSE;
154     }
155
156   return TRUE;
157 }
158 \f
159 /* Create a strtab to hold the dynamic symbol names.  */
160 static bfd_boolean
161 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
162 {
163   struct elf_link_hash_table *hash_table;
164
165   hash_table = elf_hash_table (info);
166   if (hash_table->dynobj == NULL)
167     hash_table->dynobj = abfd;
168
169   if (hash_table->dynstr == NULL)
170     {
171       hash_table->dynstr = _bfd_elf_strtab_init ();
172       if (hash_table->dynstr == NULL)
173         return FALSE;
174     }
175   return TRUE;
176 }
177
178 /* Create some sections which will be filled in with dynamic linking
179    information.  ABFD is an input file which requires dynamic sections
180    to be created.  The dynamic sections take up virtual memory space
181    when the final executable is run, so we need to create them before
182    addresses are assigned to the output sections.  We work out the
183    actual contents and size of these sections later.  */
184
185 bfd_boolean
186 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
187 {
188   flagword flags;
189   asection *s;
190   const struct elf_backend_data *bed;
191   struct elf_link_hash_entry *h;
192
193   if (! is_elf_hash_table (info->hash))
194     return FALSE;
195
196   if (elf_hash_table (info)->dynamic_sections_created)
197     return TRUE;
198
199   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
200     return FALSE;
201
202   abfd = elf_hash_table (info)->dynobj;
203   bed = get_elf_backend_data (abfd);
204
205   flags = bed->dynamic_sec_flags;
206
207   /* A dynamically linked executable has a .interp section, but a
208      shared library does not.  */
209   if (info->executable)
210     {
211       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
212                                               flags | SEC_READONLY);
213       if (s == NULL)
214         return FALSE;
215     }
216
217   /* Create sections to hold version informations.  These are removed
218      if they are not needed.  */
219   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
220                                           flags | SEC_READONLY);
221   if (s == NULL
222       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
223     return FALSE;
224
225   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
226                                           flags | SEC_READONLY);
227   if (s == NULL
228       || ! bfd_set_section_alignment (abfd, s, 1))
229     return FALSE;
230
231   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
232                                           flags | SEC_READONLY);
233   if (s == NULL
234       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
235     return FALSE;
236
237   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
238                                           flags | SEC_READONLY);
239   if (s == NULL
240       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
241     return FALSE;
242
243   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
244                                           flags | SEC_READONLY);
245   if (s == NULL)
246     return FALSE;
247
248   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
249   if (s == NULL
250       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
251     return FALSE;
252
253   /* The special symbol _DYNAMIC is always set to the start of the
254      .dynamic section.  We could set _DYNAMIC in a linker script, but we
255      only want to define it if we are, in fact, creating a .dynamic
256      section.  We don't want to define it if there is no .dynamic
257      section, since on some ELF platforms the start up code examines it
258      to decide how to initialize the process.  */
259   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
260   elf_hash_table (info)->hdynamic = h;
261   if (h == NULL)
262     return FALSE;
263
264   if (info->emit_hash)
265     {
266       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
267                                               flags | SEC_READONLY);
268       if (s == NULL
269           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
270         return FALSE;
271       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
272     }
273
274   if (info->emit_gnu_hash)
275     {
276       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
277                                               flags | SEC_READONLY);
278       if (s == NULL
279           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
280         return FALSE;
281       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
282          4 32-bit words followed by variable count of 64-bit words, then
283          variable count of 32-bit words.  */
284       if (bed->s->arch_size == 64)
285         elf_section_data (s)->this_hdr.sh_entsize = 0;
286       else
287         elf_section_data (s)->this_hdr.sh_entsize = 4;
288     }
289
290   /* Let the backend create the rest of the sections.  This lets the
291      backend set the right flags.  The backend will normally create
292      the .got and .plt sections.  */
293   if (bed->elf_backend_create_dynamic_sections == NULL
294       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
295     return FALSE;
296
297   elf_hash_table (info)->dynamic_sections_created = TRUE;
298
299   return TRUE;
300 }
301
302 /* Create dynamic sections when linking against a dynamic object.  */
303
304 bfd_boolean
305 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
306 {
307   flagword flags, pltflags;
308   struct elf_link_hash_entry *h;
309   asection *s;
310   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
311   struct elf_link_hash_table *htab = elf_hash_table (info);
312
313   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
314      .rel[a].bss sections.  */
315   flags = bed->dynamic_sec_flags;
316
317   pltflags = flags;
318   if (bed->plt_not_loaded)
319     /* We do not clear SEC_ALLOC here because we still want the OS to
320        allocate space for the section; it's just that there's nothing
321        to read in from the object file.  */
322     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
323   else
324     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
325   if (bed->plt_readonly)
326     pltflags |= SEC_READONLY;
327
328   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
329   if (s == NULL
330       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
331     return FALSE;
332   htab->splt = s;
333
334   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
335      .plt section.  */
336   if (bed->want_plt_sym)
337     {
338       h = _bfd_elf_define_linkage_sym (abfd, info, s,
339                                        "_PROCEDURE_LINKAGE_TABLE_");
340       elf_hash_table (info)->hplt = h;
341       if (h == NULL)
342         return FALSE;
343     }
344
345   s = bfd_make_section_anyway_with_flags (abfd,
346                                           (bed->rela_plts_and_copies_p
347                                            ? ".rela.plt" : ".rel.plt"),
348                                           flags | SEC_READONLY);
349   if (s == NULL
350       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
351     return FALSE;
352   htab->srelplt = s;
353
354   if (! _bfd_elf_create_got_section (abfd, info))
355     return FALSE;
356
357   if (bed->want_dynbss)
358     {
359       /* The .dynbss section is a place to put symbols which are defined
360          by dynamic objects, are referenced by regular objects, and are
361          not functions.  We must allocate space for them in the process
362          image and use a R_*_COPY reloc to tell the dynamic linker to
363          initialize them at run time.  The linker script puts the .dynbss
364          section into the .bss section of the final image.  */
365       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
366                                               (SEC_ALLOC | SEC_LINKER_CREATED));
367       if (s == NULL)
368         return FALSE;
369
370       /* The .rel[a].bss section holds copy relocs.  This section is not
371          normally needed.  We need to create it here, though, so that the
372          linker will map it to an output section.  We can't just create it
373          only if we need it, because we will not know whether we need it
374          until we have seen all the input files, and the first time the
375          main linker code calls BFD after examining all the input files
376          (size_dynamic_sections) the input sections have already been
377          mapped to the output sections.  If the section turns out not to
378          be needed, we can discard it later.  We will never need this
379          section when generating a shared object, since they do not use
380          copy relocs.  */
381       if (! info->shared)
382         {
383           s = bfd_make_section_anyway_with_flags (abfd,
384                                                   (bed->rela_plts_and_copies_p
385                                                    ? ".rela.bss" : ".rel.bss"),
386                                                   flags | SEC_READONLY);
387           if (s == NULL
388               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
389             return FALSE;
390         }
391     }
392
393   return TRUE;
394 }
395 \f
396 /* Record a new dynamic symbol.  We record the dynamic symbols as we
397    read the input files, since we need to have a list of all of them
398    before we can determine the final sizes of the output sections.
399    Note that we may actually call this function even though we are not
400    going to output any dynamic symbols; in some cases we know that a
401    symbol should be in the dynamic symbol table, but only if there is
402    one.  */
403
404 bfd_boolean
405 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
406                                     struct elf_link_hash_entry *h)
407 {
408   if (h->dynindx == -1)
409     {
410       struct elf_strtab_hash *dynstr;
411       char *p;
412       const char *name;
413       bfd_size_type indx;
414
415       /* XXX: The ABI draft says the linker must turn hidden and
416          internal symbols into STB_LOCAL symbols when producing the
417          DSO. However, if ld.so honors st_other in the dynamic table,
418          this would not be necessary.  */
419       switch (ELF_ST_VISIBILITY (h->other))
420         {
421         case STV_INTERNAL:
422         case STV_HIDDEN:
423           if (h->root.type != bfd_link_hash_undefined
424               && h->root.type != bfd_link_hash_undefweak)
425             {
426               h->forced_local = 1;
427               if (!elf_hash_table (info)->is_relocatable_executable)
428                 return TRUE;
429             }
430
431         default:
432           break;
433         }
434
435       h->dynindx = elf_hash_table (info)->dynsymcount;
436       ++elf_hash_table (info)->dynsymcount;
437
438       dynstr = elf_hash_table (info)->dynstr;
439       if (dynstr == NULL)
440         {
441           /* Create a strtab to hold the dynamic symbol names.  */
442           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
443           if (dynstr == NULL)
444             return FALSE;
445         }
446
447       /* We don't put any version information in the dynamic string
448          table.  */
449       name = h->root.root.string;
450       p = strchr (name, ELF_VER_CHR);
451       if (p != NULL)
452         /* We know that the p points into writable memory.  In fact,
453            there are only a few symbols that have read-only names, being
454            those like _GLOBAL_OFFSET_TABLE_ that are created specially
455            by the backends.  Most symbols will have names pointing into
456            an ELF string table read from a file, or to objalloc memory.  */
457         *p = 0;
458
459       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
460
461       if (p != NULL)
462         *p = ELF_VER_CHR;
463
464       if (indx == (bfd_size_type) -1)
465         return FALSE;
466       h->dynstr_index = indx;
467     }
468
469   return TRUE;
470 }
471 \f
472 /* Mark a symbol dynamic.  */
473
474 static void
475 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
476                                   struct elf_link_hash_entry *h,
477                                   Elf_Internal_Sym *sym)
478 {
479   struct bfd_elf_dynamic_list *d = info->dynamic_list;
480
481   /* It may be called more than once on the same H.  */
482   if(h->dynamic || info->relocatable)
483     return;
484
485   if ((info->dynamic_data
486        && (h->type == STT_OBJECT
487            || (sym != NULL
488                && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
489       || (d != NULL
490           && h->root.type == bfd_link_hash_new
491           && (*d->match) (&d->head, NULL, h->root.root.string)))
492     h->dynamic = 1;
493 }
494
495 /* Record an assignment to a symbol made by a linker script.  We need
496    this in case some dynamic object refers to this symbol.  */
497
498 bfd_boolean
499 bfd_elf_record_link_assignment (bfd *output_bfd,
500                                 struct bfd_link_info *info,
501                                 const char *name,
502                                 bfd_boolean provide,
503                                 bfd_boolean hidden)
504 {
505   struct elf_link_hash_entry *h, *hv;
506   struct elf_link_hash_table *htab;
507   const struct elf_backend_data *bed;
508
509   if (!is_elf_hash_table (info->hash))
510     return TRUE;
511
512   htab = elf_hash_table (info);
513   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
514   if (h == NULL)
515     return provide;
516
517   switch (h->root.type)
518     {
519     case bfd_link_hash_defined:
520     case bfd_link_hash_defweak:
521     case bfd_link_hash_common:
522       break;
523     case bfd_link_hash_undefweak:
524     case bfd_link_hash_undefined:
525       /* Since we're defining the symbol, don't let it seem to have not
526          been defined.  record_dynamic_symbol and size_dynamic_sections
527          may depend on this.  */
528       h->root.type = bfd_link_hash_new;
529       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
530         bfd_link_repair_undef_list (&htab->root);
531       break;
532     case bfd_link_hash_new:
533       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
534       h->non_elf = 0;
535       break;
536     case bfd_link_hash_indirect:
537       /* We had a versioned symbol in a dynamic library.  We make the
538          the versioned symbol point to this one.  */
539       bed = get_elf_backend_data (output_bfd);
540       hv = h;
541       while (hv->root.type == bfd_link_hash_indirect
542              || hv->root.type == bfd_link_hash_warning)
543         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
544       /* We don't need to update h->root.u since linker will set them
545          later.  */
546       h->root.type = bfd_link_hash_undefined;
547       hv->root.type = bfd_link_hash_indirect;
548       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
549       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
550       break;
551     case bfd_link_hash_warning:
552       abort ();
553       break;
554     }
555
556   /* If this symbol is being provided by the linker script, and it is
557      currently defined by a dynamic object, but not by a regular
558      object, then mark it as undefined so that the generic linker will
559      force the correct value.  */
560   if (provide
561       && h->def_dynamic
562       && !h->def_regular)
563     h->root.type = bfd_link_hash_undefined;
564
565   /* If this symbol is not being provided by the linker script, and it is
566      currently defined by a dynamic object, but not by a regular object,
567      then clear out any version information because the symbol will not be
568      associated with the dynamic object any more.  */
569   if (!provide
570       && h->def_dynamic
571       && !h->def_regular)
572     h->verinfo.verdef = NULL;
573
574   h->def_regular = 1;
575
576   if (hidden)
577     {
578       bed = get_elf_backend_data (output_bfd);
579       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
580         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
581       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
582     }
583
584   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
585      and executables.  */
586   if (!info->relocatable
587       && h->dynindx != -1
588       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
589           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
590     h->forced_local = 1;
591
592   if ((h->def_dynamic
593        || h->ref_dynamic
594        || info->shared
595        || (info->executable && elf_hash_table (info)->is_relocatable_executable))
596       && h->dynindx == -1)
597     {
598       if (! bfd_elf_link_record_dynamic_symbol (info, h))
599         return FALSE;
600
601       /* If this is a weak defined symbol, and we know a corresponding
602          real symbol from the same dynamic object, make sure the real
603          symbol is also made into a dynamic symbol.  */
604       if (h->u.weakdef != NULL
605           && h->u.weakdef->dynindx == -1)
606         {
607           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
608             return FALSE;
609         }
610     }
611
612   return TRUE;
613 }
614
615 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
616    success, and 2 on a failure caused by attempting to record a symbol
617    in a discarded section, eg. a discarded link-once section symbol.  */
618
619 int
620 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
621                                           bfd *input_bfd,
622                                           long input_indx)
623 {
624   bfd_size_type amt;
625   struct elf_link_local_dynamic_entry *entry;
626   struct elf_link_hash_table *eht;
627   struct elf_strtab_hash *dynstr;
628   unsigned long dynstr_index;
629   char *name;
630   Elf_External_Sym_Shndx eshndx;
631   char esym[sizeof (Elf64_External_Sym)];
632
633   if (! is_elf_hash_table (info->hash))
634     return 0;
635
636   /* See if the entry exists already.  */
637   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
638     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
639       return 1;
640
641   amt = sizeof (*entry);
642   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
643   if (entry == NULL)
644     return 0;
645
646   /* Go find the symbol, so that we can find it's name.  */
647   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
648                              1, input_indx, &entry->isym, esym, &eshndx))
649     {
650       bfd_release (input_bfd, entry);
651       return 0;
652     }
653
654   if (entry->isym.st_shndx != SHN_UNDEF
655       && entry->isym.st_shndx < SHN_LORESERVE)
656     {
657       asection *s;
658
659       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
660       if (s == NULL || bfd_is_abs_section (s->output_section))
661         {
662           /* We can still bfd_release here as nothing has done another
663              bfd_alloc.  We can't do this later in this function.  */
664           bfd_release (input_bfd, entry);
665           return 2;
666         }
667     }
668
669   name = (bfd_elf_string_from_elf_section
670           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
671            entry->isym.st_name));
672
673   dynstr = elf_hash_table (info)->dynstr;
674   if (dynstr == NULL)
675     {
676       /* Create a strtab to hold the dynamic symbol names.  */
677       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
678       if (dynstr == NULL)
679         return 0;
680     }
681
682   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
683   if (dynstr_index == (unsigned long) -1)
684     return 0;
685   entry->isym.st_name = dynstr_index;
686
687   eht = elf_hash_table (info);
688
689   entry->next = eht->dynlocal;
690   eht->dynlocal = entry;
691   entry->input_bfd = input_bfd;
692   entry->input_indx = input_indx;
693   eht->dynsymcount++;
694
695   /* Whatever binding the symbol had before, it's now local.  */
696   entry->isym.st_info
697     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
698
699   /* The dynindx will be set at the end of size_dynamic_sections.  */
700
701   return 1;
702 }
703
704 /* Return the dynindex of a local dynamic symbol.  */
705
706 long
707 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
708                                     bfd *input_bfd,
709                                     long input_indx)
710 {
711   struct elf_link_local_dynamic_entry *e;
712
713   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
714     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
715       return e->dynindx;
716   return -1;
717 }
718
719 /* This function is used to renumber the dynamic symbols, if some of
720    them are removed because they are marked as local.  This is called
721    via elf_link_hash_traverse.  */
722
723 static bfd_boolean
724 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
725                                       void *data)
726 {
727   size_t *count = (size_t *) data;
728
729   if (h->forced_local)
730     return TRUE;
731
732   if (h->dynindx != -1)
733     h->dynindx = ++(*count);
734
735   return TRUE;
736 }
737
738
739 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
740    STB_LOCAL binding.  */
741
742 static bfd_boolean
743 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
744                                             void *data)
745 {
746   size_t *count = (size_t *) data;
747
748   if (!h->forced_local)
749     return TRUE;
750
751   if (h->dynindx != -1)
752     h->dynindx = ++(*count);
753
754   return TRUE;
755 }
756
757 /* Return true if the dynamic symbol for a given section should be
758    omitted when creating a shared library.  */
759 bfd_boolean
760 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
761                                    struct bfd_link_info *info,
762                                    asection *p)
763 {
764   struct elf_link_hash_table *htab;
765   asection *ip;
766
767   switch (elf_section_data (p)->this_hdr.sh_type)
768     {
769     case SHT_PROGBITS:
770     case SHT_NOBITS:
771       /* If sh_type is yet undecided, assume it could be
772          SHT_PROGBITS/SHT_NOBITS.  */
773     case SHT_NULL:
774       htab = elf_hash_table (info);
775       if (p == htab->tls_sec)
776         return FALSE;
777
778       if (htab->text_index_section != NULL)
779         return p != htab->text_index_section && p != htab->data_index_section;
780
781       return (htab->dynobj != NULL
782               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
783               && ip->output_section == p);
784
785       /* There shouldn't be section relative relocations
786          against any other section.  */
787     default:
788       return TRUE;
789     }
790 }
791
792 /* Assign dynsym indices.  In a shared library we generate a section
793    symbol for each output section, which come first.  Next come symbols
794    which have been forced to local binding.  Then all of the back-end
795    allocated local dynamic syms, followed by the rest of the global
796    symbols.  */
797
798 static unsigned long
799 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
800                                 struct bfd_link_info *info,
801                                 unsigned long *section_sym_count)
802 {
803   unsigned long dynsymcount = 0;
804
805   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
806     {
807       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
808       asection *p;
809       for (p = output_bfd->sections; p ; p = p->next)
810         if ((p->flags & SEC_EXCLUDE) == 0
811             && (p->flags & SEC_ALLOC) != 0
812             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
813           elf_section_data (p)->dynindx = ++dynsymcount;
814         else
815           elf_section_data (p)->dynindx = 0;
816     }
817   *section_sym_count = dynsymcount;
818
819   elf_link_hash_traverse (elf_hash_table (info),
820                           elf_link_renumber_local_hash_table_dynsyms,
821                           &dynsymcount);
822
823   if (elf_hash_table (info)->dynlocal)
824     {
825       struct elf_link_local_dynamic_entry *p;
826       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
827         p->dynindx = ++dynsymcount;
828     }
829
830   elf_link_hash_traverse (elf_hash_table (info),
831                           elf_link_renumber_hash_table_dynsyms,
832                           &dynsymcount);
833
834   /* There is an unused NULL entry at the head of the table which
835      we must account for in our count.  Unless there weren't any
836      symbols, which means we'll have no table at all.  */
837   if (dynsymcount != 0)
838     ++dynsymcount;
839
840   elf_hash_table (info)->dynsymcount = dynsymcount;
841   return dynsymcount;
842 }
843
844 /* Merge st_other field.  */
845
846 static void
847 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
848                     const Elf_Internal_Sym *isym, asection *sec,
849                     bfd_boolean definition, bfd_boolean dynamic)
850 {
851   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
852
853   /* If st_other has a processor-specific meaning, specific
854      code might be needed here.  */
855   if (bed->elf_backend_merge_symbol_attribute)
856     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
857                                                 dynamic);
858
859   if (!dynamic)
860     {
861       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
862       unsigned hvis = ELF_ST_VISIBILITY (h->other);
863
864       /* Keep the most constraining visibility.  Leave the remainder
865          of the st_other field to elf_backend_merge_symbol_attribute.  */
866       if (symvis - 1 < hvis - 1)
867         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
868     }
869   else if (definition
870            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
871            && (sec->flags & SEC_READONLY) == 0)
872     h->protected_def = 1;
873 }
874
875 /* This function is called when we want to merge a new symbol with an
876    existing symbol.  It handles the various cases which arise when we
877    find a definition in a dynamic object, or when there is already a
878    definition in a dynamic object.  The new symbol is described by
879    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
880    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
881    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
882    of an old common symbol.  We set OVERRIDE if the old symbol is
883    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
884    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
885    to change.  By OK to change, we mean that we shouldn't warn if the
886    type or size does change.  */
887
888 static bfd_boolean
889 _bfd_elf_merge_symbol (bfd *abfd,
890                        struct bfd_link_info *info,
891                        const char *name,
892                        Elf_Internal_Sym *sym,
893                        asection **psec,
894                        bfd_vma *pvalue,
895                        struct elf_link_hash_entry **sym_hash,
896                        bfd **poldbfd,
897                        bfd_boolean *pold_weak,
898                        unsigned int *pold_alignment,
899                        bfd_boolean *skip,
900                        bfd_boolean *override,
901                        bfd_boolean *type_change_ok,
902                        bfd_boolean *size_change_ok)
903 {
904   asection *sec, *oldsec;
905   struct elf_link_hash_entry *h;
906   struct elf_link_hash_entry *hi;
907   struct elf_link_hash_entry *flip;
908   int bind;
909   bfd *oldbfd;
910   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
911   bfd_boolean newweak, oldweak, newfunc, oldfunc;
912   const struct elf_backend_data *bed;
913
914   *skip = FALSE;
915   *override = FALSE;
916
917   sec = *psec;
918   bind = ELF_ST_BIND (sym->st_info);
919
920   if (! bfd_is_und_section (sec))
921     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
922   else
923     h = ((struct elf_link_hash_entry *)
924          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
925   if (h == NULL)
926     return FALSE;
927   *sym_hash = h;
928
929   bed = get_elf_backend_data (abfd);
930
931   /* For merging, we only care about real symbols.  But we need to make
932      sure that indirect symbol dynamic flags are updated.  */
933   hi = h;
934   while (h->root.type == bfd_link_hash_indirect
935          || h->root.type == bfd_link_hash_warning)
936     h = (struct elf_link_hash_entry *) h->root.u.i.link;
937
938   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
939      existing symbol.  */
940
941   oldbfd = NULL;
942   oldsec = NULL;
943   switch (h->root.type)
944     {
945     default:
946       break;
947
948     case bfd_link_hash_undefined:
949     case bfd_link_hash_undefweak:
950       oldbfd = h->root.u.undef.abfd;
951       break;
952
953     case bfd_link_hash_defined:
954     case bfd_link_hash_defweak:
955       oldbfd = h->root.u.def.section->owner;
956       oldsec = h->root.u.def.section;
957       break;
958
959     case bfd_link_hash_common:
960       oldbfd = h->root.u.c.p->section->owner;
961       oldsec = h->root.u.c.p->section;
962       if (pold_alignment)
963         *pold_alignment = h->root.u.c.p->alignment_power;
964       break;
965     }
966   if (poldbfd && *poldbfd == NULL)
967     *poldbfd = oldbfd;
968
969   /* Differentiate strong and weak symbols.  */
970   newweak = bind == STB_WEAK;
971   oldweak = (h->root.type == bfd_link_hash_defweak
972              || h->root.type == bfd_link_hash_undefweak);
973   if (pold_weak)
974     *pold_weak = oldweak;
975
976   /* This code is for coping with dynamic objects, and is only useful
977      if we are doing an ELF link.  */
978   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
979     return TRUE;
980
981   /* We have to check it for every instance since the first few may be
982      references and not all compilers emit symbol type for undefined
983      symbols.  */
984   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
985
986   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
987      respectively, is from a dynamic object.  */
988
989   newdyn = (abfd->flags & DYNAMIC) != 0;
990
991   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
992      syms and defined syms in dynamic libraries respectively.
993      ref_dynamic on the other hand can be set for a symbol defined in
994      a dynamic library, and def_dynamic may not be set;  When the
995      definition in a dynamic lib is overridden by a definition in the
996      executable use of the symbol in the dynamic lib becomes a
997      reference to the executable symbol.  */
998   if (newdyn)
999     {
1000       if (bfd_is_und_section (sec))
1001         {
1002           if (bind != STB_WEAK)
1003             {
1004               h->ref_dynamic_nonweak = 1;
1005               hi->ref_dynamic_nonweak = 1;
1006             }
1007         }
1008       else
1009         {
1010           h->dynamic_def = 1;
1011           hi->dynamic_def = 1;
1012         }
1013     }
1014
1015   /* If we just created the symbol, mark it as being an ELF symbol.
1016      Other than that, there is nothing to do--there is no merge issue
1017      with a newly defined symbol--so we just return.  */
1018
1019   if (h->root.type == bfd_link_hash_new)
1020     {
1021       h->non_elf = 0;
1022       return TRUE;
1023     }
1024
1025   /* In cases involving weak versioned symbols, we may wind up trying
1026      to merge a symbol with itself.  Catch that here, to avoid the
1027      confusion that results if we try to override a symbol with
1028      itself.  The additional tests catch cases like
1029      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1030      dynamic object, which we do want to handle here.  */
1031   if (abfd == oldbfd
1032       && (newweak || oldweak)
1033       && ((abfd->flags & DYNAMIC) == 0
1034           || !h->def_regular))
1035     return TRUE;
1036
1037   olddyn = FALSE;
1038   if (oldbfd != NULL)
1039     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1040   else if (oldsec != NULL)
1041     {
1042       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1043          indices used by MIPS ELF.  */
1044       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1045     }
1046
1047   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1048      respectively, appear to be a definition rather than reference.  */
1049
1050   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1051
1052   olddef = (h->root.type != bfd_link_hash_undefined
1053             && h->root.type != bfd_link_hash_undefweak
1054             && h->root.type != bfd_link_hash_common);
1055
1056   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1057      respectively, appear to be a function.  */
1058
1059   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1060              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1061
1062   oldfunc = (h->type != STT_NOTYPE
1063              && bed->is_function_type (h->type));
1064
1065   /* When we try to create a default indirect symbol from the dynamic
1066      definition with the default version, we skip it if its type and
1067      the type of existing regular definition mismatch.  */
1068   if (pold_alignment == NULL
1069       && newdyn
1070       && newdef
1071       && !olddyn
1072       && (((olddef || h->root.type == bfd_link_hash_common)
1073            && ELF_ST_TYPE (sym->st_info) != h->type
1074            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1075            && h->type != STT_NOTYPE
1076            && !(newfunc && oldfunc))
1077           || (olddef
1078               && ((h->type == STT_GNU_IFUNC)
1079                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1080     {
1081       *skip = TRUE;
1082       return TRUE;
1083     }
1084
1085   /* Check TLS symbols.  We don't check undefined symbols introduced
1086      by "ld -u" which have no type (and oldbfd NULL), and we don't
1087      check symbols from plugins because they also have no type.  */
1088   if (oldbfd != NULL
1089       && (oldbfd->flags & BFD_PLUGIN) == 0
1090       && (abfd->flags & BFD_PLUGIN) == 0
1091       && ELF_ST_TYPE (sym->st_info) != h->type
1092       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1093     {
1094       bfd *ntbfd, *tbfd;
1095       bfd_boolean ntdef, tdef;
1096       asection *ntsec, *tsec;
1097
1098       if (h->type == STT_TLS)
1099         {
1100           ntbfd = abfd;
1101           ntsec = sec;
1102           ntdef = newdef;
1103           tbfd = oldbfd;
1104           tsec = oldsec;
1105           tdef = olddef;
1106         }
1107       else
1108         {
1109           ntbfd = oldbfd;
1110           ntsec = oldsec;
1111           ntdef = olddef;
1112           tbfd = abfd;
1113           tsec = sec;
1114           tdef = newdef;
1115         }
1116
1117       if (tdef && ntdef)
1118         (*_bfd_error_handler)
1119           (_("%s: TLS definition in %B section %A "
1120              "mismatches non-TLS definition in %B section %A"),
1121            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1122       else if (!tdef && !ntdef)
1123         (*_bfd_error_handler)
1124           (_("%s: TLS reference in %B "
1125              "mismatches non-TLS reference in %B"),
1126            tbfd, ntbfd, h->root.root.string);
1127       else if (tdef)
1128         (*_bfd_error_handler)
1129           (_("%s: TLS definition in %B section %A "
1130              "mismatches non-TLS reference in %B"),
1131            tbfd, tsec, ntbfd, h->root.root.string);
1132       else
1133         (*_bfd_error_handler)
1134           (_("%s: TLS reference in %B "
1135              "mismatches non-TLS definition in %B section %A"),
1136            tbfd, ntbfd, ntsec, h->root.root.string);
1137
1138       bfd_set_error (bfd_error_bad_value);
1139       return FALSE;
1140     }
1141
1142   /* If the old symbol has non-default visibility, we ignore the new
1143      definition from a dynamic object.  */
1144   if (newdyn
1145       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1146       && !bfd_is_und_section (sec))
1147     {
1148       *skip = TRUE;
1149       /* Make sure this symbol is dynamic.  */
1150       h->ref_dynamic = 1;
1151       hi->ref_dynamic = 1;
1152       /* A protected symbol has external availability. Make sure it is
1153          recorded as dynamic.
1154
1155          FIXME: Should we check type and size for protected symbol?  */
1156       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1157         return bfd_elf_link_record_dynamic_symbol (info, h);
1158       else
1159         return TRUE;
1160     }
1161   else if (!newdyn
1162            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1163            && h->def_dynamic)
1164     {
1165       /* If the new symbol with non-default visibility comes from a
1166          relocatable file and the old definition comes from a dynamic
1167          object, we remove the old definition.  */
1168       if (hi->root.type == bfd_link_hash_indirect)
1169         {
1170           /* Handle the case where the old dynamic definition is
1171              default versioned.  We need to copy the symbol info from
1172              the symbol with default version to the normal one if it
1173              was referenced before.  */
1174           if (h->ref_regular)
1175             {
1176               hi->root.type = h->root.type;
1177               h->root.type = bfd_link_hash_indirect;
1178               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1179
1180               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1181               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1182                 {
1183                   /* If the new symbol is hidden or internal, completely undo
1184                      any dynamic link state.  */
1185                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1186                   h->forced_local = 0;
1187                   h->ref_dynamic = 0;
1188                 }
1189               else
1190                 h->ref_dynamic = 1;
1191
1192               h->def_dynamic = 0;
1193               /* FIXME: Should we check type and size for protected symbol?  */
1194               h->size = 0;
1195               h->type = 0;
1196
1197               h = hi;
1198             }
1199           else
1200             h = hi;
1201         }
1202
1203       /* If the old symbol was undefined before, then it will still be
1204          on the undefs list.  If the new symbol is undefined or
1205          common, we can't make it bfd_link_hash_new here, because new
1206          undefined or common symbols will be added to the undefs list
1207          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1208          added twice to the undefs list.  Also, if the new symbol is
1209          undefweak then we don't want to lose the strong undef.  */
1210       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1211         {
1212           h->root.type = bfd_link_hash_undefined;
1213           h->root.u.undef.abfd = abfd;
1214         }
1215       else
1216         {
1217           h->root.type = bfd_link_hash_new;
1218           h->root.u.undef.abfd = NULL;
1219         }
1220
1221       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1222         {
1223           /* If the new symbol is hidden or internal, completely undo
1224              any dynamic link state.  */
1225           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1226           h->forced_local = 0;
1227           h->ref_dynamic = 0;
1228         }
1229       else
1230         h->ref_dynamic = 1;
1231       h->def_dynamic = 0;
1232       /* FIXME: Should we check type and size for protected symbol?  */
1233       h->size = 0;
1234       h->type = 0;
1235       return TRUE;
1236     }
1237
1238   /* If a new weak symbol definition comes from a regular file and the
1239      old symbol comes from a dynamic library, we treat the new one as
1240      strong.  Similarly, an old weak symbol definition from a regular
1241      file is treated as strong when the new symbol comes from a dynamic
1242      library.  Further, an old weak symbol from a dynamic library is
1243      treated as strong if the new symbol is from a dynamic library.
1244      This reflects the way glibc's ld.so works.
1245
1246      Do this before setting *type_change_ok or *size_change_ok so that
1247      we warn properly when dynamic library symbols are overridden.  */
1248
1249   if (newdef && !newdyn && olddyn)
1250     newweak = FALSE;
1251   if (olddef && newdyn)
1252     oldweak = FALSE;
1253
1254   /* Allow changes between different types of function symbol.  */
1255   if (newfunc && oldfunc)
1256     *type_change_ok = TRUE;
1257
1258   /* It's OK to change the type if either the existing symbol or the
1259      new symbol is weak.  A type change is also OK if the old symbol
1260      is undefined and the new symbol is defined.  */
1261
1262   if (oldweak
1263       || newweak
1264       || (newdef
1265           && h->root.type == bfd_link_hash_undefined))
1266     *type_change_ok = TRUE;
1267
1268   /* It's OK to change the size if either the existing symbol or the
1269      new symbol is weak, or if the old symbol is undefined.  */
1270
1271   if (*type_change_ok
1272       || h->root.type == bfd_link_hash_undefined)
1273     *size_change_ok = TRUE;
1274
1275   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1276      symbol, respectively, appears to be a common symbol in a dynamic
1277      object.  If a symbol appears in an uninitialized section, and is
1278      not weak, and is not a function, then it may be a common symbol
1279      which was resolved when the dynamic object was created.  We want
1280      to treat such symbols specially, because they raise special
1281      considerations when setting the symbol size: if the symbol
1282      appears as a common symbol in a regular object, and the size in
1283      the regular object is larger, we must make sure that we use the
1284      larger size.  This problematic case can always be avoided in C,
1285      but it must be handled correctly when using Fortran shared
1286      libraries.
1287
1288      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1289      likewise for OLDDYNCOMMON and OLDDEF.
1290
1291      Note that this test is just a heuristic, and that it is quite
1292      possible to have an uninitialized symbol in a shared object which
1293      is really a definition, rather than a common symbol.  This could
1294      lead to some minor confusion when the symbol really is a common
1295      symbol in some regular object.  However, I think it will be
1296      harmless.  */
1297
1298   if (newdyn
1299       && newdef
1300       && !newweak
1301       && (sec->flags & SEC_ALLOC) != 0
1302       && (sec->flags & SEC_LOAD) == 0
1303       && sym->st_size > 0
1304       && !newfunc)
1305     newdyncommon = TRUE;
1306   else
1307     newdyncommon = FALSE;
1308
1309   if (olddyn
1310       && olddef
1311       && h->root.type == bfd_link_hash_defined
1312       && h->def_dynamic
1313       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1314       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1315       && h->size > 0
1316       && !oldfunc)
1317     olddyncommon = TRUE;
1318   else
1319     olddyncommon = FALSE;
1320
1321   /* We now know everything about the old and new symbols.  We ask the
1322      backend to check if we can merge them.  */
1323   if (bed->merge_symbol != NULL)
1324     {
1325       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1326         return FALSE;
1327       sec = *psec;
1328     }
1329
1330   /* If both the old and the new symbols look like common symbols in a
1331      dynamic object, set the size of the symbol to the larger of the
1332      two.  */
1333
1334   if (olddyncommon
1335       && newdyncommon
1336       && sym->st_size != h->size)
1337     {
1338       /* Since we think we have two common symbols, issue a multiple
1339          common warning if desired.  Note that we only warn if the
1340          size is different.  If the size is the same, we simply let
1341          the old symbol override the new one as normally happens with
1342          symbols defined in dynamic objects.  */
1343
1344       if (! ((*info->callbacks->multiple_common)
1345              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1346         return FALSE;
1347
1348       if (sym->st_size > h->size)
1349         h->size = sym->st_size;
1350
1351       *size_change_ok = TRUE;
1352     }
1353
1354   /* If we are looking at a dynamic object, and we have found a
1355      definition, we need to see if the symbol was already defined by
1356      some other object.  If so, we want to use the existing
1357      definition, and we do not want to report a multiple symbol
1358      definition error; we do this by clobbering *PSEC to be
1359      bfd_und_section_ptr.
1360
1361      We treat a common symbol as a definition if the symbol in the
1362      shared library is a function, since common symbols always
1363      represent variables; this can cause confusion in principle, but
1364      any such confusion would seem to indicate an erroneous program or
1365      shared library.  We also permit a common symbol in a regular
1366      object to override a weak symbol in a shared object.  */
1367
1368   if (newdyn
1369       && newdef
1370       && (olddef
1371           || (h->root.type == bfd_link_hash_common
1372               && (newweak || newfunc))))
1373     {
1374       *override = TRUE;
1375       newdef = FALSE;
1376       newdyncommon = FALSE;
1377
1378       *psec = sec = bfd_und_section_ptr;
1379       *size_change_ok = TRUE;
1380
1381       /* If we get here when the old symbol is a common symbol, then
1382          we are explicitly letting it override a weak symbol or
1383          function in a dynamic object, and we don't want to warn about
1384          a type change.  If the old symbol is a defined symbol, a type
1385          change warning may still be appropriate.  */
1386
1387       if (h->root.type == bfd_link_hash_common)
1388         *type_change_ok = TRUE;
1389     }
1390
1391   /* Handle the special case of an old common symbol merging with a
1392      new symbol which looks like a common symbol in a shared object.
1393      We change *PSEC and *PVALUE to make the new symbol look like a
1394      common symbol, and let _bfd_generic_link_add_one_symbol do the
1395      right thing.  */
1396
1397   if (newdyncommon
1398       && h->root.type == bfd_link_hash_common)
1399     {
1400       *override = TRUE;
1401       newdef = FALSE;
1402       newdyncommon = FALSE;
1403       *pvalue = sym->st_size;
1404       *psec = sec = bed->common_section (oldsec);
1405       *size_change_ok = TRUE;
1406     }
1407
1408   /* Skip weak definitions of symbols that are already defined.  */
1409   if (newdef && olddef && newweak)
1410     {
1411       /* Don't skip new non-IR weak syms.  */
1412       if (!(oldbfd != NULL
1413             && (oldbfd->flags & BFD_PLUGIN) != 0
1414             && (abfd->flags & BFD_PLUGIN) == 0))
1415         {
1416           newdef = FALSE;
1417           *skip = TRUE;
1418         }
1419
1420       /* Merge st_other.  If the symbol already has a dynamic index,
1421          but visibility says it should not be visible, turn it into a
1422          local symbol.  */
1423       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1424       if (h->dynindx != -1)
1425         switch (ELF_ST_VISIBILITY (h->other))
1426           {
1427           case STV_INTERNAL:
1428           case STV_HIDDEN:
1429             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1430             break;
1431           }
1432     }
1433
1434   /* If the old symbol is from a dynamic object, and the new symbol is
1435      a definition which is not from a dynamic object, then the new
1436      symbol overrides the old symbol.  Symbols from regular files
1437      always take precedence over symbols from dynamic objects, even if
1438      they are defined after the dynamic object in the link.
1439
1440      As above, we again permit a common symbol in a regular object to
1441      override a definition in a shared object if the shared object
1442      symbol is a function or is weak.  */
1443
1444   flip = NULL;
1445   if (!newdyn
1446       && (newdef
1447           || (bfd_is_com_section (sec)
1448               && (oldweak || oldfunc)))
1449       && olddyn
1450       && olddef
1451       && h->def_dynamic)
1452     {
1453       /* Change the hash table entry to undefined, and let
1454          _bfd_generic_link_add_one_symbol do the right thing with the
1455          new definition.  */
1456
1457       h->root.type = bfd_link_hash_undefined;
1458       h->root.u.undef.abfd = h->root.u.def.section->owner;
1459       *size_change_ok = TRUE;
1460
1461       olddef = FALSE;
1462       olddyncommon = FALSE;
1463
1464       /* We again permit a type change when a common symbol may be
1465          overriding a function.  */
1466
1467       if (bfd_is_com_section (sec))
1468         {
1469           if (oldfunc)
1470             {
1471               /* If a common symbol overrides a function, make sure
1472                  that it isn't defined dynamically nor has type
1473                  function.  */
1474               h->def_dynamic = 0;
1475               h->type = STT_NOTYPE;
1476             }
1477           *type_change_ok = TRUE;
1478         }
1479
1480       if (hi->root.type == bfd_link_hash_indirect)
1481         flip = hi;
1482       else
1483         /* This union may have been set to be non-NULL when this symbol
1484            was seen in a dynamic object.  We must force the union to be
1485            NULL, so that it is correct for a regular symbol.  */
1486         h->verinfo.vertree = NULL;
1487     }
1488
1489   /* Handle the special case of a new common symbol merging with an
1490      old symbol that looks like it might be a common symbol defined in
1491      a shared object.  Note that we have already handled the case in
1492      which a new common symbol should simply override the definition
1493      in the shared library.  */
1494
1495   if (! newdyn
1496       && bfd_is_com_section (sec)
1497       && olddyncommon)
1498     {
1499       /* It would be best if we could set the hash table entry to a
1500          common symbol, but we don't know what to use for the section
1501          or the alignment.  */
1502       if (! ((*info->callbacks->multiple_common)
1503              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1504         return FALSE;
1505
1506       /* If the presumed common symbol in the dynamic object is
1507          larger, pretend that the new symbol has its size.  */
1508
1509       if (h->size > *pvalue)
1510         *pvalue = h->size;
1511
1512       /* We need to remember the alignment required by the symbol
1513          in the dynamic object.  */
1514       BFD_ASSERT (pold_alignment);
1515       *pold_alignment = h->root.u.def.section->alignment_power;
1516
1517       olddef = FALSE;
1518       olddyncommon = FALSE;
1519
1520       h->root.type = bfd_link_hash_undefined;
1521       h->root.u.undef.abfd = h->root.u.def.section->owner;
1522
1523       *size_change_ok = TRUE;
1524       *type_change_ok = TRUE;
1525
1526       if (hi->root.type == bfd_link_hash_indirect)
1527         flip = hi;
1528       else
1529         h->verinfo.vertree = NULL;
1530     }
1531
1532   if (flip != NULL)
1533     {
1534       /* Handle the case where we had a versioned symbol in a dynamic
1535          library and now find a definition in a normal object.  In this
1536          case, we make the versioned symbol point to the normal one.  */
1537       flip->root.type = h->root.type;
1538       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1539       h->root.type = bfd_link_hash_indirect;
1540       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1541       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1542       if (h->def_dynamic)
1543         {
1544           h->def_dynamic = 0;
1545           flip->ref_dynamic = 1;
1546         }
1547     }
1548
1549   return TRUE;
1550 }
1551
1552 /* This function is called to create an indirect symbol from the
1553    default for the symbol with the default version if needed. The
1554    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1555    set DYNSYM if the new indirect symbol is dynamic.  */
1556
1557 static bfd_boolean
1558 _bfd_elf_add_default_symbol (bfd *abfd,
1559                              struct bfd_link_info *info,
1560                              struct elf_link_hash_entry *h,
1561                              const char *name,
1562                              Elf_Internal_Sym *sym,
1563                              asection *sec,
1564                              bfd_vma value,
1565                              bfd **poldbfd,
1566                              bfd_boolean *dynsym)
1567 {
1568   bfd_boolean type_change_ok;
1569   bfd_boolean size_change_ok;
1570   bfd_boolean skip;
1571   char *shortname;
1572   struct elf_link_hash_entry *hi;
1573   struct bfd_link_hash_entry *bh;
1574   const struct elf_backend_data *bed;
1575   bfd_boolean collect;
1576   bfd_boolean dynamic;
1577   bfd_boolean override;
1578   char *p;
1579   size_t len, shortlen;
1580   asection *tmp_sec;
1581
1582   /* If this symbol has a version, and it is the default version, we
1583      create an indirect symbol from the default name to the fully
1584      decorated name.  This will cause external references which do not
1585      specify a version to be bound to this version of the symbol.  */
1586   p = strchr (name, ELF_VER_CHR);
1587   if (p == NULL || p[1] != ELF_VER_CHR)
1588     return TRUE;
1589
1590   bed = get_elf_backend_data (abfd);
1591   collect = bed->collect;
1592   dynamic = (abfd->flags & DYNAMIC) != 0;
1593
1594   shortlen = p - name;
1595   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1596   if (shortname == NULL)
1597     return FALSE;
1598   memcpy (shortname, name, shortlen);
1599   shortname[shortlen] = '\0';
1600
1601   /* We are going to create a new symbol.  Merge it with any existing
1602      symbol with this name.  For the purposes of the merge, act as
1603      though we were defining the symbol we just defined, although we
1604      actually going to define an indirect symbol.  */
1605   type_change_ok = FALSE;
1606   size_change_ok = FALSE;
1607   tmp_sec = sec;
1608   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1609                               &hi, poldbfd, NULL, NULL, &skip, &override,
1610                               &type_change_ok, &size_change_ok))
1611     return FALSE;
1612
1613   if (skip)
1614     goto nondefault;
1615
1616   if (! override)
1617     {
1618       bh = &hi->root;
1619       if (! (_bfd_generic_link_add_one_symbol
1620              (info, abfd, shortname, BSF_INDIRECT, bfd_ind_section_ptr,
1621               0, name, FALSE, collect, &bh)))
1622         return FALSE;
1623       hi = (struct elf_link_hash_entry *) bh;
1624     }
1625   else
1626     {
1627       /* In this case the symbol named SHORTNAME is overriding the
1628          indirect symbol we want to add.  We were planning on making
1629          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1630          is the name without a version.  NAME is the fully versioned
1631          name, and it is the default version.
1632
1633          Overriding means that we already saw a definition for the
1634          symbol SHORTNAME in a regular object, and it is overriding
1635          the symbol defined in the dynamic object.
1636
1637          When this happens, we actually want to change NAME, the
1638          symbol we just added, to refer to SHORTNAME.  This will cause
1639          references to NAME in the shared object to become references
1640          to SHORTNAME in the regular object.  This is what we expect
1641          when we override a function in a shared object: that the
1642          references in the shared object will be mapped to the
1643          definition in the regular object.  */
1644
1645       while (hi->root.type == bfd_link_hash_indirect
1646              || hi->root.type == bfd_link_hash_warning)
1647         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1648
1649       h->root.type = bfd_link_hash_indirect;
1650       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1651       if (h->def_dynamic)
1652         {
1653           h->def_dynamic = 0;
1654           hi->ref_dynamic = 1;
1655           if (hi->ref_regular
1656               || hi->def_regular)
1657             {
1658               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1659                 return FALSE;
1660             }
1661         }
1662
1663       /* Now set HI to H, so that the following code will set the
1664          other fields correctly.  */
1665       hi = h;
1666     }
1667
1668   /* Check if HI is a warning symbol.  */
1669   if (hi->root.type == bfd_link_hash_warning)
1670     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1671
1672   /* If there is a duplicate definition somewhere, then HI may not
1673      point to an indirect symbol.  We will have reported an error to
1674      the user in that case.  */
1675
1676   if (hi->root.type == bfd_link_hash_indirect)
1677     {
1678       struct elf_link_hash_entry *ht;
1679
1680       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1681       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1682
1683       /* A reference to the SHORTNAME symbol from a dynamic library
1684          will be satisfied by the versioned symbol at runtime.  In
1685          effect, we have a reference to the versioned symbol.  */
1686       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1687       hi->dynamic_def |= ht->dynamic_def;
1688
1689       /* See if the new flags lead us to realize that the symbol must
1690          be dynamic.  */
1691       if (! *dynsym)
1692         {
1693           if (! dynamic)
1694             {
1695               if (! info->executable
1696                   || hi->def_dynamic
1697                   || hi->ref_dynamic)
1698                 *dynsym = TRUE;
1699             }
1700           else
1701             {
1702               if (hi->ref_regular)
1703                 *dynsym = TRUE;
1704             }
1705         }
1706     }
1707
1708   /* We also need to define an indirection from the nondefault version
1709      of the symbol.  */
1710
1711 nondefault:
1712   len = strlen (name);
1713   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1714   if (shortname == NULL)
1715     return FALSE;
1716   memcpy (shortname, name, shortlen);
1717   memcpy (shortname + shortlen, p + 1, len - shortlen);
1718
1719   /* Once again, merge with any existing symbol.  */
1720   type_change_ok = FALSE;
1721   size_change_ok = FALSE;
1722   tmp_sec = sec;
1723   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1724                               &hi, poldbfd, NULL, NULL, &skip, &override,
1725                               &type_change_ok, &size_change_ok))
1726     return FALSE;
1727
1728   if (skip)
1729     return TRUE;
1730
1731   if (override)
1732     {
1733       /* Here SHORTNAME is a versioned name, so we don't expect to see
1734          the type of override we do in the case above unless it is
1735          overridden by a versioned definition.  */
1736       if (hi->root.type != bfd_link_hash_defined
1737           && hi->root.type != bfd_link_hash_defweak)
1738         (*_bfd_error_handler)
1739           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1740            abfd, shortname);
1741     }
1742   else
1743     {
1744       bh = &hi->root;
1745       if (! (_bfd_generic_link_add_one_symbol
1746              (info, abfd, shortname, BSF_INDIRECT,
1747               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1748         return FALSE;
1749       hi = (struct elf_link_hash_entry *) bh;
1750
1751       /* If there is a duplicate definition somewhere, then HI may not
1752          point to an indirect symbol.  We will have reported an error
1753          to the user in that case.  */
1754
1755       if (hi->root.type == bfd_link_hash_indirect)
1756         {
1757           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1758           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1759           hi->dynamic_def |= h->dynamic_def;
1760
1761           /* See if the new flags lead us to realize that the symbol
1762              must be dynamic.  */
1763           if (! *dynsym)
1764             {
1765               if (! dynamic)
1766                 {
1767                   if (! info->executable
1768                       || hi->ref_dynamic)
1769                     *dynsym = TRUE;
1770                 }
1771               else
1772                 {
1773                   if (hi->ref_regular)
1774                     *dynsym = TRUE;
1775                 }
1776             }
1777         }
1778     }
1779
1780   return TRUE;
1781 }
1782 \f
1783 /* This routine is used to export all defined symbols into the dynamic
1784    symbol table.  It is called via elf_link_hash_traverse.  */
1785
1786 static bfd_boolean
1787 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1788 {
1789   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1790
1791   /* Ignore indirect symbols.  These are added by the versioning code.  */
1792   if (h->root.type == bfd_link_hash_indirect)
1793     return TRUE;
1794
1795   /* Ignore this if we won't export it.  */
1796   if (!eif->info->export_dynamic && !h->dynamic)
1797     return TRUE;
1798
1799   if (h->dynindx == -1
1800       && (h->def_regular || h->ref_regular)
1801       && ! bfd_hide_sym_by_version (eif->info->version_info,
1802                                     h->root.root.string))
1803     {
1804       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1805         {
1806           eif->failed = TRUE;
1807           return FALSE;
1808         }
1809     }
1810
1811   return TRUE;
1812 }
1813 \f
1814 /* Look through the symbols which are defined in other shared
1815    libraries and referenced here.  Update the list of version
1816    dependencies.  This will be put into the .gnu.version_r section.
1817    This function is called via elf_link_hash_traverse.  */
1818
1819 static bfd_boolean
1820 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1821                                          void *data)
1822 {
1823   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1824   Elf_Internal_Verneed *t;
1825   Elf_Internal_Vernaux *a;
1826   bfd_size_type amt;
1827
1828   /* We only care about symbols defined in shared objects with version
1829      information.  */
1830   if (!h->def_dynamic
1831       || h->def_regular
1832       || h->dynindx == -1
1833       || h->verinfo.verdef == NULL
1834       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
1835           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
1836     return TRUE;
1837
1838   /* See if we already know about this version.  */
1839   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1840        t != NULL;
1841        t = t->vn_nextref)
1842     {
1843       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1844         continue;
1845
1846       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1847         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1848           return TRUE;
1849
1850       break;
1851     }
1852
1853   /* This is a new version.  Add it to tree we are building.  */
1854
1855   if (t == NULL)
1856     {
1857       amt = sizeof *t;
1858       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
1859       if (t == NULL)
1860         {
1861           rinfo->failed = TRUE;
1862           return FALSE;
1863         }
1864
1865       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1866       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
1867       elf_tdata (rinfo->info->output_bfd)->verref = t;
1868     }
1869
1870   amt = sizeof *a;
1871   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
1872   if (a == NULL)
1873     {
1874       rinfo->failed = TRUE;
1875       return FALSE;
1876     }
1877
1878   /* Note that we are copying a string pointer here, and testing it
1879      above.  If bfd_elf_string_from_elf_section is ever changed to
1880      discard the string data when low in memory, this will have to be
1881      fixed.  */
1882   a->vna_nodename = h->verinfo.verdef->vd_nodename;
1883
1884   a->vna_flags = h->verinfo.verdef->vd_flags;
1885   a->vna_nextptr = t->vn_auxptr;
1886
1887   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1888   ++rinfo->vers;
1889
1890   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1891
1892   t->vn_auxptr = a;
1893
1894   return TRUE;
1895 }
1896
1897 /* Figure out appropriate versions for all the symbols.  We may not
1898    have the version number script until we have read all of the input
1899    files, so until that point we don't know which symbols should be
1900    local.  This function is called via elf_link_hash_traverse.  */
1901
1902 static bfd_boolean
1903 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
1904 {
1905   struct elf_info_failed *sinfo;
1906   struct bfd_link_info *info;
1907   const struct elf_backend_data *bed;
1908   struct elf_info_failed eif;
1909   char *p;
1910   bfd_size_type amt;
1911
1912   sinfo = (struct elf_info_failed *) data;
1913   info = sinfo->info;
1914
1915   /* Fix the symbol flags.  */
1916   eif.failed = FALSE;
1917   eif.info = info;
1918   if (! _bfd_elf_fix_symbol_flags (h, &eif))
1919     {
1920       if (eif.failed)
1921         sinfo->failed = TRUE;
1922       return FALSE;
1923     }
1924
1925   /* We only need version numbers for symbols defined in regular
1926      objects.  */
1927   if (!h->def_regular)
1928     return TRUE;
1929
1930   bed = get_elf_backend_data (info->output_bfd);
1931   p = strchr (h->root.root.string, ELF_VER_CHR);
1932   if (p != NULL && h->verinfo.vertree == NULL)
1933     {
1934       struct bfd_elf_version_tree *t;
1935       bfd_boolean hidden;
1936
1937       hidden = TRUE;
1938
1939       /* There are two consecutive ELF_VER_CHR characters if this is
1940          not a hidden symbol.  */
1941       ++p;
1942       if (*p == ELF_VER_CHR)
1943         {
1944           hidden = FALSE;
1945           ++p;
1946         }
1947
1948       /* If there is no version string, we can just return out.  */
1949       if (*p == '\0')
1950         {
1951           if (hidden)
1952             h->hidden = 1;
1953           return TRUE;
1954         }
1955
1956       /* Look for the version.  If we find it, it is no longer weak.  */
1957       for (t = sinfo->info->version_info; t != NULL; t = t->next)
1958         {
1959           if (strcmp (t->name, p) == 0)
1960             {
1961               size_t len;
1962               char *alc;
1963               struct bfd_elf_version_expr *d;
1964
1965               len = p - h->root.root.string;
1966               alc = (char *) bfd_malloc (len);
1967               if (alc == NULL)
1968                 {
1969                   sinfo->failed = TRUE;
1970                   return FALSE;
1971                 }
1972               memcpy (alc, h->root.root.string, len - 1);
1973               alc[len - 1] = '\0';
1974               if (alc[len - 2] == ELF_VER_CHR)
1975                 alc[len - 2] = '\0';
1976
1977               h->verinfo.vertree = t;
1978               t->used = TRUE;
1979               d = NULL;
1980
1981               if (t->globals.list != NULL)
1982                 d = (*t->match) (&t->globals, NULL, alc);
1983
1984               /* See if there is anything to force this symbol to
1985                  local scope.  */
1986               if (d == NULL && t->locals.list != NULL)
1987                 {
1988                   d = (*t->match) (&t->locals, NULL, alc);
1989                   if (d != NULL
1990                       && h->dynindx != -1
1991                       && ! info->export_dynamic)
1992                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1993                 }
1994
1995               free (alc);
1996               break;
1997             }
1998         }
1999
2000       /* If we are building an application, we need to create a
2001          version node for this version.  */
2002       if (t == NULL && info->executable)
2003         {
2004           struct bfd_elf_version_tree **pp;
2005           int version_index;
2006
2007           /* If we aren't going to export this symbol, we don't need
2008              to worry about it.  */
2009           if (h->dynindx == -1)
2010             return TRUE;
2011
2012           amt = sizeof *t;
2013           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2014           if (t == NULL)
2015             {
2016               sinfo->failed = TRUE;
2017               return FALSE;
2018             }
2019
2020           t->name = p;
2021           t->name_indx = (unsigned int) -1;
2022           t->used = TRUE;
2023
2024           version_index = 1;
2025           /* Don't count anonymous version tag.  */
2026           if (sinfo->info->version_info != NULL
2027               && sinfo->info->version_info->vernum == 0)
2028             version_index = 0;
2029           for (pp = &sinfo->info->version_info;
2030                *pp != NULL;
2031                pp = &(*pp)->next)
2032             ++version_index;
2033           t->vernum = version_index;
2034
2035           *pp = t;
2036
2037           h->verinfo.vertree = t;
2038         }
2039       else if (t == NULL)
2040         {
2041           /* We could not find the version for a symbol when
2042              generating a shared archive.  Return an error.  */
2043           (*_bfd_error_handler)
2044             (_("%B: version node not found for symbol %s"),
2045              info->output_bfd, h->root.root.string);
2046           bfd_set_error (bfd_error_bad_value);
2047           sinfo->failed = TRUE;
2048           return FALSE;
2049         }
2050
2051       if (hidden)
2052         h->hidden = 1;
2053     }
2054
2055   /* If we don't have a version for this symbol, see if we can find
2056      something.  */
2057   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2058     {
2059       bfd_boolean hide;
2060
2061       h->verinfo.vertree
2062         = bfd_find_version_for_sym (sinfo->info->version_info,
2063                                     h->root.root.string, &hide);
2064       if (h->verinfo.vertree != NULL && hide)
2065         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2066     }
2067
2068   return TRUE;
2069 }
2070 \f
2071 /* Read and swap the relocs from the section indicated by SHDR.  This
2072    may be either a REL or a RELA section.  The relocations are
2073    translated into RELA relocations and stored in INTERNAL_RELOCS,
2074    which should have already been allocated to contain enough space.
2075    The EXTERNAL_RELOCS are a buffer where the external form of the
2076    relocations should be stored.
2077
2078    Returns FALSE if something goes wrong.  */
2079
2080 static bfd_boolean
2081 elf_link_read_relocs_from_section (bfd *abfd,
2082                                    asection *sec,
2083                                    Elf_Internal_Shdr *shdr,
2084                                    void *external_relocs,
2085                                    Elf_Internal_Rela *internal_relocs)
2086 {
2087   const struct elf_backend_data *bed;
2088   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2089   const bfd_byte *erela;
2090   const bfd_byte *erelaend;
2091   Elf_Internal_Rela *irela;
2092   Elf_Internal_Shdr *symtab_hdr;
2093   size_t nsyms;
2094
2095   /* Position ourselves at the start of the section.  */
2096   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2097     return FALSE;
2098
2099   /* Read the relocations.  */
2100   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2101     return FALSE;
2102
2103   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2104   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2105
2106   bed = get_elf_backend_data (abfd);
2107
2108   /* Convert the external relocations to the internal format.  */
2109   if (shdr->sh_entsize == bed->s->sizeof_rel)
2110     swap_in = bed->s->swap_reloc_in;
2111   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2112     swap_in = bed->s->swap_reloca_in;
2113   else
2114     {
2115       bfd_set_error (bfd_error_wrong_format);
2116       return FALSE;
2117     }
2118
2119   erela = (const bfd_byte *) external_relocs;
2120   erelaend = erela + shdr->sh_size;
2121   irela = internal_relocs;
2122   while (erela < erelaend)
2123     {
2124       bfd_vma r_symndx;
2125
2126       (*swap_in) (abfd, erela, irela);
2127       r_symndx = ELF32_R_SYM (irela->r_info);
2128       if (bed->s->arch_size == 64)
2129         r_symndx >>= 24;
2130       if (nsyms > 0)
2131         {
2132           if ((size_t) r_symndx >= nsyms)
2133             {
2134               (*_bfd_error_handler)
2135                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2136                    " for offset 0x%lx in section `%A'"),
2137                  abfd, sec,
2138                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2139               bfd_set_error (bfd_error_bad_value);
2140               return FALSE;
2141             }
2142         }
2143       else if (r_symndx != STN_UNDEF)
2144         {
2145           (*_bfd_error_handler)
2146             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2147                " when the object file has no symbol table"),
2148              abfd, sec,
2149              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2150           bfd_set_error (bfd_error_bad_value);
2151           return FALSE;
2152         }
2153       irela += bed->s->int_rels_per_ext_rel;
2154       erela += shdr->sh_entsize;
2155     }
2156
2157   return TRUE;
2158 }
2159
2160 /* Read and swap the relocs for a section O.  They may have been
2161    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2162    not NULL, they are used as buffers to read into.  They are known to
2163    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2164    the return value is allocated using either malloc or bfd_alloc,
2165    according to the KEEP_MEMORY argument.  If O has two relocation
2166    sections (both REL and RELA relocations), then the REL_HDR
2167    relocations will appear first in INTERNAL_RELOCS, followed by the
2168    RELA_HDR relocations.  */
2169
2170 Elf_Internal_Rela *
2171 _bfd_elf_link_read_relocs (bfd *abfd,
2172                            asection *o,
2173                            void *external_relocs,
2174                            Elf_Internal_Rela *internal_relocs,
2175                            bfd_boolean keep_memory)
2176 {
2177   void *alloc1 = NULL;
2178   Elf_Internal_Rela *alloc2 = NULL;
2179   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2180   struct bfd_elf_section_data *esdo = elf_section_data (o);
2181   Elf_Internal_Rela *internal_rela_relocs;
2182
2183   if (esdo->relocs != NULL)
2184     return esdo->relocs;
2185
2186   if (o->reloc_count == 0)
2187     return NULL;
2188
2189   if (internal_relocs == NULL)
2190     {
2191       bfd_size_type size;
2192
2193       size = o->reloc_count;
2194       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2195       if (keep_memory)
2196         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2197       else
2198         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2199       if (internal_relocs == NULL)
2200         goto error_return;
2201     }
2202
2203   if (external_relocs == NULL)
2204     {
2205       bfd_size_type size = 0;
2206
2207       if (esdo->rel.hdr)
2208         size += esdo->rel.hdr->sh_size;
2209       if (esdo->rela.hdr)
2210         size += esdo->rela.hdr->sh_size;
2211
2212       alloc1 = bfd_malloc (size);
2213       if (alloc1 == NULL)
2214         goto error_return;
2215       external_relocs = alloc1;
2216     }
2217
2218   internal_rela_relocs = internal_relocs;
2219   if (esdo->rel.hdr)
2220     {
2221       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2222                                               external_relocs,
2223                                               internal_relocs))
2224         goto error_return;
2225       external_relocs = (((bfd_byte *) external_relocs)
2226                          + esdo->rel.hdr->sh_size);
2227       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2228                                * bed->s->int_rels_per_ext_rel);
2229     }
2230
2231   if (esdo->rela.hdr
2232       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2233                                               external_relocs,
2234                                               internal_rela_relocs)))
2235     goto error_return;
2236
2237   /* Cache the results for next time, if we can.  */
2238   if (keep_memory)
2239     esdo->relocs = internal_relocs;
2240
2241   if (alloc1 != NULL)
2242     free (alloc1);
2243
2244   /* Don't free alloc2, since if it was allocated we are passing it
2245      back (under the name of internal_relocs).  */
2246
2247   return internal_relocs;
2248
2249  error_return:
2250   if (alloc1 != NULL)
2251     free (alloc1);
2252   if (alloc2 != NULL)
2253     {
2254       if (keep_memory)
2255         bfd_release (abfd, alloc2);
2256       else
2257         free (alloc2);
2258     }
2259   return NULL;
2260 }
2261
2262 /* Compute the size of, and allocate space for, REL_HDR which is the
2263    section header for a section containing relocations for O.  */
2264
2265 static bfd_boolean
2266 _bfd_elf_link_size_reloc_section (bfd *abfd,
2267                                   struct bfd_elf_section_reloc_data *reldata)
2268 {
2269   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2270
2271   /* That allows us to calculate the size of the section.  */
2272   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2273
2274   /* The contents field must last into write_object_contents, so we
2275      allocate it with bfd_alloc rather than malloc.  Also since we
2276      cannot be sure that the contents will actually be filled in,
2277      we zero the allocated space.  */
2278   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2279   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2280     return FALSE;
2281
2282   if (reldata->hashes == NULL && reldata->count)
2283     {
2284       struct elf_link_hash_entry **p;
2285
2286       p = (struct elf_link_hash_entry **)
2287           bfd_zmalloc (reldata->count * sizeof (struct elf_link_hash_entry *));
2288       if (p == NULL)
2289         return FALSE;
2290
2291       reldata->hashes = p;
2292     }
2293
2294   return TRUE;
2295 }
2296
2297 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2298    originated from the section given by INPUT_REL_HDR) to the
2299    OUTPUT_BFD.  */
2300
2301 bfd_boolean
2302 _bfd_elf_link_output_relocs (bfd *output_bfd,
2303                              asection *input_section,
2304                              Elf_Internal_Shdr *input_rel_hdr,
2305                              Elf_Internal_Rela *internal_relocs,
2306                              struct elf_link_hash_entry **rel_hash
2307                                ATTRIBUTE_UNUSED)
2308 {
2309   Elf_Internal_Rela *irela;
2310   Elf_Internal_Rela *irelaend;
2311   bfd_byte *erel;
2312   struct bfd_elf_section_reloc_data *output_reldata;
2313   asection *output_section;
2314   const struct elf_backend_data *bed;
2315   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2316   struct bfd_elf_section_data *esdo;
2317
2318   output_section = input_section->output_section;
2319
2320   bed = get_elf_backend_data (output_bfd);
2321   esdo = elf_section_data (output_section);
2322   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2323     {
2324       output_reldata = &esdo->rel;
2325       swap_out = bed->s->swap_reloc_out;
2326     }
2327   else if (esdo->rela.hdr
2328            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2329     {
2330       output_reldata = &esdo->rela;
2331       swap_out = bed->s->swap_reloca_out;
2332     }
2333   else
2334     {
2335       (*_bfd_error_handler)
2336         (_("%B: relocation size mismatch in %B section %A"),
2337          output_bfd, input_section->owner, input_section);
2338       bfd_set_error (bfd_error_wrong_format);
2339       return FALSE;
2340     }
2341
2342   erel = output_reldata->hdr->contents;
2343   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2344   irela = internal_relocs;
2345   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2346                       * bed->s->int_rels_per_ext_rel);
2347   while (irela < irelaend)
2348     {
2349       (*swap_out) (output_bfd, irela, erel);
2350       irela += bed->s->int_rels_per_ext_rel;
2351       erel += input_rel_hdr->sh_entsize;
2352     }
2353
2354   /* Bump the counter, so that we know where to add the next set of
2355      relocations.  */
2356   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2357
2358   return TRUE;
2359 }
2360 \f
2361 /* Make weak undefined symbols in PIE dynamic.  */
2362
2363 bfd_boolean
2364 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2365                                  struct elf_link_hash_entry *h)
2366 {
2367   if (info->pie
2368       && h->dynindx == -1
2369       && h->root.type == bfd_link_hash_undefweak)
2370     return bfd_elf_link_record_dynamic_symbol (info, h);
2371
2372   return TRUE;
2373 }
2374
2375 /* Fix up the flags for a symbol.  This handles various cases which
2376    can only be fixed after all the input files are seen.  This is
2377    currently called by both adjust_dynamic_symbol and
2378    assign_sym_version, which is unnecessary but perhaps more robust in
2379    the face of future changes.  */
2380
2381 static bfd_boolean
2382 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2383                            struct elf_info_failed *eif)
2384 {
2385   const struct elf_backend_data *bed;
2386
2387   /* If this symbol was mentioned in a non-ELF file, try to set
2388      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2389      permit a non-ELF file to correctly refer to a symbol defined in
2390      an ELF dynamic object.  */
2391   if (h->non_elf)
2392     {
2393       while (h->root.type == bfd_link_hash_indirect)
2394         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2395
2396       if (h->root.type != bfd_link_hash_defined
2397           && h->root.type != bfd_link_hash_defweak)
2398         {
2399           h->ref_regular = 1;
2400           h->ref_regular_nonweak = 1;
2401         }
2402       else
2403         {
2404           if (h->root.u.def.section->owner != NULL
2405               && (bfd_get_flavour (h->root.u.def.section->owner)
2406                   == bfd_target_elf_flavour))
2407             {
2408               h->ref_regular = 1;
2409               h->ref_regular_nonweak = 1;
2410             }
2411           else
2412             h->def_regular = 1;
2413         }
2414
2415       if (h->dynindx == -1
2416           && (h->def_dynamic
2417               || h->ref_dynamic))
2418         {
2419           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2420             {
2421               eif->failed = TRUE;
2422               return FALSE;
2423             }
2424         }
2425     }
2426   else
2427     {
2428       /* Unfortunately, NON_ELF is only correct if the symbol
2429          was first seen in a non-ELF file.  Fortunately, if the symbol
2430          was first seen in an ELF file, we're probably OK unless the
2431          symbol was defined in a non-ELF file.  Catch that case here.
2432          FIXME: We're still in trouble if the symbol was first seen in
2433          a dynamic object, and then later in a non-ELF regular object.  */
2434       if ((h->root.type == bfd_link_hash_defined
2435            || h->root.type == bfd_link_hash_defweak)
2436           && !h->def_regular
2437           && (h->root.u.def.section->owner != NULL
2438               ? (bfd_get_flavour (h->root.u.def.section->owner)
2439                  != bfd_target_elf_flavour)
2440               : (bfd_is_abs_section (h->root.u.def.section)
2441                  && !h->def_dynamic)))
2442         h->def_regular = 1;
2443     }
2444
2445   /* Backend specific symbol fixup.  */
2446   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2447   if (bed->elf_backend_fixup_symbol
2448       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2449     return FALSE;
2450
2451   /* If this is a final link, and the symbol was defined as a common
2452      symbol in a regular object file, and there was no definition in
2453      any dynamic object, then the linker will have allocated space for
2454      the symbol in a common section but the DEF_REGULAR
2455      flag will not have been set.  */
2456   if (h->root.type == bfd_link_hash_defined
2457       && !h->def_regular
2458       && h->ref_regular
2459       && !h->def_dynamic
2460       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2461     h->def_regular = 1;
2462
2463   /* If -Bsymbolic was used (which means to bind references to global
2464      symbols to the definition within the shared object), and this
2465      symbol was defined in a regular object, then it actually doesn't
2466      need a PLT entry.  Likewise, if the symbol has non-default
2467      visibility.  If the symbol has hidden or internal visibility, we
2468      will force it local.  */
2469   if (h->needs_plt
2470       && eif->info->shared
2471       && is_elf_hash_table (eif->info->hash)
2472       && (SYMBOLIC_BIND (eif->info, h)
2473           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2474       && h->def_regular)
2475     {
2476       bfd_boolean force_local;
2477
2478       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2479                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2480       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2481     }
2482
2483   /* If a weak undefined symbol has non-default visibility, we also
2484      hide it from the dynamic linker.  */
2485   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2486       && h->root.type == bfd_link_hash_undefweak)
2487     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2488
2489   /* If this is a weak defined symbol in a dynamic object, and we know
2490      the real definition in the dynamic object, copy interesting flags
2491      over to the real definition.  */
2492   if (h->u.weakdef != NULL)
2493     {
2494       /* If the real definition is defined by a regular object file,
2495          don't do anything special.  See the longer description in
2496          _bfd_elf_adjust_dynamic_symbol, below.  */
2497       if (h->u.weakdef->def_regular)
2498         h->u.weakdef = NULL;
2499       else
2500         {
2501           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2502
2503           while (h->root.type == bfd_link_hash_indirect)
2504             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2505
2506           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2507                       || h->root.type == bfd_link_hash_defweak);
2508           BFD_ASSERT (weakdef->def_dynamic);
2509           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2510                       || weakdef->root.type == bfd_link_hash_defweak);
2511           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2512         }
2513     }
2514
2515   return TRUE;
2516 }
2517
2518 /* Make the backend pick a good value for a dynamic symbol.  This is
2519    called via elf_link_hash_traverse, and also calls itself
2520    recursively.  */
2521
2522 static bfd_boolean
2523 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2524 {
2525   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2526   bfd *dynobj;
2527   const struct elf_backend_data *bed;
2528
2529   if (! is_elf_hash_table (eif->info->hash))
2530     return FALSE;
2531
2532   /* Ignore indirect symbols.  These are added by the versioning code.  */
2533   if (h->root.type == bfd_link_hash_indirect)
2534     return TRUE;
2535
2536   /* Fix the symbol flags.  */
2537   if (! _bfd_elf_fix_symbol_flags (h, eif))
2538     return FALSE;
2539
2540   /* If this symbol does not require a PLT entry, and it is not
2541      defined by a dynamic object, or is not referenced by a regular
2542      object, ignore it.  We do have to handle a weak defined symbol,
2543      even if no regular object refers to it, if we decided to add it
2544      to the dynamic symbol table.  FIXME: Do we normally need to worry
2545      about symbols which are defined by one dynamic object and
2546      referenced by another one?  */
2547   if (!h->needs_plt
2548       && h->type != STT_GNU_IFUNC
2549       && (h->def_regular
2550           || !h->def_dynamic
2551           || (!h->ref_regular
2552               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2553     {
2554       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2555       return TRUE;
2556     }
2557
2558   /* If we've already adjusted this symbol, don't do it again.  This
2559      can happen via a recursive call.  */
2560   if (h->dynamic_adjusted)
2561     return TRUE;
2562
2563   /* Don't look at this symbol again.  Note that we must set this
2564      after checking the above conditions, because we may look at a
2565      symbol once, decide not to do anything, and then get called
2566      recursively later after REF_REGULAR is set below.  */
2567   h->dynamic_adjusted = 1;
2568
2569   /* If this is a weak definition, and we know a real definition, and
2570      the real symbol is not itself defined by a regular object file,
2571      then get a good value for the real definition.  We handle the
2572      real symbol first, for the convenience of the backend routine.
2573
2574      Note that there is a confusing case here.  If the real definition
2575      is defined by a regular object file, we don't get the real symbol
2576      from the dynamic object, but we do get the weak symbol.  If the
2577      processor backend uses a COPY reloc, then if some routine in the
2578      dynamic object changes the real symbol, we will not see that
2579      change in the corresponding weak symbol.  This is the way other
2580      ELF linkers work as well, and seems to be a result of the shared
2581      library model.
2582
2583      I will clarify this issue.  Most SVR4 shared libraries define the
2584      variable _timezone and define timezone as a weak synonym.  The
2585      tzset call changes _timezone.  If you write
2586        extern int timezone;
2587        int _timezone = 5;
2588        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2589      you might expect that, since timezone is a synonym for _timezone,
2590      the same number will print both times.  However, if the processor
2591      backend uses a COPY reloc, then actually timezone will be copied
2592      into your process image, and, since you define _timezone
2593      yourself, _timezone will not.  Thus timezone and _timezone will
2594      wind up at different memory locations.  The tzset call will set
2595      _timezone, leaving timezone unchanged.  */
2596
2597   if (h->u.weakdef != NULL)
2598     {
2599       /* If we get to this point, there is an implicit reference to
2600          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2601       h->u.weakdef->ref_regular = 1;
2602
2603       /* Ensure that the backend adjust_dynamic_symbol function sees
2604          H->U.WEAKDEF before H by recursively calling ourselves.  */
2605       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2606         return FALSE;
2607     }
2608
2609   /* If a symbol has no type and no size and does not require a PLT
2610      entry, then we are probably about to do the wrong thing here: we
2611      are probably going to create a COPY reloc for an empty object.
2612      This case can arise when a shared object is built with assembly
2613      code, and the assembly code fails to set the symbol type.  */
2614   if (h->size == 0
2615       && h->type == STT_NOTYPE
2616       && !h->needs_plt)
2617     (*_bfd_error_handler)
2618       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2619        h->root.root.string);
2620
2621   dynobj = elf_hash_table (eif->info)->dynobj;
2622   bed = get_elf_backend_data (dynobj);
2623
2624   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2625     {
2626       eif->failed = TRUE;
2627       return FALSE;
2628     }
2629
2630   return TRUE;
2631 }
2632
2633 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2634    DYNBSS.  */
2635
2636 bfd_boolean
2637 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2638                               struct elf_link_hash_entry *h,
2639                               asection *dynbss)
2640 {
2641   unsigned int power_of_two;
2642   bfd_vma mask;
2643   asection *sec = h->root.u.def.section;
2644
2645   /* The section aligment of definition is the maximum alignment
2646      requirement of symbols defined in the section.  Since we don't
2647      know the symbol alignment requirement, we start with the
2648      maximum alignment and check low bits of the symbol address
2649      for the minimum alignment.  */
2650   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2651   mask = ((bfd_vma) 1 << power_of_two) - 1;
2652   while ((h->root.u.def.value & mask) != 0)
2653     {
2654        mask >>= 1;
2655        --power_of_two;
2656     }
2657
2658   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2659                                                 dynbss))
2660     {
2661       /* Adjust the section alignment if needed.  */
2662       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2663                                        power_of_two))
2664         return FALSE;
2665     }
2666
2667   /* We make sure that the symbol will be aligned properly.  */
2668   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2669
2670   /* Define the symbol as being at this point in DYNBSS.  */
2671   h->root.u.def.section = dynbss;
2672   h->root.u.def.value = dynbss->size;
2673
2674   /* Increment the size of DYNBSS to make room for the symbol.  */
2675   dynbss->size += h->size;
2676
2677   if (h->protected_def)
2678     info->callbacks->einfo
2679       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2680        h->root.root.string);
2681
2682   return TRUE;
2683 }
2684
2685 /* Adjust all external symbols pointing into SEC_MERGE sections
2686    to reflect the object merging within the sections.  */
2687
2688 static bfd_boolean
2689 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2690 {
2691   asection *sec;
2692
2693   if ((h->root.type == bfd_link_hash_defined
2694        || h->root.type == bfd_link_hash_defweak)
2695       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2696       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2697     {
2698       bfd *output_bfd = (bfd *) data;
2699
2700       h->root.u.def.value =
2701         _bfd_merged_section_offset (output_bfd,
2702                                     &h->root.u.def.section,
2703                                     elf_section_data (sec)->sec_info,
2704                                     h->root.u.def.value);
2705     }
2706
2707   return TRUE;
2708 }
2709
2710 /* Returns false if the symbol referred to by H should be considered
2711    to resolve local to the current module, and true if it should be
2712    considered to bind dynamically.  */
2713
2714 bfd_boolean
2715 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2716                            struct bfd_link_info *info,
2717                            bfd_boolean not_local_protected)
2718 {
2719   bfd_boolean binding_stays_local_p;
2720   const struct elf_backend_data *bed;
2721   struct elf_link_hash_table *hash_table;
2722
2723   if (h == NULL)
2724     return FALSE;
2725
2726   while (h->root.type == bfd_link_hash_indirect
2727          || h->root.type == bfd_link_hash_warning)
2728     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2729
2730   /* If it was forced local, then clearly it's not dynamic.  */
2731   if (h->dynindx == -1)
2732     return FALSE;
2733   if (h->forced_local)
2734     return FALSE;
2735
2736   /* Identify the cases where name binding rules say that a
2737      visible symbol resolves locally.  */
2738   binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2739
2740   switch (ELF_ST_VISIBILITY (h->other))
2741     {
2742     case STV_INTERNAL:
2743     case STV_HIDDEN:
2744       return FALSE;
2745
2746     case STV_PROTECTED:
2747       hash_table = elf_hash_table (info);
2748       if (!is_elf_hash_table (hash_table))
2749         return FALSE;
2750
2751       bed = get_elf_backend_data (hash_table->dynobj);
2752
2753       /* Proper resolution for function pointer equality may require
2754          that these symbols perhaps be resolved dynamically, even though
2755          we should be resolving them to the current module.  */
2756       if (!not_local_protected || !bed->is_function_type (h->type))
2757         binding_stays_local_p = TRUE;
2758       break;
2759
2760     default:
2761       break;
2762     }
2763
2764   /* If it isn't defined locally, then clearly it's dynamic.  */
2765   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2766     return TRUE;
2767
2768   /* Otherwise, the symbol is dynamic if binding rules don't tell
2769      us that it remains local.  */
2770   return !binding_stays_local_p;
2771 }
2772
2773 /* Return true if the symbol referred to by H should be considered
2774    to resolve local to the current module, and false otherwise.  Differs
2775    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2776    undefined symbols.  The two functions are virtually identical except
2777    for the place where forced_local and dynindx == -1 are tested.  If
2778    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2779    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2780    the symbol is local only for defined symbols.
2781    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2782    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2783    treatment of undefined weak symbols.  For those that do not make
2784    undefined weak symbols dynamic, both functions may return false.  */
2785
2786 bfd_boolean
2787 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2788                               struct bfd_link_info *info,
2789                               bfd_boolean local_protected)
2790 {
2791   const struct elf_backend_data *bed;
2792   struct elf_link_hash_table *hash_table;
2793
2794   /* If it's a local sym, of course we resolve locally.  */
2795   if (h == NULL)
2796     return TRUE;
2797
2798   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2799   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2800       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2801     return TRUE;
2802
2803   /* Common symbols that become definitions don't get the DEF_REGULAR
2804      flag set, so test it first, and don't bail out.  */
2805   if (ELF_COMMON_DEF_P (h))
2806     /* Do nothing.  */;
2807   /* If we don't have a definition in a regular file, then we can't
2808      resolve locally.  The sym is either undefined or dynamic.  */
2809   else if (!h->def_regular)
2810     return FALSE;
2811
2812   /* Forced local symbols resolve locally.  */
2813   if (h->forced_local)
2814     return TRUE;
2815
2816   /* As do non-dynamic symbols.  */
2817   if (h->dynindx == -1)
2818     return TRUE;
2819
2820   /* At this point, we know the symbol is defined and dynamic.  In an
2821      executable it must resolve locally, likewise when building symbolic
2822      shared libraries.  */
2823   if (info->executable || SYMBOLIC_BIND (info, h))
2824     return TRUE;
2825
2826   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2827      with default visibility might not resolve locally.  */
2828   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2829     return FALSE;
2830
2831   hash_table = elf_hash_table (info);
2832   if (!is_elf_hash_table (hash_table))
2833     return TRUE;
2834
2835   bed = get_elf_backend_data (hash_table->dynobj);
2836
2837   /* STV_PROTECTED non-function symbols are local.  */
2838   if (!bed->is_function_type (h->type))
2839     return TRUE;
2840
2841   /* Function pointer equality tests may require that STV_PROTECTED
2842      symbols be treated as dynamic symbols.  If the address of a
2843      function not defined in an executable is set to that function's
2844      plt entry in the executable, then the address of the function in
2845      a shared library must also be the plt entry in the executable.  */
2846   return local_protected;
2847 }
2848
2849 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2850    aligned.  Returns the first TLS output section.  */
2851
2852 struct bfd_section *
2853 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2854 {
2855   struct bfd_section *sec, *tls;
2856   unsigned int align = 0;
2857
2858   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2859     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2860       break;
2861   tls = sec;
2862
2863   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2864     if (sec->alignment_power > align)
2865       align = sec->alignment_power;
2866
2867   elf_hash_table (info)->tls_sec = tls;
2868
2869   /* Ensure the alignment of the first section is the largest alignment,
2870      so that the tls segment starts aligned.  */
2871   if (tls != NULL)
2872     tls->alignment_power = align;
2873
2874   return tls;
2875 }
2876
2877 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2878 static bfd_boolean
2879 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2880                                   Elf_Internal_Sym *sym)
2881 {
2882   const struct elf_backend_data *bed;
2883
2884   /* Local symbols do not count, but target specific ones might.  */
2885   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2886       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2887     return FALSE;
2888
2889   bed = get_elf_backend_data (abfd);
2890   /* Function symbols do not count.  */
2891   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
2892     return FALSE;
2893
2894   /* If the section is undefined, then so is the symbol.  */
2895   if (sym->st_shndx == SHN_UNDEF)
2896     return FALSE;
2897
2898   /* If the symbol is defined in the common section, then
2899      it is a common definition and so does not count.  */
2900   if (bed->common_definition (sym))
2901     return FALSE;
2902
2903   /* If the symbol is in a target specific section then we
2904      must rely upon the backend to tell us what it is.  */
2905   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
2906     /* FIXME - this function is not coded yet:
2907
2908        return _bfd_is_global_symbol_definition (abfd, sym);
2909
2910        Instead for now assume that the definition is not global,
2911        Even if this is wrong, at least the linker will behave
2912        in the same way that it used to do.  */
2913     return FALSE;
2914
2915   return TRUE;
2916 }
2917
2918 /* Search the symbol table of the archive element of the archive ABFD
2919    whose archive map contains a mention of SYMDEF, and determine if
2920    the symbol is defined in this element.  */
2921 static bfd_boolean
2922 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
2923 {
2924   Elf_Internal_Shdr * hdr;
2925   bfd_size_type symcount;
2926   bfd_size_type extsymcount;
2927   bfd_size_type extsymoff;
2928   Elf_Internal_Sym *isymbuf;
2929   Elf_Internal_Sym *isym;
2930   Elf_Internal_Sym *isymend;
2931   bfd_boolean result;
2932
2933   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
2934   if (abfd == NULL)
2935     return FALSE;
2936
2937   if (! bfd_check_format (abfd, bfd_object))
2938     return FALSE;
2939
2940   /* Select the appropriate symbol table.  */
2941   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
2942     hdr = &elf_tdata (abfd)->symtab_hdr;
2943   else
2944     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2945
2946   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
2947
2948   /* The sh_info field of the symtab header tells us where the
2949      external symbols start.  We don't care about the local symbols.  */
2950   if (elf_bad_symtab (abfd))
2951     {
2952       extsymcount = symcount;
2953       extsymoff = 0;
2954     }
2955   else
2956     {
2957       extsymcount = symcount - hdr->sh_info;
2958       extsymoff = hdr->sh_info;
2959     }
2960
2961   if (extsymcount == 0)
2962     return FALSE;
2963
2964   /* Read in the symbol table.  */
2965   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
2966                                   NULL, NULL, NULL);
2967   if (isymbuf == NULL)
2968     return FALSE;
2969
2970   /* Scan the symbol table looking for SYMDEF.  */
2971   result = FALSE;
2972   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
2973     {
2974       const char *name;
2975
2976       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
2977                                               isym->st_name);
2978       if (name == NULL)
2979         break;
2980
2981       if (strcmp (name, symdef->name) == 0)
2982         {
2983           result = is_global_data_symbol_definition (abfd, isym);
2984           break;
2985         }
2986     }
2987
2988   free (isymbuf);
2989
2990   return result;
2991 }
2992 \f
2993 /* Add an entry to the .dynamic table.  */
2994
2995 bfd_boolean
2996 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
2997                             bfd_vma tag,
2998                             bfd_vma val)
2999 {
3000   struct elf_link_hash_table *hash_table;
3001   const struct elf_backend_data *bed;
3002   asection *s;
3003   bfd_size_type newsize;
3004   bfd_byte *newcontents;
3005   Elf_Internal_Dyn dyn;
3006
3007   hash_table = elf_hash_table (info);
3008   if (! is_elf_hash_table (hash_table))
3009     return FALSE;
3010
3011   bed = get_elf_backend_data (hash_table->dynobj);
3012   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3013   BFD_ASSERT (s != NULL);
3014
3015   newsize = s->size + bed->s->sizeof_dyn;
3016   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3017   if (newcontents == NULL)
3018     return FALSE;
3019
3020   dyn.d_tag = tag;
3021   dyn.d_un.d_val = val;
3022   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3023
3024   s->size = newsize;
3025   s->contents = newcontents;
3026
3027   return TRUE;
3028 }
3029
3030 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3031    otherwise just check whether one already exists.  Returns -1 on error,
3032    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3033
3034 static int
3035 elf_add_dt_needed_tag (bfd *abfd,
3036                        struct bfd_link_info *info,
3037                        const char *soname,
3038                        bfd_boolean do_it)
3039 {
3040   struct elf_link_hash_table *hash_table;
3041   bfd_size_type strindex;
3042
3043   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3044     return -1;
3045
3046   hash_table = elf_hash_table (info);
3047   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3048   if (strindex == (bfd_size_type) -1)
3049     return -1;
3050
3051   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3052     {
3053       asection *sdyn;
3054       const struct elf_backend_data *bed;
3055       bfd_byte *extdyn;
3056
3057       bed = get_elf_backend_data (hash_table->dynobj);
3058       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3059       if (sdyn != NULL)
3060         for (extdyn = sdyn->contents;
3061              extdyn < sdyn->contents + sdyn->size;
3062              extdyn += bed->s->sizeof_dyn)
3063           {
3064             Elf_Internal_Dyn dyn;
3065
3066             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3067             if (dyn.d_tag == DT_NEEDED
3068                 && dyn.d_un.d_val == strindex)
3069               {
3070                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3071                 return 1;
3072               }
3073           }
3074     }
3075
3076   if (do_it)
3077     {
3078       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3079         return -1;
3080
3081       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3082         return -1;
3083     }
3084   else
3085     /* We were just checking for existence of the tag.  */
3086     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3087
3088   return 0;
3089 }
3090
3091 static bfd_boolean
3092 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3093 {
3094   for (; needed != NULL; needed = needed->next)
3095     if ((elf_dyn_lib_class (needed->by) & DYN_AS_NEEDED) == 0
3096         && strcmp (soname, needed->name) == 0)
3097       return TRUE;
3098
3099   return FALSE;
3100 }
3101
3102 /* Sort symbol by value, section, and size.  */
3103 static int
3104 elf_sort_symbol (const void *arg1, const void *arg2)
3105 {
3106   const struct elf_link_hash_entry *h1;
3107   const struct elf_link_hash_entry *h2;
3108   bfd_signed_vma vdiff;
3109
3110   h1 = *(const struct elf_link_hash_entry **) arg1;
3111   h2 = *(const struct elf_link_hash_entry **) arg2;
3112   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3113   if (vdiff != 0)
3114     return vdiff > 0 ? 1 : -1;
3115   else
3116     {
3117       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3118       if (sdiff != 0)
3119         return sdiff > 0 ? 1 : -1;
3120     }
3121   vdiff = h1->size - h2->size;
3122   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3123 }
3124
3125 /* This function is used to adjust offsets into .dynstr for
3126    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3127
3128 static bfd_boolean
3129 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3130 {
3131   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3132
3133   if (h->dynindx != -1)
3134     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3135   return TRUE;
3136 }
3137
3138 /* Assign string offsets in .dynstr, update all structures referencing
3139    them.  */
3140
3141 static bfd_boolean
3142 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3143 {
3144   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3145   struct elf_link_local_dynamic_entry *entry;
3146   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3147   bfd *dynobj = hash_table->dynobj;
3148   asection *sdyn;
3149   bfd_size_type size;
3150   const struct elf_backend_data *bed;
3151   bfd_byte *extdyn;
3152
3153   _bfd_elf_strtab_finalize (dynstr);
3154   size = _bfd_elf_strtab_size (dynstr);
3155
3156   bed = get_elf_backend_data (dynobj);
3157   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3158   BFD_ASSERT (sdyn != NULL);
3159
3160   /* Update all .dynamic entries referencing .dynstr strings.  */
3161   for (extdyn = sdyn->contents;
3162        extdyn < sdyn->contents + sdyn->size;
3163        extdyn += bed->s->sizeof_dyn)
3164     {
3165       Elf_Internal_Dyn dyn;
3166
3167       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3168       switch (dyn.d_tag)
3169         {
3170         case DT_STRSZ:
3171           dyn.d_un.d_val = size;
3172           break;
3173         case DT_NEEDED:
3174         case DT_SONAME:
3175         case DT_RPATH:
3176         case DT_RUNPATH:
3177         case DT_FILTER:
3178         case DT_AUXILIARY:
3179         case DT_AUDIT:
3180         case DT_DEPAUDIT:
3181           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3182           break;
3183         default:
3184           continue;
3185         }
3186       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3187     }
3188
3189   /* Now update local dynamic symbols.  */
3190   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3191     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3192                                                   entry->isym.st_name);
3193
3194   /* And the rest of dynamic symbols.  */
3195   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3196
3197   /* Adjust version definitions.  */
3198   if (elf_tdata (output_bfd)->cverdefs)
3199     {
3200       asection *s;
3201       bfd_byte *p;
3202       bfd_size_type i;
3203       Elf_Internal_Verdef def;
3204       Elf_Internal_Verdaux defaux;
3205
3206       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3207       p = s->contents;
3208       do
3209         {
3210           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3211                                    &def);
3212           p += sizeof (Elf_External_Verdef);
3213           if (def.vd_aux != sizeof (Elf_External_Verdef))
3214             continue;
3215           for (i = 0; i < def.vd_cnt; ++i)
3216             {
3217               _bfd_elf_swap_verdaux_in (output_bfd,
3218                                         (Elf_External_Verdaux *) p, &defaux);
3219               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3220                                                         defaux.vda_name);
3221               _bfd_elf_swap_verdaux_out (output_bfd,
3222                                          &defaux, (Elf_External_Verdaux *) p);
3223               p += sizeof (Elf_External_Verdaux);
3224             }
3225         }
3226       while (def.vd_next);
3227     }
3228
3229   /* Adjust version references.  */
3230   if (elf_tdata (output_bfd)->verref)
3231     {
3232       asection *s;
3233       bfd_byte *p;
3234       bfd_size_type i;
3235       Elf_Internal_Verneed need;
3236       Elf_Internal_Vernaux needaux;
3237
3238       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3239       p = s->contents;
3240       do
3241         {
3242           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3243                                     &need);
3244           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3245           _bfd_elf_swap_verneed_out (output_bfd, &need,
3246                                      (Elf_External_Verneed *) p);
3247           p += sizeof (Elf_External_Verneed);
3248           for (i = 0; i < need.vn_cnt; ++i)
3249             {
3250               _bfd_elf_swap_vernaux_in (output_bfd,
3251                                         (Elf_External_Vernaux *) p, &needaux);
3252               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3253                                                          needaux.vna_name);
3254               _bfd_elf_swap_vernaux_out (output_bfd,
3255                                          &needaux,
3256                                          (Elf_External_Vernaux *) p);
3257               p += sizeof (Elf_External_Vernaux);
3258             }
3259         }
3260       while (need.vn_next);
3261     }
3262
3263   return TRUE;
3264 }
3265 \f
3266 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3267    The default is to only match when the INPUT and OUTPUT are exactly
3268    the same target.  */
3269
3270 bfd_boolean
3271 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3272                                     const bfd_target *output)
3273 {
3274   return input == output;
3275 }
3276
3277 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3278    This version is used when different targets for the same architecture
3279    are virtually identical.  */
3280
3281 bfd_boolean
3282 _bfd_elf_relocs_compatible (const bfd_target *input,
3283                             const bfd_target *output)
3284 {
3285   const struct elf_backend_data *obed, *ibed;
3286
3287   if (input == output)
3288     return TRUE;
3289
3290   ibed = xvec_get_elf_backend_data (input);
3291   obed = xvec_get_elf_backend_data (output);
3292
3293   if (ibed->arch != obed->arch)
3294     return FALSE;
3295
3296   /* If both backends are using this function, deem them compatible.  */
3297   return ibed->relocs_compatible == obed->relocs_compatible;
3298 }
3299
3300 /* Make a special call to the linker "notice" function to tell it that
3301    we are about to handle an as-needed lib, or have finished
3302    processing the lib.  */ 
3303
3304 bfd_boolean
3305 _bfd_elf_notice_as_needed (bfd *ibfd,
3306                            struct bfd_link_info *info,
3307                            enum notice_asneeded_action act)
3308 {
3309   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3310 }
3311
3312 /* Add symbols from an ELF object file to the linker hash table.  */
3313
3314 static bfd_boolean
3315 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3316 {
3317   Elf_Internal_Ehdr *ehdr;
3318   Elf_Internal_Shdr *hdr;
3319   bfd_size_type symcount;
3320   bfd_size_type extsymcount;
3321   bfd_size_type extsymoff;
3322   struct elf_link_hash_entry **sym_hash;
3323   bfd_boolean dynamic;
3324   Elf_External_Versym *extversym = NULL;
3325   Elf_External_Versym *ever;
3326   struct elf_link_hash_entry *weaks;
3327   struct elf_link_hash_entry **nondeflt_vers = NULL;
3328   bfd_size_type nondeflt_vers_cnt = 0;
3329   Elf_Internal_Sym *isymbuf = NULL;
3330   Elf_Internal_Sym *isym;
3331   Elf_Internal_Sym *isymend;
3332   const struct elf_backend_data *bed;
3333   bfd_boolean add_needed;
3334   struct elf_link_hash_table *htab;
3335   bfd_size_type amt;
3336   void *alloc_mark = NULL;
3337   struct bfd_hash_entry **old_table = NULL;
3338   unsigned int old_size = 0;
3339   unsigned int old_count = 0;
3340   void *old_tab = NULL;
3341   void *old_ent;
3342   struct bfd_link_hash_entry *old_undefs = NULL;
3343   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3344   long old_dynsymcount = 0;
3345   bfd_size_type old_dynstr_size = 0;
3346   size_t tabsize = 0;
3347   asection *s;
3348   bfd_boolean just_syms;
3349
3350   htab = elf_hash_table (info);
3351   bed = get_elf_backend_data (abfd);
3352
3353   if ((abfd->flags & DYNAMIC) == 0)
3354     dynamic = FALSE;
3355   else
3356     {
3357       dynamic = TRUE;
3358
3359       /* You can't use -r against a dynamic object.  Also, there's no
3360          hope of using a dynamic object which does not exactly match
3361          the format of the output file.  */
3362       if (info->relocatable
3363           || !is_elf_hash_table (htab)
3364           || info->output_bfd->xvec != abfd->xvec)
3365         {
3366           if (info->relocatable)
3367             bfd_set_error (bfd_error_invalid_operation);
3368           else
3369             bfd_set_error (bfd_error_wrong_format);
3370           goto error_return;
3371         }
3372     }
3373
3374   ehdr = elf_elfheader (abfd);
3375   if (info->warn_alternate_em
3376       && bed->elf_machine_code != ehdr->e_machine
3377       && ((bed->elf_machine_alt1 != 0
3378            && ehdr->e_machine == bed->elf_machine_alt1)
3379           || (bed->elf_machine_alt2 != 0
3380               && ehdr->e_machine == bed->elf_machine_alt2)))
3381     info->callbacks->einfo
3382       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3383        ehdr->e_machine, abfd, bed->elf_machine_code);
3384
3385   /* As a GNU extension, any input sections which are named
3386      .gnu.warning.SYMBOL are treated as warning symbols for the given
3387      symbol.  This differs from .gnu.warning sections, which generate
3388      warnings when they are included in an output file.  */
3389   /* PR 12761: Also generate this warning when building shared libraries.  */
3390   for (s = abfd->sections; s != NULL; s = s->next)
3391     {
3392       const char *name;
3393
3394       name = bfd_get_section_name (abfd, s);
3395       if (CONST_STRNEQ (name, ".gnu.warning."))
3396         {
3397           char *msg;
3398           bfd_size_type sz;
3399
3400           name += sizeof ".gnu.warning." - 1;
3401
3402           /* If this is a shared object, then look up the symbol
3403              in the hash table.  If it is there, and it is already
3404              been defined, then we will not be using the entry
3405              from this shared object, so we don't need to warn.
3406              FIXME: If we see the definition in a regular object
3407              later on, we will warn, but we shouldn't.  The only
3408              fix is to keep track of what warnings we are supposed
3409              to emit, and then handle them all at the end of the
3410              link.  */
3411           if (dynamic)
3412             {
3413               struct elf_link_hash_entry *h;
3414
3415               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3416
3417               /* FIXME: What about bfd_link_hash_common?  */
3418               if (h != NULL
3419                   && (h->root.type == bfd_link_hash_defined
3420                       || h->root.type == bfd_link_hash_defweak))
3421                 continue;
3422             }
3423
3424           sz = s->size;
3425           msg = (char *) bfd_alloc (abfd, sz + 1);
3426           if (msg == NULL)
3427             goto error_return;
3428
3429           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3430             goto error_return;
3431
3432           msg[sz] = '\0';
3433
3434           if (! (_bfd_generic_link_add_one_symbol
3435                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3436                   FALSE, bed->collect, NULL)))
3437             goto error_return;
3438
3439           if (!info->relocatable && info->executable)
3440             {
3441               /* Clobber the section size so that the warning does
3442                  not get copied into the output file.  */
3443               s->size = 0;
3444
3445               /* Also set SEC_EXCLUDE, so that symbols defined in
3446                  the warning section don't get copied to the output.  */
3447               s->flags |= SEC_EXCLUDE;
3448             }
3449         }
3450     }
3451
3452   just_syms = ((s = abfd->sections) != NULL
3453                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3454
3455   add_needed = TRUE;
3456   if (! dynamic)
3457     {
3458       /* If we are creating a shared library, create all the dynamic
3459          sections immediately.  We need to attach them to something,
3460          so we attach them to this BFD, provided it is the right
3461          format and is not from ld --just-symbols.  FIXME: If there
3462          are no input BFD's of the same format as the output, we can't
3463          make a shared library.  */
3464       if (!just_syms
3465           && info->shared
3466           && is_elf_hash_table (htab)
3467           && info->output_bfd->xvec == abfd->xvec
3468           && !htab->dynamic_sections_created)
3469         {
3470           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3471             goto error_return;
3472         }
3473     }
3474   else if (!is_elf_hash_table (htab))
3475     goto error_return;
3476   else
3477     {
3478       const char *soname = NULL;
3479       char *audit = NULL;
3480       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3481       int ret;
3482
3483       /* ld --just-symbols and dynamic objects don't mix very well.
3484          ld shouldn't allow it.  */
3485       if (just_syms)
3486         abort ();
3487
3488       /* If this dynamic lib was specified on the command line with
3489          --as-needed in effect, then we don't want to add a DT_NEEDED
3490          tag unless the lib is actually used.  Similary for libs brought
3491          in by another lib's DT_NEEDED.  When --no-add-needed is used
3492          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3493          any dynamic library in DT_NEEDED tags in the dynamic lib at
3494          all.  */
3495       add_needed = (elf_dyn_lib_class (abfd)
3496                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3497                        | DYN_NO_NEEDED)) == 0;
3498
3499       s = bfd_get_section_by_name (abfd, ".dynamic");
3500       if (s != NULL)
3501         {
3502           bfd_byte *dynbuf;
3503           bfd_byte *extdyn;
3504           unsigned int elfsec;
3505           unsigned long shlink;
3506
3507           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3508             {
3509 error_free_dyn:
3510               free (dynbuf);
3511               goto error_return;
3512             }
3513
3514           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3515           if (elfsec == SHN_BAD)
3516             goto error_free_dyn;
3517           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3518
3519           for (extdyn = dynbuf;
3520                extdyn < dynbuf + s->size;
3521                extdyn += bed->s->sizeof_dyn)
3522             {
3523               Elf_Internal_Dyn dyn;
3524
3525               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3526               if (dyn.d_tag == DT_SONAME)
3527                 {
3528                   unsigned int tagv = dyn.d_un.d_val;
3529                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3530                   if (soname == NULL)
3531                     goto error_free_dyn;
3532                 }
3533               if (dyn.d_tag == DT_NEEDED)
3534                 {
3535                   struct bfd_link_needed_list *n, **pn;
3536                   char *fnm, *anm;
3537                   unsigned int tagv = dyn.d_un.d_val;
3538
3539                   amt = sizeof (struct bfd_link_needed_list);
3540                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3541                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3542                   if (n == NULL || fnm == NULL)
3543                     goto error_free_dyn;
3544                   amt = strlen (fnm) + 1;
3545                   anm = (char *) bfd_alloc (abfd, amt);
3546                   if (anm == NULL)
3547                     goto error_free_dyn;
3548                   memcpy (anm, fnm, amt);
3549                   n->name = anm;
3550                   n->by = abfd;
3551                   n->next = NULL;
3552                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3553                     ;
3554                   *pn = n;
3555                 }
3556               if (dyn.d_tag == DT_RUNPATH)
3557                 {
3558                   struct bfd_link_needed_list *n, **pn;
3559                   char *fnm, *anm;
3560                   unsigned int tagv = dyn.d_un.d_val;
3561
3562                   amt = sizeof (struct bfd_link_needed_list);
3563                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3564                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3565                   if (n == NULL || fnm == NULL)
3566                     goto error_free_dyn;
3567                   amt = strlen (fnm) + 1;
3568                   anm = (char *) bfd_alloc (abfd, amt);
3569                   if (anm == NULL)
3570                     goto error_free_dyn;
3571                   memcpy (anm, fnm, amt);
3572                   n->name = anm;
3573                   n->by = abfd;
3574                   n->next = NULL;
3575                   for (pn = & runpath;
3576                        *pn != NULL;
3577                        pn = &(*pn)->next)
3578                     ;
3579                   *pn = n;
3580                 }
3581               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3582               if (!runpath && dyn.d_tag == DT_RPATH)
3583                 {
3584                   struct bfd_link_needed_list *n, **pn;
3585                   char *fnm, *anm;
3586                   unsigned int tagv = dyn.d_un.d_val;
3587
3588                   amt = sizeof (struct bfd_link_needed_list);
3589                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3590                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3591                   if (n == NULL || fnm == NULL)
3592                     goto error_free_dyn;
3593                   amt = strlen (fnm) + 1;
3594                   anm = (char *) bfd_alloc (abfd, amt);
3595                   if (anm == NULL)
3596                     goto error_free_dyn;
3597                   memcpy (anm, fnm, amt);
3598                   n->name = anm;
3599                   n->by = abfd;
3600                   n->next = NULL;
3601                   for (pn = & rpath;
3602                        *pn != NULL;
3603                        pn = &(*pn)->next)
3604                     ;
3605                   *pn = n;
3606                 }
3607               if (dyn.d_tag == DT_AUDIT)
3608                 {
3609                   unsigned int tagv = dyn.d_un.d_val;
3610                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3611                 }
3612             }
3613
3614           free (dynbuf);
3615         }
3616
3617       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3618          frees all more recently bfd_alloc'd blocks as well.  */
3619       if (runpath)
3620         rpath = runpath;
3621
3622       if (rpath)
3623         {
3624           struct bfd_link_needed_list **pn;
3625           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3626             ;
3627           *pn = rpath;
3628         }
3629
3630       /* We do not want to include any of the sections in a dynamic
3631          object in the output file.  We hack by simply clobbering the
3632          list of sections in the BFD.  This could be handled more
3633          cleanly by, say, a new section flag; the existing
3634          SEC_NEVER_LOAD flag is not the one we want, because that one
3635          still implies that the section takes up space in the output
3636          file.  */
3637       bfd_section_list_clear (abfd);
3638
3639       /* Find the name to use in a DT_NEEDED entry that refers to this
3640          object.  If the object has a DT_SONAME entry, we use it.
3641          Otherwise, if the generic linker stuck something in
3642          elf_dt_name, we use that.  Otherwise, we just use the file
3643          name.  */
3644       if (soname == NULL || *soname == '\0')
3645         {
3646           soname = elf_dt_name (abfd);
3647           if (soname == NULL || *soname == '\0')
3648             soname = bfd_get_filename (abfd);
3649         }
3650
3651       /* Save the SONAME because sometimes the linker emulation code
3652          will need to know it.  */
3653       elf_dt_name (abfd) = soname;
3654
3655       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3656       if (ret < 0)
3657         goto error_return;
3658
3659       /* If we have already included this dynamic object in the
3660          link, just ignore it.  There is no reason to include a
3661          particular dynamic object more than once.  */
3662       if (ret > 0)
3663         return TRUE;
3664
3665       /* Save the DT_AUDIT entry for the linker emulation code. */
3666       elf_dt_audit (abfd) = audit;
3667     }
3668
3669   /* If this is a dynamic object, we always link against the .dynsym
3670      symbol table, not the .symtab symbol table.  The dynamic linker
3671      will only see the .dynsym symbol table, so there is no reason to
3672      look at .symtab for a dynamic object.  */
3673
3674   if (! dynamic || elf_dynsymtab (abfd) == 0)
3675     hdr = &elf_tdata (abfd)->symtab_hdr;
3676   else
3677     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3678
3679   symcount = hdr->sh_size / bed->s->sizeof_sym;
3680
3681   /* The sh_info field of the symtab header tells us where the
3682      external symbols start.  We don't care about the local symbols at
3683      this point.  */
3684   if (elf_bad_symtab (abfd))
3685     {
3686       extsymcount = symcount;
3687       extsymoff = 0;
3688     }
3689   else
3690     {
3691       extsymcount = symcount - hdr->sh_info;
3692       extsymoff = hdr->sh_info;
3693     }
3694
3695   sym_hash = elf_sym_hashes (abfd);
3696   if (extsymcount != 0)
3697     {
3698       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3699                                       NULL, NULL, NULL);
3700       if (isymbuf == NULL)
3701         goto error_return;
3702
3703       if (sym_hash == NULL)
3704         {
3705           /* We store a pointer to the hash table entry for each
3706              external symbol.  */
3707           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3708           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3709           if (sym_hash == NULL)
3710             goto error_free_sym;
3711           elf_sym_hashes (abfd) = sym_hash;
3712         }
3713     }
3714
3715   if (dynamic)
3716     {
3717       /* Read in any version definitions.  */
3718       if (!_bfd_elf_slurp_version_tables (abfd,
3719                                           info->default_imported_symver))
3720         goto error_free_sym;
3721
3722       /* Read in the symbol versions, but don't bother to convert them
3723          to internal format.  */
3724       if (elf_dynversym (abfd) != 0)
3725         {
3726           Elf_Internal_Shdr *versymhdr;
3727
3728           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3729           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3730           if (extversym == NULL)
3731             goto error_free_sym;
3732           amt = versymhdr->sh_size;
3733           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3734               || bfd_bread (extversym, amt, abfd) != amt)
3735             goto error_free_vers;
3736         }
3737     }
3738
3739   /* If we are loading an as-needed shared lib, save the symbol table
3740      state before we start adding symbols.  If the lib turns out
3741      to be unneeded, restore the state.  */
3742   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3743     {
3744       unsigned int i;
3745       size_t entsize;
3746
3747       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3748         {
3749           struct bfd_hash_entry *p;
3750           struct elf_link_hash_entry *h;
3751
3752           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3753             {
3754               h = (struct elf_link_hash_entry *) p;
3755               entsize += htab->root.table.entsize;
3756               if (h->root.type == bfd_link_hash_warning)
3757                 entsize += htab->root.table.entsize;
3758             }
3759         }
3760
3761       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3762       old_tab = bfd_malloc (tabsize + entsize);
3763       if (old_tab == NULL)
3764         goto error_free_vers;
3765
3766       /* Remember the current objalloc pointer, so that all mem for
3767          symbols added can later be reclaimed.  */
3768       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3769       if (alloc_mark == NULL)
3770         goto error_free_vers;
3771
3772       /* Make a special call to the linker "notice" function to
3773          tell it that we are about to handle an as-needed lib.  */
3774       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
3775         goto error_free_vers;
3776
3777       /* Clone the symbol table.  Remember some pointers into the
3778          symbol table, and dynamic symbol count.  */
3779       old_ent = (char *) old_tab + tabsize;
3780       memcpy (old_tab, htab->root.table.table, tabsize);
3781       old_undefs = htab->root.undefs;
3782       old_undefs_tail = htab->root.undefs_tail;
3783       old_table = htab->root.table.table;
3784       old_size = htab->root.table.size;
3785       old_count = htab->root.table.count;
3786       old_dynsymcount = htab->dynsymcount;
3787       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
3788
3789       for (i = 0; i < htab->root.table.size; i++)
3790         {
3791           struct bfd_hash_entry *p;
3792           struct elf_link_hash_entry *h;
3793
3794           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3795             {
3796               memcpy (old_ent, p, htab->root.table.entsize);
3797               old_ent = (char *) old_ent + htab->root.table.entsize;
3798               h = (struct elf_link_hash_entry *) p;
3799               if (h->root.type == bfd_link_hash_warning)
3800                 {
3801                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3802                   old_ent = (char *) old_ent + htab->root.table.entsize;
3803                 }
3804             }
3805         }
3806     }
3807
3808   weaks = NULL;
3809   ever = extversym != NULL ? extversym + extsymoff : NULL;
3810   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3811        isym < isymend;
3812        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3813     {
3814       int bind;
3815       bfd_vma value;
3816       asection *sec, *new_sec;
3817       flagword flags;
3818       const char *name;
3819       struct elf_link_hash_entry *h;
3820       struct elf_link_hash_entry *hi;
3821       bfd_boolean definition;
3822       bfd_boolean size_change_ok;
3823       bfd_boolean type_change_ok;
3824       bfd_boolean new_weakdef;
3825       bfd_boolean new_weak;
3826       bfd_boolean old_weak;
3827       bfd_boolean override;
3828       bfd_boolean common;
3829       unsigned int old_alignment;
3830       bfd *old_bfd;
3831
3832       override = FALSE;
3833
3834       flags = BSF_NO_FLAGS;
3835       sec = NULL;
3836       value = isym->st_value;
3837       common = bed->common_definition (isym);
3838
3839       bind = ELF_ST_BIND (isym->st_info);
3840       switch (bind)
3841         {
3842         case STB_LOCAL:
3843           /* This should be impossible, since ELF requires that all
3844              global symbols follow all local symbols, and that sh_info
3845              point to the first global symbol.  Unfortunately, Irix 5
3846              screws this up.  */
3847           continue;
3848
3849         case STB_GLOBAL:
3850           if (isym->st_shndx != SHN_UNDEF && !common)
3851             flags = BSF_GLOBAL;
3852           break;
3853
3854         case STB_WEAK:
3855           flags = BSF_WEAK;
3856           break;
3857
3858         case STB_GNU_UNIQUE:
3859           flags = BSF_GNU_UNIQUE;
3860           break;
3861
3862         default:
3863           /* Leave it up to the processor backend.  */
3864           break;
3865         }
3866
3867       if (isym->st_shndx == SHN_UNDEF)
3868         sec = bfd_und_section_ptr;
3869       else if (isym->st_shndx == SHN_ABS)
3870         sec = bfd_abs_section_ptr;
3871       else if (isym->st_shndx == SHN_COMMON)
3872         {
3873           sec = bfd_com_section_ptr;
3874           /* What ELF calls the size we call the value.  What ELF
3875              calls the value we call the alignment.  */
3876           value = isym->st_size;
3877         }
3878       else
3879         {
3880           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3881           if (sec == NULL)
3882             sec = bfd_abs_section_ptr;
3883           else if (discarded_section (sec))
3884             {
3885               /* Symbols from discarded section are undefined.  We keep
3886                  its visibility.  */
3887               sec = bfd_und_section_ptr;
3888               isym->st_shndx = SHN_UNDEF;
3889             }
3890           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3891             value -= sec->vma;
3892         }
3893
3894       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3895                                               isym->st_name);
3896       if (name == NULL)
3897         goto error_free_vers;
3898
3899       if (isym->st_shndx == SHN_COMMON
3900           && (abfd->flags & BFD_PLUGIN) != 0)
3901         {
3902           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
3903
3904           if (xc == NULL)
3905             {
3906               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
3907                                  | SEC_EXCLUDE);
3908               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
3909               if (xc == NULL)
3910                 goto error_free_vers;
3911             }
3912           sec = xc;
3913         }
3914       else if (isym->st_shndx == SHN_COMMON
3915                && ELF_ST_TYPE (isym->st_info) == STT_TLS
3916                && !info->relocatable)
3917         {
3918           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
3919
3920           if (tcomm == NULL)
3921             {
3922               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
3923                                  | SEC_LINKER_CREATED);
3924               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
3925               if (tcomm == NULL)
3926                 goto error_free_vers;
3927             }
3928           sec = tcomm;
3929         }
3930       else if (bed->elf_add_symbol_hook)
3931         {
3932           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
3933                                              &sec, &value))
3934             goto error_free_vers;
3935
3936           /* The hook function sets the name to NULL if this symbol
3937              should be skipped for some reason.  */
3938           if (name == NULL)
3939             continue;
3940         }
3941
3942       /* Sanity check that all possibilities were handled.  */
3943       if (sec == NULL)
3944         {
3945           bfd_set_error (bfd_error_bad_value);
3946           goto error_free_vers;
3947         }
3948
3949       /* Silently discard TLS symbols from --just-syms.  There's
3950          no way to combine a static TLS block with a new TLS block
3951          for this executable.  */
3952       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
3953           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
3954         continue;
3955
3956       if (bfd_is_und_section (sec)
3957           || bfd_is_com_section (sec))
3958         definition = FALSE;
3959       else
3960         definition = TRUE;
3961
3962       size_change_ok = FALSE;
3963       type_change_ok = bed->type_change_ok;
3964       old_weak = FALSE;
3965       old_alignment = 0;
3966       old_bfd = NULL;
3967       new_sec = sec;
3968
3969       if (is_elf_hash_table (htab))
3970         {
3971           Elf_Internal_Versym iver;
3972           unsigned int vernum = 0;
3973           bfd_boolean skip;
3974
3975           if (ever == NULL)
3976             {
3977               if (info->default_imported_symver)
3978                 /* Use the default symbol version created earlier.  */
3979                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
3980               else
3981                 iver.vs_vers = 0;
3982             }
3983           else
3984             _bfd_elf_swap_versym_in (abfd, ever, &iver);
3985
3986           vernum = iver.vs_vers & VERSYM_VERSION;
3987
3988           /* If this is a hidden symbol, or if it is not version
3989              1, we append the version name to the symbol name.
3990              However, we do not modify a non-hidden absolute symbol
3991              if it is not a function, because it might be the version
3992              symbol itself.  FIXME: What if it isn't?  */
3993           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
3994               || (vernum > 1
3995                   && (!bfd_is_abs_section (sec)
3996                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
3997             {
3998               const char *verstr;
3999               size_t namelen, verlen, newlen;
4000               char *newname, *p;
4001
4002               if (isym->st_shndx != SHN_UNDEF)
4003                 {
4004                   if (vernum > elf_tdata (abfd)->cverdefs)
4005                     verstr = NULL;
4006                   else if (vernum > 1)
4007                     verstr =
4008                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4009                   else
4010                     verstr = "";
4011
4012                   if (verstr == NULL)
4013                     {
4014                       (*_bfd_error_handler)
4015                         (_("%B: %s: invalid version %u (max %d)"),
4016                          abfd, name, vernum,
4017                          elf_tdata (abfd)->cverdefs);
4018                       bfd_set_error (bfd_error_bad_value);
4019                       goto error_free_vers;
4020                     }
4021                 }
4022               else
4023                 {
4024                   /* We cannot simply test for the number of
4025                      entries in the VERNEED section since the
4026                      numbers for the needed versions do not start
4027                      at 0.  */
4028                   Elf_Internal_Verneed *t;
4029
4030                   verstr = NULL;
4031                   for (t = elf_tdata (abfd)->verref;
4032                        t != NULL;
4033                        t = t->vn_nextref)
4034                     {
4035                       Elf_Internal_Vernaux *a;
4036
4037                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4038                         {
4039                           if (a->vna_other == vernum)
4040                             {
4041                               verstr = a->vna_nodename;
4042                               break;
4043                             }
4044                         }
4045                       if (a != NULL)
4046                         break;
4047                     }
4048                   if (verstr == NULL)
4049                     {
4050                       (*_bfd_error_handler)
4051                         (_("%B: %s: invalid needed version %d"),
4052                          abfd, name, vernum);
4053                       bfd_set_error (bfd_error_bad_value);
4054                       goto error_free_vers;
4055                     }
4056                 }
4057
4058               namelen = strlen (name);
4059               verlen = strlen (verstr);
4060               newlen = namelen + verlen + 2;
4061               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4062                   && isym->st_shndx != SHN_UNDEF)
4063                 ++newlen;
4064
4065               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4066               if (newname == NULL)
4067                 goto error_free_vers;
4068               memcpy (newname, name, namelen);
4069               p = newname + namelen;
4070               *p++ = ELF_VER_CHR;
4071               /* If this is a defined non-hidden version symbol,
4072                  we add another @ to the name.  This indicates the
4073                  default version of the symbol.  */
4074               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4075                   && isym->st_shndx != SHN_UNDEF)
4076                 *p++ = ELF_VER_CHR;
4077               memcpy (p, verstr, verlen + 1);
4078
4079               name = newname;
4080             }
4081
4082           /* If this symbol has default visibility and the user has
4083              requested we not re-export it, then mark it as hidden.  */
4084           if (definition
4085               && !dynamic
4086               && (abfd->no_export
4087                   || (abfd->my_archive && abfd->my_archive->no_export))
4088               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4089             isym->st_other = (STV_HIDDEN
4090                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4091
4092           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4093                                       sym_hash, &old_bfd, &old_weak,
4094                                       &old_alignment, &skip, &override,
4095                                       &type_change_ok, &size_change_ok))
4096             goto error_free_vers;
4097
4098           if (skip)
4099             continue;
4100
4101           if (override)
4102             definition = FALSE;
4103
4104           h = *sym_hash;
4105           while (h->root.type == bfd_link_hash_indirect
4106                  || h->root.type == bfd_link_hash_warning)
4107             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4108
4109           if (elf_tdata (abfd)->verdef != NULL
4110               && vernum > 1
4111               && definition)
4112             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4113         }
4114
4115       if (! (_bfd_generic_link_add_one_symbol
4116              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4117               (struct bfd_link_hash_entry **) sym_hash)))
4118         goto error_free_vers;
4119
4120       h = *sym_hash;
4121       /* We need to make sure that indirect symbol dynamic flags are
4122          updated.  */
4123       hi = h;
4124       while (h->root.type == bfd_link_hash_indirect
4125              || h->root.type == bfd_link_hash_warning)
4126         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4127
4128       *sym_hash = h;
4129
4130       new_weak = (flags & BSF_WEAK) != 0;
4131       new_weakdef = FALSE;
4132       if (dynamic
4133           && definition
4134           && new_weak
4135           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4136           && is_elf_hash_table (htab)
4137           && h->u.weakdef == NULL)
4138         {
4139           /* Keep a list of all weak defined non function symbols from
4140              a dynamic object, using the weakdef field.  Later in this
4141              function we will set the weakdef field to the correct
4142              value.  We only put non-function symbols from dynamic
4143              objects on this list, because that happens to be the only
4144              time we need to know the normal symbol corresponding to a
4145              weak symbol, and the information is time consuming to
4146              figure out.  If the weakdef field is not already NULL,
4147              then this symbol was already defined by some previous
4148              dynamic object, and we will be using that previous
4149              definition anyhow.  */
4150
4151           h->u.weakdef = weaks;
4152           weaks = h;
4153           new_weakdef = TRUE;
4154         }
4155
4156       /* Set the alignment of a common symbol.  */
4157       if ((common || bfd_is_com_section (sec))
4158           && h->root.type == bfd_link_hash_common)
4159         {
4160           unsigned int align;
4161
4162           if (common)
4163             align = bfd_log2 (isym->st_value);
4164           else
4165             {
4166               /* The new symbol is a common symbol in a shared object.
4167                  We need to get the alignment from the section.  */
4168               align = new_sec->alignment_power;
4169             }
4170           if (align > old_alignment)
4171             h->root.u.c.p->alignment_power = align;
4172           else
4173             h->root.u.c.p->alignment_power = old_alignment;
4174         }
4175
4176       if (is_elf_hash_table (htab))
4177         {
4178           /* Set a flag in the hash table entry indicating the type of
4179              reference or definition we just found.  A dynamic symbol
4180              is one which is referenced or defined by both a regular
4181              object and a shared object.  */
4182           bfd_boolean dynsym = FALSE;
4183
4184           /* Plugin symbols aren't normal.  Don't set def_regular or
4185              ref_regular for them, or make them dynamic.  */
4186           if ((abfd->flags & BFD_PLUGIN) != 0)
4187             ;
4188           else if (! dynamic)
4189             {
4190               if (! definition)
4191                 {
4192                   h->ref_regular = 1;
4193                   if (bind != STB_WEAK)
4194                     h->ref_regular_nonweak = 1;
4195                 }
4196               else
4197                 {
4198                   h->def_regular = 1;
4199                   if (h->def_dynamic)
4200                     {
4201                       h->def_dynamic = 0;
4202                       h->ref_dynamic = 1;
4203                     }
4204                 }
4205
4206               /* If the indirect symbol has been forced local, don't
4207                  make the real symbol dynamic.  */
4208               if ((h == hi || !hi->forced_local)
4209                   && (! info->executable
4210                       || h->def_dynamic
4211                       || h->ref_dynamic))
4212                 dynsym = TRUE;
4213             }
4214           else
4215             {
4216               if (! definition)
4217                 {
4218                   h->ref_dynamic = 1;
4219                   hi->ref_dynamic = 1;
4220                 }
4221               else
4222                 {
4223                   h->def_dynamic = 1;
4224                   hi->def_dynamic = 1;
4225                 }
4226
4227               /* If the indirect symbol has been forced local, don't
4228                  make the real symbol dynamic.  */
4229               if ((h == hi || !hi->forced_local)
4230                   && (h->def_regular
4231                       || h->ref_regular
4232                       || (h->u.weakdef != NULL
4233                           && ! new_weakdef
4234                           && h->u.weakdef->dynindx != -1)))
4235                 dynsym = TRUE;
4236             }
4237
4238           /* Check to see if we need to add an indirect symbol for
4239              the default name.  */
4240           if (definition
4241               || (!override && h->root.type == bfd_link_hash_common))
4242             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4243                                               sec, value, &old_bfd, &dynsym))
4244               goto error_free_vers;
4245
4246           /* Check the alignment when a common symbol is involved. This
4247              can change when a common symbol is overridden by a normal
4248              definition or a common symbol is ignored due to the old
4249              normal definition. We need to make sure the maximum
4250              alignment is maintained.  */
4251           if ((old_alignment || common)
4252               && h->root.type != bfd_link_hash_common)
4253             {
4254               unsigned int common_align;
4255               unsigned int normal_align;
4256               unsigned int symbol_align;
4257               bfd *normal_bfd;
4258               bfd *common_bfd;
4259
4260               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4261                           || h->root.type == bfd_link_hash_defweak);
4262
4263               symbol_align = ffs (h->root.u.def.value) - 1;
4264               if (h->root.u.def.section->owner != NULL
4265                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4266                 {
4267                   normal_align = h->root.u.def.section->alignment_power;
4268                   if (normal_align > symbol_align)
4269                     normal_align = symbol_align;
4270                 }
4271               else
4272                 normal_align = symbol_align;
4273
4274               if (old_alignment)
4275                 {
4276                   common_align = old_alignment;
4277                   common_bfd = old_bfd;
4278                   normal_bfd = abfd;
4279                 }
4280               else
4281                 {
4282                   common_align = bfd_log2 (isym->st_value);
4283                   common_bfd = abfd;
4284                   normal_bfd = old_bfd;
4285                 }
4286
4287               if (normal_align < common_align)
4288                 {
4289                   /* PR binutils/2735 */
4290                   if (normal_bfd == NULL)
4291                     (*_bfd_error_handler)
4292                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4293                          " greater than the alignment (%u) of its section %A"),
4294                        common_bfd, h->root.u.def.section,
4295                        1 << common_align, name, 1 << normal_align);
4296                   else
4297                     (*_bfd_error_handler)
4298                       (_("Warning: alignment %u of symbol `%s' in %B"
4299                          " is smaller than %u in %B"),
4300                        normal_bfd, common_bfd,
4301                        1 << normal_align, name, 1 << common_align);
4302                 }
4303             }
4304
4305           /* Remember the symbol size if it isn't undefined.  */
4306           if (isym->st_size != 0
4307               && isym->st_shndx != SHN_UNDEF
4308               && (definition || h->size == 0))
4309             {
4310               if (h->size != 0
4311                   && h->size != isym->st_size
4312                   && ! size_change_ok)
4313                 (*_bfd_error_handler)
4314                   (_("Warning: size of symbol `%s' changed"
4315                      " from %lu in %B to %lu in %B"),
4316                    old_bfd, abfd,
4317                    name, (unsigned long) h->size,
4318                    (unsigned long) isym->st_size);
4319
4320               h->size = isym->st_size;
4321             }
4322
4323           /* If this is a common symbol, then we always want H->SIZE
4324              to be the size of the common symbol.  The code just above
4325              won't fix the size if a common symbol becomes larger.  We
4326              don't warn about a size change here, because that is
4327              covered by --warn-common.  Allow changes between different
4328              function types.  */
4329           if (h->root.type == bfd_link_hash_common)
4330             h->size = h->root.u.c.size;
4331
4332           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4333               && ((definition && !new_weak)
4334                   || (old_weak && h->root.type == bfd_link_hash_common)
4335                   || h->type == STT_NOTYPE))
4336             {
4337               unsigned int type = ELF_ST_TYPE (isym->st_info);
4338
4339               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4340                  symbol.  */
4341               if (type == STT_GNU_IFUNC
4342                   && (abfd->flags & DYNAMIC) != 0)
4343                 type = STT_FUNC;
4344
4345               if (h->type != type)
4346                 {
4347                   if (h->type != STT_NOTYPE && ! type_change_ok)
4348                     (*_bfd_error_handler)
4349                       (_("Warning: type of symbol `%s' changed"
4350                          " from %d to %d in %B"),
4351                        abfd, name, h->type, type);
4352
4353                   h->type = type;
4354                 }
4355             }
4356
4357           /* Merge st_other field.  */
4358           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4359
4360           /* We don't want to make debug symbol dynamic.  */
4361           if (definition && (sec->flags & SEC_DEBUGGING) && !info->relocatable)
4362             dynsym = FALSE;
4363
4364           /* Nor should we make plugin symbols dynamic.  */
4365           if ((abfd->flags & BFD_PLUGIN) != 0)
4366             dynsym = FALSE;
4367
4368           if (definition)
4369             {
4370               h->target_internal = isym->st_target_internal;
4371               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4372             }
4373
4374           if (definition && !dynamic)
4375             {
4376               char *p = strchr (name, ELF_VER_CHR);
4377               if (p != NULL && p[1] != ELF_VER_CHR)
4378                 {
4379                   /* Queue non-default versions so that .symver x, x@FOO
4380                      aliases can be checked.  */
4381                   if (!nondeflt_vers)
4382                     {
4383                       amt = ((isymend - isym + 1)
4384                              * sizeof (struct elf_link_hash_entry *));
4385                       nondeflt_vers =
4386                           (struct elf_link_hash_entry **) bfd_malloc (amt);
4387                       if (!nondeflt_vers)
4388                         goto error_free_vers;
4389                     }
4390                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4391                 }
4392             }
4393
4394           if (dynsym && h->dynindx == -1)
4395             {
4396               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4397                 goto error_free_vers;
4398               if (h->u.weakdef != NULL
4399                   && ! new_weakdef
4400                   && h->u.weakdef->dynindx == -1)
4401                 {
4402                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4403                     goto error_free_vers;
4404                 }
4405             }
4406           else if (dynsym && h->dynindx != -1)
4407             /* If the symbol already has a dynamic index, but
4408                visibility says it should not be visible, turn it into
4409                a local symbol.  */
4410             switch (ELF_ST_VISIBILITY (h->other))
4411               {
4412               case STV_INTERNAL:
4413               case STV_HIDDEN:
4414                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4415                 dynsym = FALSE;
4416                 break;
4417               }
4418
4419           /* Don't add DT_NEEDED for references from the dummy bfd.  */
4420           if (!add_needed
4421               && definition
4422               && ((dynsym
4423                    && h->ref_regular_nonweak
4424                    && (old_bfd == NULL
4425                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4426                   || (h->ref_dynamic_nonweak
4427                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4428                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4429             {
4430               int ret;
4431               const char *soname = elf_dt_name (abfd);
4432
4433               info->callbacks->minfo ("%!", soname, old_bfd,
4434                                       h->root.root.string);
4435
4436               /* A symbol from a library loaded via DT_NEEDED of some
4437                  other library is referenced by a regular object.
4438                  Add a DT_NEEDED entry for it.  Issue an error if
4439                  --no-add-needed is used and the reference was not
4440                  a weak one.  */
4441               if (old_bfd != NULL
4442                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4443                 {
4444                   (*_bfd_error_handler)
4445                     (_("%B: undefined reference to symbol '%s'"),
4446                      old_bfd, name);
4447                   bfd_set_error (bfd_error_missing_dso);
4448                   goto error_free_vers;
4449                 }
4450
4451               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4452                   (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4453
4454               add_needed = TRUE;
4455               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4456               if (ret < 0)
4457                 goto error_free_vers;
4458
4459               BFD_ASSERT (ret == 0);
4460             }
4461         }
4462     }
4463
4464   if (extversym != NULL)
4465     {
4466       free (extversym);
4467       extversym = NULL;
4468     }
4469
4470   if (isymbuf != NULL)
4471     {
4472       free (isymbuf);
4473       isymbuf = NULL;
4474     }
4475
4476   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4477     {
4478       unsigned int i;
4479
4480       /* Restore the symbol table.  */
4481       old_ent = (char *) old_tab + tabsize;
4482       memset (elf_sym_hashes (abfd), 0,
4483               extsymcount * sizeof (struct elf_link_hash_entry *));
4484       htab->root.table.table = old_table;
4485       htab->root.table.size = old_size;
4486       htab->root.table.count = old_count;
4487       memcpy (htab->root.table.table, old_tab, tabsize);
4488       htab->root.undefs = old_undefs;
4489       htab->root.undefs_tail = old_undefs_tail;
4490       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4491       for (i = 0; i < htab->root.table.size; i++)
4492         {
4493           struct bfd_hash_entry *p;
4494           struct elf_link_hash_entry *h;
4495           bfd_size_type size;
4496           unsigned int alignment_power;
4497
4498           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4499             {
4500               h = (struct elf_link_hash_entry *) p;
4501               if (h->root.type == bfd_link_hash_warning)
4502                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4503               if (h->dynindx >= old_dynsymcount
4504                   && h->dynstr_index < old_dynstr_size)
4505                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4506
4507               /* Preserve the maximum alignment and size for common
4508                  symbols even if this dynamic lib isn't on DT_NEEDED
4509                  since it can still be loaded at run time by another
4510                  dynamic lib.  */
4511               if (h->root.type == bfd_link_hash_common)
4512                 {
4513                   size = h->root.u.c.size;
4514                   alignment_power = h->root.u.c.p->alignment_power;
4515                 }
4516               else
4517                 {
4518                   size = 0;
4519                   alignment_power = 0;
4520                 }
4521               memcpy (p, old_ent, htab->root.table.entsize);
4522               old_ent = (char *) old_ent + htab->root.table.entsize;
4523               h = (struct elf_link_hash_entry *) p;
4524               if (h->root.type == bfd_link_hash_warning)
4525                 {
4526                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4527                   old_ent = (char *) old_ent + htab->root.table.entsize;
4528                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4529                 }
4530               if (h->root.type == bfd_link_hash_common)
4531                 {
4532                   if (size > h->root.u.c.size)
4533                     h->root.u.c.size = size;
4534                   if (alignment_power > h->root.u.c.p->alignment_power)
4535                     h->root.u.c.p->alignment_power = alignment_power;
4536                 }
4537             }
4538         }
4539
4540       /* Make a special call to the linker "notice" function to
4541          tell it that symbols added for crefs may need to be removed.  */
4542       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4543         goto error_free_vers;
4544
4545       free (old_tab);
4546       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4547                            alloc_mark);
4548       if (nondeflt_vers != NULL)
4549         free (nondeflt_vers);
4550       return TRUE;
4551     }
4552
4553   if (old_tab != NULL)
4554     {
4555       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4556         goto error_free_vers;
4557       free (old_tab);
4558       old_tab = NULL;
4559     }
4560
4561   /* Now that all the symbols from this input file are created, handle
4562      .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4563   if (nondeflt_vers != NULL)
4564     {
4565       bfd_size_type cnt, symidx;
4566
4567       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4568         {
4569           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4570           char *shortname, *p;
4571
4572           p = strchr (h->root.root.string, ELF_VER_CHR);
4573           if (p == NULL
4574               || (h->root.type != bfd_link_hash_defined
4575                   && h->root.type != bfd_link_hash_defweak))
4576             continue;
4577
4578           amt = p - h->root.root.string;
4579           shortname = (char *) bfd_malloc (amt + 1);
4580           if (!shortname)
4581             goto error_free_vers;
4582           memcpy (shortname, h->root.root.string, amt);
4583           shortname[amt] = '\0';
4584
4585           hi = (struct elf_link_hash_entry *)
4586                bfd_link_hash_lookup (&htab->root, shortname,
4587                                      FALSE, FALSE, FALSE);
4588           if (hi != NULL
4589               && hi->root.type == h->root.type
4590               && hi->root.u.def.value == h->root.u.def.value
4591               && hi->root.u.def.section == h->root.u.def.section)
4592             {
4593               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4594               hi->root.type = bfd_link_hash_indirect;
4595               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4596               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4597               sym_hash = elf_sym_hashes (abfd);
4598               if (sym_hash)
4599                 for (symidx = 0; symidx < extsymcount; ++symidx)
4600                   if (sym_hash[symidx] == hi)
4601                     {
4602                       sym_hash[symidx] = h;
4603                       break;
4604                     }
4605             }
4606           free (shortname);
4607         }
4608       free (nondeflt_vers);
4609       nondeflt_vers = NULL;
4610     }
4611
4612   /* Now set the weakdefs field correctly for all the weak defined
4613      symbols we found.  The only way to do this is to search all the
4614      symbols.  Since we only need the information for non functions in
4615      dynamic objects, that's the only time we actually put anything on
4616      the list WEAKS.  We need this information so that if a regular
4617      object refers to a symbol defined weakly in a dynamic object, the
4618      real symbol in the dynamic object is also put in the dynamic
4619      symbols; we also must arrange for both symbols to point to the
4620      same memory location.  We could handle the general case of symbol
4621      aliasing, but a general symbol alias can only be generated in
4622      assembler code, handling it correctly would be very time
4623      consuming, and other ELF linkers don't handle general aliasing
4624      either.  */
4625   if (weaks != NULL)
4626     {
4627       struct elf_link_hash_entry **hpp;
4628       struct elf_link_hash_entry **hppend;
4629       struct elf_link_hash_entry **sorted_sym_hash;
4630       struct elf_link_hash_entry *h;
4631       size_t sym_count;
4632
4633       /* Since we have to search the whole symbol list for each weak
4634          defined symbol, search time for N weak defined symbols will be
4635          O(N^2). Binary search will cut it down to O(NlogN).  */
4636       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4637       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4638       if (sorted_sym_hash == NULL)
4639         goto error_return;
4640       sym_hash = sorted_sym_hash;
4641       hpp = elf_sym_hashes (abfd);
4642       hppend = hpp + extsymcount;
4643       sym_count = 0;
4644       for (; hpp < hppend; hpp++)
4645         {
4646           h = *hpp;
4647           if (h != NULL
4648               && h->root.type == bfd_link_hash_defined
4649               && !bed->is_function_type (h->type))
4650             {
4651               *sym_hash = h;
4652               sym_hash++;
4653               sym_count++;
4654             }
4655         }
4656
4657       qsort (sorted_sym_hash, sym_count,
4658              sizeof (struct elf_link_hash_entry *),
4659              elf_sort_symbol);
4660
4661       while (weaks != NULL)
4662         {
4663           struct elf_link_hash_entry *hlook;
4664           asection *slook;
4665           bfd_vma vlook;
4666           size_t i, j, idx = 0;
4667
4668           hlook = weaks;
4669           weaks = hlook->u.weakdef;
4670           hlook->u.weakdef = NULL;
4671
4672           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4673                       || hlook->root.type == bfd_link_hash_defweak
4674                       || hlook->root.type == bfd_link_hash_common
4675                       || hlook->root.type == bfd_link_hash_indirect);
4676           slook = hlook->root.u.def.section;
4677           vlook = hlook->root.u.def.value;
4678
4679           i = 0;
4680           j = sym_count;
4681           while (i != j)
4682             {
4683               bfd_signed_vma vdiff;
4684               idx = (i + j) / 2;
4685               h = sorted_sym_hash[idx];
4686               vdiff = vlook - h->root.u.def.value;
4687               if (vdiff < 0)
4688                 j = idx;
4689               else if (vdiff > 0)
4690                 i = idx + 1;
4691               else
4692                 {
4693                   long sdiff = slook->id - h->root.u.def.section->id;
4694                   if (sdiff < 0)
4695                     j = idx;
4696                   else if (sdiff > 0)
4697                     i = idx + 1;
4698                   else
4699                     break;
4700                 }
4701             }
4702
4703           /* We didn't find a value/section match.  */
4704           if (i == j)
4705             continue;
4706
4707           /* With multiple aliases, or when the weak symbol is already
4708              strongly defined, we have multiple matching symbols and
4709              the binary search above may land on any of them.  Step
4710              one past the matching symbol(s).  */
4711           while (++idx != j)
4712             {
4713               h = sorted_sym_hash[idx];
4714               if (h->root.u.def.section != slook
4715                   || h->root.u.def.value != vlook)
4716                 break;
4717             }
4718
4719           /* Now look back over the aliases.  Since we sorted by size
4720              as well as value and section, we'll choose the one with
4721              the largest size.  */
4722           while (idx-- != i)
4723             {
4724               h = sorted_sym_hash[idx];
4725
4726               /* Stop if value or section doesn't match.  */
4727               if (h->root.u.def.section != slook
4728                   || h->root.u.def.value != vlook)
4729                 break;
4730               else if (h != hlook)
4731                 {
4732                   hlook->u.weakdef = h;
4733
4734                   /* If the weak definition is in the list of dynamic
4735                      symbols, make sure the real definition is put
4736                      there as well.  */
4737                   if (hlook->dynindx != -1 && h->dynindx == -1)
4738                     {
4739                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4740                         {
4741                         err_free_sym_hash:
4742                           free (sorted_sym_hash);
4743                           goto error_return;
4744                         }
4745                     }
4746
4747                   /* If the real definition is in the list of dynamic
4748                      symbols, make sure the weak definition is put
4749                      there as well.  If we don't do this, then the
4750                      dynamic loader might not merge the entries for the
4751                      real definition and the weak definition.  */
4752                   if (h->dynindx != -1 && hlook->dynindx == -1)
4753                     {
4754                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4755                         goto err_free_sym_hash;
4756                     }
4757                   break;
4758                 }
4759             }
4760         }
4761
4762       free (sorted_sym_hash);
4763     }
4764
4765   if (bed->check_directives
4766       && !(*bed->check_directives) (abfd, info))
4767     return FALSE;
4768
4769   /* If this object is the same format as the output object, and it is
4770      not a shared library, then let the backend look through the
4771      relocs.
4772
4773      This is required to build global offset table entries and to
4774      arrange for dynamic relocs.  It is not required for the
4775      particular common case of linking non PIC code, even when linking
4776      against shared libraries, but unfortunately there is no way of
4777      knowing whether an object file has been compiled PIC or not.
4778      Looking through the relocs is not particularly time consuming.
4779      The problem is that we must either (1) keep the relocs in memory,
4780      which causes the linker to require additional runtime memory or
4781      (2) read the relocs twice from the input file, which wastes time.
4782      This would be a good case for using mmap.
4783
4784      I have no idea how to handle linking PIC code into a file of a
4785      different format.  It probably can't be done.  */
4786   if (! dynamic
4787       && is_elf_hash_table (htab)
4788       && bed->check_relocs != NULL
4789       && elf_object_id (abfd) == elf_hash_table_id (htab)
4790       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4791     {
4792       asection *o;
4793
4794       for (o = abfd->sections; o != NULL; o = o->next)
4795         {
4796           Elf_Internal_Rela *internal_relocs;
4797           bfd_boolean ok;
4798
4799           if ((o->flags & SEC_RELOC) == 0
4800               || o->reloc_count == 0
4801               || ((info->strip == strip_all || info->strip == strip_debugger)
4802                   && (o->flags & SEC_DEBUGGING) != 0)
4803               || bfd_is_abs_section (o->output_section))
4804             continue;
4805
4806           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4807                                                        info->keep_memory);
4808           if (internal_relocs == NULL)
4809             goto error_return;
4810
4811           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4812
4813           if (elf_section_data (o)->relocs != internal_relocs)
4814             free (internal_relocs);
4815
4816           if (! ok)
4817             goto error_return;
4818         }
4819     }
4820
4821   /* If this is a non-traditional link, try to optimize the handling
4822      of the .stab/.stabstr sections.  */
4823   if (! dynamic
4824       && ! info->traditional_format
4825       && is_elf_hash_table (htab)
4826       && (info->strip != strip_all && info->strip != strip_debugger))
4827     {
4828       asection *stabstr;
4829
4830       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4831       if (stabstr != NULL)
4832         {
4833           bfd_size_type string_offset = 0;
4834           asection *stab;
4835
4836           for (stab = abfd->sections; stab; stab = stab->next)
4837             if (CONST_STRNEQ (stab->name, ".stab")
4838                 && (!stab->name[5] ||
4839                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4840                 && (stab->flags & SEC_MERGE) == 0
4841                 && !bfd_is_abs_section (stab->output_section))
4842               {
4843                 struct bfd_elf_section_data *secdata;
4844
4845                 secdata = elf_section_data (stab);
4846                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4847                                                stabstr, &secdata->sec_info,
4848                                                &string_offset))
4849                   goto error_return;
4850                 if (secdata->sec_info)
4851                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
4852             }
4853         }
4854     }
4855
4856   if (is_elf_hash_table (htab) && add_needed)
4857     {
4858       /* Add this bfd to the loaded list.  */
4859       struct elf_link_loaded_list *n;
4860
4861       n = (struct elf_link_loaded_list *)
4862           bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4863       if (n == NULL)
4864         goto error_return;
4865       n->abfd = abfd;
4866       n->next = htab->loaded;
4867       htab->loaded = n;
4868     }
4869
4870   return TRUE;
4871
4872  error_free_vers:
4873   if (old_tab != NULL)
4874     free (old_tab);
4875   if (nondeflt_vers != NULL)
4876     free (nondeflt_vers);
4877   if (extversym != NULL)
4878     free (extversym);
4879  error_free_sym:
4880   if (isymbuf != NULL)
4881     free (isymbuf);
4882  error_return:
4883   return FALSE;
4884 }
4885
4886 /* Return the linker hash table entry of a symbol that might be
4887    satisfied by an archive symbol.  Return -1 on error.  */
4888
4889 struct elf_link_hash_entry *
4890 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4891                                 struct bfd_link_info *info,
4892                                 const char *name)
4893 {
4894   struct elf_link_hash_entry *h;
4895   char *p, *copy;
4896   size_t len, first;
4897
4898   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
4899   if (h != NULL)
4900     return h;
4901
4902   /* If this is a default version (the name contains @@), look up the
4903      symbol again with only one `@' as well as without the version.
4904      The effect is that references to the symbol with and without the
4905      version will be matched by the default symbol in the archive.  */
4906
4907   p = strchr (name, ELF_VER_CHR);
4908   if (p == NULL || p[1] != ELF_VER_CHR)
4909     return h;
4910
4911   /* First check with only one `@'.  */
4912   len = strlen (name);
4913   copy = (char *) bfd_alloc (abfd, len);
4914   if (copy == NULL)
4915     return (struct elf_link_hash_entry *) 0 - 1;
4916
4917   first = p - name + 1;
4918   memcpy (copy, name, first);
4919   memcpy (copy + first, name + first + 1, len - first);
4920
4921   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
4922   if (h == NULL)
4923     {
4924       /* We also need to check references to the symbol without the
4925          version.  */
4926       copy[first - 1] = '\0';
4927       h = elf_link_hash_lookup (elf_hash_table (info), copy,
4928                                 FALSE, FALSE, TRUE);
4929     }
4930
4931   bfd_release (abfd, copy);
4932   return h;
4933 }
4934
4935 /* Add symbols from an ELF archive file to the linker hash table.  We
4936    don't use _bfd_generic_link_add_archive_symbols because we need to
4937    handle versioned symbols.
4938
4939    Fortunately, ELF archive handling is simpler than that done by
4940    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4941    oddities.  In ELF, if we find a symbol in the archive map, and the
4942    symbol is currently undefined, we know that we must pull in that
4943    object file.
4944
4945    Unfortunately, we do have to make multiple passes over the symbol
4946    table until nothing further is resolved.  */
4947
4948 static bfd_boolean
4949 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4950 {
4951   symindex c;
4952   unsigned char *included = NULL;
4953   carsym *symdefs;
4954   bfd_boolean loop;
4955   bfd_size_type amt;
4956   const struct elf_backend_data *bed;
4957   struct elf_link_hash_entry * (*archive_symbol_lookup)
4958     (bfd *, struct bfd_link_info *, const char *);
4959
4960   if (! bfd_has_map (abfd))
4961     {
4962       /* An empty archive is a special case.  */
4963       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4964         return TRUE;
4965       bfd_set_error (bfd_error_no_armap);
4966       return FALSE;
4967     }
4968
4969   /* Keep track of all symbols we know to be already defined, and all
4970      files we know to be already included.  This is to speed up the
4971      second and subsequent passes.  */
4972   c = bfd_ardata (abfd)->symdef_count;
4973   if (c == 0)
4974     return TRUE;
4975   amt = c;
4976   amt *= sizeof (*included);
4977   included = (unsigned char *) bfd_zmalloc (amt);
4978   if (included == NULL)
4979     return FALSE;
4980
4981   symdefs = bfd_ardata (abfd)->symdefs;
4982   bed = get_elf_backend_data (abfd);
4983   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
4984
4985   do
4986     {
4987       file_ptr last;
4988       symindex i;
4989       carsym *symdef;
4990       carsym *symdefend;
4991
4992       loop = FALSE;
4993       last = -1;
4994
4995       symdef = symdefs;
4996       symdefend = symdef + c;
4997       for (i = 0; symdef < symdefend; symdef++, i++)
4998         {
4999           struct elf_link_hash_entry *h;
5000           bfd *element;
5001           struct bfd_link_hash_entry *undefs_tail;
5002           symindex mark;
5003
5004           if (included[i])
5005             continue;
5006           if (symdef->file_offset == last)
5007             {
5008               included[i] = TRUE;
5009               continue;
5010             }
5011
5012           h = archive_symbol_lookup (abfd, info, symdef->name);
5013           if (h == (struct elf_link_hash_entry *) 0 - 1)
5014             goto error_return;
5015
5016           if (h == NULL)
5017             continue;
5018
5019           if (h->root.type == bfd_link_hash_common)
5020             {
5021               /* We currently have a common symbol.  The archive map contains
5022                  a reference to this symbol, so we may want to include it.  We
5023                  only want to include it however, if this archive element
5024                  contains a definition of the symbol, not just another common
5025                  declaration of it.
5026
5027                  Unfortunately some archivers (including GNU ar) will put
5028                  declarations of common symbols into their archive maps, as
5029                  well as real definitions, so we cannot just go by the archive
5030                  map alone.  Instead we must read in the element's symbol
5031                  table and check that to see what kind of symbol definition
5032                  this is.  */
5033               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5034                 continue;
5035             }
5036           else if (h->root.type != bfd_link_hash_undefined)
5037             {
5038               if (h->root.type != bfd_link_hash_undefweak)
5039                 /* Symbol must be defined.  Don't check it again.  */
5040                 included[i] = TRUE;
5041               continue;
5042             }
5043
5044           /* We need to include this archive member.  */
5045           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5046           if (element == NULL)
5047             goto error_return;
5048
5049           if (! bfd_check_format (element, bfd_object))
5050             goto error_return;
5051
5052           undefs_tail = info->hash->undefs_tail;
5053
5054           if (!(*info->callbacks
5055                 ->add_archive_element) (info, element, symdef->name, &element))
5056             goto error_return;
5057           if (!bfd_link_add_symbols (element, info))
5058             goto error_return;
5059
5060           /* If there are any new undefined symbols, we need to make
5061              another pass through the archive in order to see whether
5062              they can be defined.  FIXME: This isn't perfect, because
5063              common symbols wind up on undefs_tail and because an
5064              undefined symbol which is defined later on in this pass
5065              does not require another pass.  This isn't a bug, but it
5066              does make the code less efficient than it could be.  */
5067           if (undefs_tail != info->hash->undefs_tail)
5068             loop = TRUE;
5069
5070           /* Look backward to mark all symbols from this object file
5071              which we have already seen in this pass.  */
5072           mark = i;
5073           do
5074             {
5075               included[mark] = TRUE;
5076               if (mark == 0)
5077                 break;
5078               --mark;
5079             }
5080           while (symdefs[mark].file_offset == symdef->file_offset);
5081
5082           /* We mark subsequent symbols from this object file as we go
5083              on through the loop.  */
5084           last = symdef->file_offset;
5085         }
5086     }
5087   while (loop);
5088
5089   free (included);
5090
5091   return TRUE;
5092
5093  error_return:
5094   if (included != NULL)
5095     free (included);
5096   return FALSE;
5097 }
5098
5099 /* Given an ELF BFD, add symbols to the global hash table as
5100    appropriate.  */
5101
5102 bfd_boolean
5103 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5104 {
5105   switch (bfd_get_format (abfd))
5106     {
5107     case bfd_object:
5108       return elf_link_add_object_symbols (abfd, info);
5109     case bfd_archive:
5110       return elf_link_add_archive_symbols (abfd, info);
5111     default:
5112       bfd_set_error (bfd_error_wrong_format);
5113       return FALSE;
5114     }
5115 }
5116 \f
5117 struct hash_codes_info
5118 {
5119   unsigned long *hashcodes;
5120   bfd_boolean error;
5121 };
5122
5123 /* This function will be called though elf_link_hash_traverse to store
5124    all hash value of the exported symbols in an array.  */
5125
5126 static bfd_boolean
5127 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5128 {
5129   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5130   const char *name;
5131   char *p;
5132   unsigned long ha;
5133   char *alc = NULL;
5134
5135   /* Ignore indirect symbols.  These are added by the versioning code.  */
5136   if (h->dynindx == -1)
5137     return TRUE;
5138
5139   name = h->root.root.string;
5140   p = strchr (name, ELF_VER_CHR);
5141   if (p != NULL)
5142     {
5143       alc = (char *) bfd_malloc (p - name + 1);
5144       if (alc == NULL)
5145         {
5146           inf->error = TRUE;
5147           return FALSE;
5148         }
5149       memcpy (alc, name, p - name);
5150       alc[p - name] = '\0';
5151       name = alc;
5152     }
5153
5154   /* Compute the hash value.  */
5155   ha = bfd_elf_hash (name);
5156
5157   /* Store the found hash value in the array given as the argument.  */
5158   *(inf->hashcodes)++ = ha;
5159
5160   /* And store it in the struct so that we can put it in the hash table
5161      later.  */
5162   h->u.elf_hash_value = ha;
5163
5164   if (alc != NULL)
5165     free (alc);
5166
5167   return TRUE;
5168 }
5169
5170 struct collect_gnu_hash_codes
5171 {
5172   bfd *output_bfd;
5173   const struct elf_backend_data *bed;
5174   unsigned long int nsyms;
5175   unsigned long int maskbits;
5176   unsigned long int *hashcodes;
5177   unsigned long int *hashval;
5178   unsigned long int *indx;
5179   unsigned long int *counts;
5180   bfd_vma *bitmask;
5181   bfd_byte *contents;
5182   long int min_dynindx;
5183   unsigned long int bucketcount;
5184   unsigned long int symindx;
5185   long int local_indx;
5186   long int shift1, shift2;
5187   unsigned long int mask;
5188   bfd_boolean error;
5189 };
5190
5191 /* This function will be called though elf_link_hash_traverse to store
5192    all hash value of the exported symbols in an array.  */
5193
5194 static bfd_boolean
5195 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5196 {
5197   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5198   const char *name;
5199   char *p;
5200   unsigned long ha;
5201   char *alc = NULL;
5202
5203   /* Ignore indirect symbols.  These are added by the versioning code.  */
5204   if (h->dynindx == -1)
5205     return TRUE;
5206
5207   /* Ignore also local symbols and undefined symbols.  */
5208   if (! (*s->bed->elf_hash_symbol) (h))
5209     return TRUE;
5210
5211   name = h->root.root.string;
5212   p = strchr (name, ELF_VER_CHR);
5213   if (p != NULL)
5214     {
5215       alc = (char *) bfd_malloc (p - name + 1);
5216       if (alc == NULL)
5217         {
5218           s->error = TRUE;
5219           return FALSE;
5220         }
5221       memcpy (alc, name, p - name);
5222       alc[p - name] = '\0';
5223       name = alc;
5224     }
5225
5226   /* Compute the hash value.  */
5227   ha = bfd_elf_gnu_hash (name);
5228
5229   /* Store the found hash value in the array for compute_bucket_count,
5230      and also for .dynsym reordering purposes.  */
5231   s->hashcodes[s->nsyms] = ha;
5232   s->hashval[h->dynindx] = ha;
5233   ++s->nsyms;
5234   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5235     s->min_dynindx = h->dynindx;
5236
5237   if (alc != NULL)
5238     free (alc);
5239
5240   return TRUE;
5241 }
5242
5243 /* This function will be called though elf_link_hash_traverse to do
5244    final dynaminc symbol renumbering.  */
5245
5246 static bfd_boolean
5247 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5248 {
5249   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5250   unsigned long int bucket;
5251   unsigned long int val;
5252
5253   /* Ignore indirect symbols.  */
5254   if (h->dynindx == -1)
5255     return TRUE;
5256
5257   /* Ignore also local symbols and undefined symbols.  */
5258   if (! (*s->bed->elf_hash_symbol) (h))
5259     {
5260       if (h->dynindx >= s->min_dynindx)
5261         h->dynindx = s->local_indx++;
5262       return TRUE;
5263     }
5264
5265   bucket = s->hashval[h->dynindx] % s->bucketcount;
5266   val = (s->hashval[h->dynindx] >> s->shift1)
5267         & ((s->maskbits >> s->shift1) - 1);
5268   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5269   s->bitmask[val]
5270     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5271   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5272   if (s->counts[bucket] == 1)
5273     /* Last element terminates the chain.  */
5274     val |= 1;
5275   bfd_put_32 (s->output_bfd, val,
5276               s->contents + (s->indx[bucket] - s->symindx) * 4);
5277   --s->counts[bucket];
5278   h->dynindx = s->indx[bucket]++;
5279   return TRUE;
5280 }
5281
5282 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5283
5284 bfd_boolean
5285 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5286 {
5287   return !(h->forced_local
5288            || h->root.type == bfd_link_hash_undefined
5289            || h->root.type == bfd_link_hash_undefweak
5290            || ((h->root.type == bfd_link_hash_defined
5291                 || h->root.type == bfd_link_hash_defweak)
5292                && h->root.u.def.section->output_section == NULL));
5293 }
5294
5295 /* Array used to determine the number of hash table buckets to use
5296    based on the number of symbols there are.  If there are fewer than
5297    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5298    fewer than 37 we use 17 buckets, and so forth.  We never use more
5299    than 32771 buckets.  */
5300
5301 static const size_t elf_buckets[] =
5302 {
5303   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5304   16411, 32771, 0
5305 };
5306
5307 /* Compute bucket count for hashing table.  We do not use a static set
5308    of possible tables sizes anymore.  Instead we determine for all
5309    possible reasonable sizes of the table the outcome (i.e., the
5310    number of collisions etc) and choose the best solution.  The
5311    weighting functions are not too simple to allow the table to grow
5312    without bounds.  Instead one of the weighting factors is the size.
5313    Therefore the result is always a good payoff between few collisions
5314    (= short chain lengths) and table size.  */
5315 static size_t
5316 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5317                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5318                       unsigned long int nsyms,
5319                       int gnu_hash)
5320 {
5321   size_t best_size = 0;
5322   unsigned long int i;
5323
5324   /* We have a problem here.  The following code to optimize the table
5325      size requires an integer type with more the 32 bits.  If
5326      BFD_HOST_U_64_BIT is set we know about such a type.  */
5327 #ifdef BFD_HOST_U_64_BIT
5328   if (info->optimize)
5329     {
5330       size_t minsize;
5331       size_t maxsize;
5332       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5333       bfd *dynobj = elf_hash_table (info)->dynobj;
5334       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5335       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5336       unsigned long int *counts;
5337       bfd_size_type amt;
5338       unsigned int no_improvement_count = 0;
5339
5340       /* Possible optimization parameters: if we have NSYMS symbols we say
5341          that the hashing table must at least have NSYMS/4 and at most
5342          2*NSYMS buckets.  */
5343       minsize = nsyms / 4;
5344       if (minsize == 0)
5345         minsize = 1;
5346       best_size = maxsize = nsyms * 2;
5347       if (gnu_hash)
5348         {
5349           if (minsize < 2)
5350             minsize = 2;
5351           if ((best_size & 31) == 0)
5352             ++best_size;
5353         }
5354
5355       /* Create array where we count the collisions in.  We must use bfd_malloc
5356          since the size could be large.  */
5357       amt = maxsize;
5358       amt *= sizeof (unsigned long int);
5359       counts = (unsigned long int *) bfd_malloc (amt);
5360       if (counts == NULL)
5361         return 0;
5362
5363       /* Compute the "optimal" size for the hash table.  The criteria is a
5364          minimal chain length.  The minor criteria is (of course) the size
5365          of the table.  */
5366       for (i = minsize; i < maxsize; ++i)
5367         {
5368           /* Walk through the array of hashcodes and count the collisions.  */
5369           BFD_HOST_U_64_BIT max;
5370           unsigned long int j;
5371           unsigned long int fact;
5372
5373           if (gnu_hash && (i & 31) == 0)
5374             continue;
5375
5376           memset (counts, '\0', i * sizeof (unsigned long int));
5377
5378           /* Determine how often each hash bucket is used.  */
5379           for (j = 0; j < nsyms; ++j)
5380             ++counts[hashcodes[j] % i];
5381
5382           /* For the weight function we need some information about the
5383              pagesize on the target.  This is information need not be 100%
5384              accurate.  Since this information is not available (so far) we
5385              define it here to a reasonable default value.  If it is crucial
5386              to have a better value some day simply define this value.  */
5387 # ifndef BFD_TARGET_PAGESIZE
5388 #  define BFD_TARGET_PAGESIZE   (4096)
5389 # endif
5390
5391           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5392              and the chains.  */
5393           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5394
5395 # if 1
5396           /* Variant 1: optimize for short chains.  We add the squares
5397              of all the chain lengths (which favors many small chain
5398              over a few long chains).  */
5399           for (j = 0; j < i; ++j)
5400             max += counts[j] * counts[j];
5401
5402           /* This adds penalties for the overall size of the table.  */
5403           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5404           max *= fact * fact;
5405 # else
5406           /* Variant 2: Optimize a lot more for small table.  Here we
5407              also add squares of the size but we also add penalties for
5408              empty slots (the +1 term).  */
5409           for (j = 0; j < i; ++j)
5410             max += (1 + counts[j]) * (1 + counts[j]);
5411
5412           /* The overall size of the table is considered, but not as
5413              strong as in variant 1, where it is squared.  */
5414           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5415           max *= fact;
5416 # endif
5417
5418           /* Compare with current best results.  */
5419           if (max < best_chlen)
5420             {
5421               best_chlen = max;
5422               best_size = i;
5423               no_improvement_count = 0;
5424             }
5425           /* PR 11843: Avoid futile long searches for the best bucket size
5426              when there are a large number of symbols.  */
5427           else if (++no_improvement_count == 100)
5428             break;
5429         }
5430
5431       free (counts);
5432     }
5433   else
5434 #endif /* defined (BFD_HOST_U_64_BIT) */
5435     {
5436       /* This is the fallback solution if no 64bit type is available or if we
5437          are not supposed to spend much time on optimizations.  We select the
5438          bucket count using a fixed set of numbers.  */
5439       for (i = 0; elf_buckets[i] != 0; i++)
5440         {
5441           best_size = elf_buckets[i];
5442           if (nsyms < elf_buckets[i + 1])
5443             break;
5444         }
5445       if (gnu_hash && best_size < 2)
5446         best_size = 2;
5447     }
5448
5449   return best_size;
5450 }
5451
5452 /* Size any SHT_GROUP section for ld -r.  */
5453
5454 bfd_boolean
5455 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5456 {
5457   bfd *ibfd;
5458
5459   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5460     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5461         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5462       return FALSE;
5463   return TRUE;
5464 }
5465
5466 /* Set a default stack segment size.  The value in INFO wins.  If it
5467    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5468    undefined it is initialized.  */
5469
5470 bfd_boolean
5471 bfd_elf_stack_segment_size (bfd *output_bfd,
5472                             struct bfd_link_info *info,
5473                             const char *legacy_symbol,
5474                             bfd_vma default_size)
5475 {
5476   struct elf_link_hash_entry *h = NULL;
5477
5478   /* Look for legacy symbol.  */
5479   if (legacy_symbol)
5480     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5481                               FALSE, FALSE, FALSE);
5482   if (h && (h->root.type == bfd_link_hash_defined
5483             || h->root.type == bfd_link_hash_defweak)
5484       && h->def_regular
5485       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5486     {
5487       /* The symbol has no type if specified on the command line.  */
5488       h->type = STT_OBJECT;
5489       if (info->stacksize)
5490         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5491                                output_bfd, legacy_symbol);
5492       else if (h->root.u.def.section != bfd_abs_section_ptr)
5493         (*_bfd_error_handler) (_("%B: %s not absolute"),
5494                                output_bfd, legacy_symbol);
5495       else
5496         info->stacksize = h->root.u.def.value;
5497     }
5498
5499   if (!info->stacksize)
5500     /* If the user didn't set a size, or explicitly inhibit the
5501        size, set it now.  */
5502     info->stacksize = default_size;
5503
5504   /* Provide the legacy symbol, if it is referenced.  */
5505   if (h && (h->root.type == bfd_link_hash_undefined
5506             || h->root.type == bfd_link_hash_undefweak))
5507     {
5508       struct bfd_link_hash_entry *bh = NULL;
5509
5510       if (!(_bfd_generic_link_add_one_symbol
5511             (info, output_bfd, legacy_symbol,
5512              BSF_GLOBAL, bfd_abs_section_ptr,
5513              info->stacksize >= 0 ? info->stacksize : 0,
5514              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5515         return FALSE;
5516
5517       h = (struct elf_link_hash_entry *) bh;
5518       h->def_regular = 1;
5519       h->type = STT_OBJECT;
5520     }
5521
5522   return TRUE;
5523 }
5524
5525 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5526    called by the ELF linker emulation before_allocation routine.  We
5527    must set the sizes of the sections before the linker sets the
5528    addresses of the various sections.  */
5529
5530 bfd_boolean
5531 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5532                                const char *soname,
5533                                const char *rpath,
5534                                const char *filter_shlib,
5535                                const char *audit,
5536                                const char *depaudit,
5537                                const char * const *auxiliary_filters,
5538                                struct bfd_link_info *info,
5539                                asection **sinterpptr)
5540 {
5541   bfd_size_type soname_indx;
5542   bfd *dynobj;
5543   const struct elf_backend_data *bed;
5544   struct elf_info_failed asvinfo;
5545
5546   *sinterpptr = NULL;
5547
5548   soname_indx = (bfd_size_type) -1;
5549
5550   if (!is_elf_hash_table (info->hash))
5551     return TRUE;
5552
5553   bed = get_elf_backend_data (output_bfd);
5554
5555   /* Any syms created from now on start with -1 in
5556      got.refcount/offset and plt.refcount/offset.  */
5557   elf_hash_table (info)->init_got_refcount
5558     = elf_hash_table (info)->init_got_offset;
5559   elf_hash_table (info)->init_plt_refcount
5560     = elf_hash_table (info)->init_plt_offset;
5561
5562   if (info->relocatable
5563       && !_bfd_elf_size_group_sections (info))
5564     return FALSE;
5565
5566   /* The backend may have to create some sections regardless of whether
5567      we're dynamic or not.  */
5568   if (bed->elf_backend_always_size_sections
5569       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5570     return FALSE;
5571
5572   /* Determine any GNU_STACK segment requirements, after the backend
5573      has had a chance to set a default segment size.  */
5574   if (info->execstack)
5575     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5576   else if (info->noexecstack)
5577     elf_stack_flags (output_bfd) = PF_R | PF_W;
5578   else
5579     {
5580       bfd *inputobj;
5581       asection *notesec = NULL;
5582       int exec = 0;
5583
5584       for (inputobj = info->input_bfds;
5585            inputobj;
5586            inputobj = inputobj->link.next)
5587         {
5588           asection *s;
5589
5590           if (inputobj->flags
5591               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5592             continue;
5593           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5594           if (s)
5595             {
5596               if (s->flags & SEC_CODE)
5597                 exec = PF_X;
5598               notesec = s;
5599             }
5600           else if (bed->default_execstack)
5601             exec = PF_X;
5602         }
5603       if (notesec || info->stacksize > 0)
5604         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5605       if (notesec && exec && info->relocatable
5606           && notesec->output_section != bfd_abs_section_ptr)
5607         notesec->output_section->flags |= SEC_CODE;
5608     }
5609
5610   dynobj = elf_hash_table (info)->dynobj;
5611
5612   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5613     {
5614       struct elf_info_failed eif;
5615       struct elf_link_hash_entry *h;
5616       asection *dynstr;
5617       struct bfd_elf_version_tree *t;
5618       struct bfd_elf_version_expr *d;
5619       asection *s;
5620       bfd_boolean all_defined;
5621
5622       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5623       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5624
5625       if (soname != NULL)
5626         {
5627           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5628                                              soname, TRUE);
5629           if (soname_indx == (bfd_size_type) -1
5630               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5631             return FALSE;
5632         }
5633
5634       if (info->symbolic)
5635         {
5636           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5637             return FALSE;
5638           info->flags |= DF_SYMBOLIC;
5639         }
5640
5641       if (rpath != NULL)
5642         {
5643           bfd_size_type indx;
5644           bfd_vma tag;
5645
5646           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5647                                       TRUE);
5648           if (indx == (bfd_size_type) -1)
5649             return FALSE;
5650
5651           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5652           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5653             return FALSE;
5654         }
5655
5656       if (filter_shlib != NULL)
5657         {
5658           bfd_size_type indx;
5659
5660           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5661                                       filter_shlib, TRUE);
5662           if (indx == (bfd_size_type) -1
5663               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5664             return FALSE;
5665         }
5666
5667       if (auxiliary_filters != NULL)
5668         {
5669           const char * const *p;
5670
5671           for (p = auxiliary_filters; *p != NULL; p++)
5672             {
5673               bfd_size_type indx;
5674
5675               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5676                                           *p, TRUE);
5677               if (indx == (bfd_size_type) -1
5678                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5679                 return FALSE;
5680             }
5681         }
5682
5683       if (audit != NULL)
5684         {
5685           bfd_size_type indx;
5686
5687           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5688                                       TRUE);
5689           if (indx == (bfd_size_type) -1
5690               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5691             return FALSE;
5692         }
5693
5694       if (depaudit != NULL)
5695         {
5696           bfd_size_type indx;
5697
5698           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5699                                       TRUE);
5700           if (indx == (bfd_size_type) -1
5701               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5702             return FALSE;
5703         }
5704
5705       eif.info = info;
5706       eif.failed = FALSE;
5707
5708       /* If we are supposed to export all symbols into the dynamic symbol
5709          table (this is not the normal case), then do so.  */
5710       if (info->export_dynamic
5711           || (info->executable && info->dynamic))
5712         {
5713           elf_link_hash_traverse (elf_hash_table (info),
5714                                   _bfd_elf_export_symbol,
5715                                   &eif);
5716           if (eif.failed)
5717             return FALSE;
5718         }
5719
5720       /* Make all global versions with definition.  */
5721       for (t = info->version_info; t != NULL; t = t->next)
5722         for (d = t->globals.list; d != NULL; d = d->next)
5723           if (!d->symver && d->literal)
5724             {
5725               const char *verstr, *name;
5726               size_t namelen, verlen, newlen;
5727               char *newname, *p, leading_char;
5728               struct elf_link_hash_entry *newh;
5729
5730               leading_char = bfd_get_symbol_leading_char (output_bfd);
5731               name = d->pattern;
5732               namelen = strlen (name) + (leading_char != '\0');
5733               verstr = t->name;
5734               verlen = strlen (verstr);
5735               newlen = namelen + verlen + 3;
5736
5737               newname = (char *) bfd_malloc (newlen);
5738               if (newname == NULL)
5739                 return FALSE;
5740               newname[0] = leading_char;
5741               memcpy (newname + (leading_char != '\0'), name, namelen);
5742
5743               /* Check the hidden versioned definition.  */
5744               p = newname + namelen;
5745               *p++ = ELF_VER_CHR;
5746               memcpy (p, verstr, verlen + 1);
5747               newh = elf_link_hash_lookup (elf_hash_table (info),
5748                                            newname, FALSE, FALSE,
5749                                            FALSE);
5750               if (newh == NULL
5751                   || (newh->root.type != bfd_link_hash_defined
5752                       && newh->root.type != bfd_link_hash_defweak))
5753                 {
5754                   /* Check the default versioned definition.  */
5755                   *p++ = ELF_VER_CHR;
5756                   memcpy (p, verstr, verlen + 1);
5757                   newh = elf_link_hash_lookup (elf_hash_table (info),
5758                                                newname, FALSE, FALSE,
5759                                                FALSE);
5760                 }
5761               free (newname);
5762
5763               /* Mark this version if there is a definition and it is
5764                  not defined in a shared object.  */
5765               if (newh != NULL
5766                   && !newh->def_dynamic
5767                   && (newh->root.type == bfd_link_hash_defined
5768                       || newh->root.type == bfd_link_hash_defweak))
5769                 d->symver = 1;
5770             }
5771
5772       /* Attach all the symbols to their version information.  */
5773       asvinfo.info = info;
5774       asvinfo.failed = FALSE;
5775
5776       elf_link_hash_traverse (elf_hash_table (info),
5777                               _bfd_elf_link_assign_sym_version,
5778                               &asvinfo);
5779       if (asvinfo.failed)
5780         return FALSE;
5781
5782       if (!info->allow_undefined_version)
5783         {
5784           /* Check if all global versions have a definition.  */
5785           all_defined = TRUE;
5786           for (t = info->version_info; t != NULL; t = t->next)
5787             for (d = t->globals.list; d != NULL; d = d->next)
5788               if (d->literal && !d->symver && !d->script)
5789                 {
5790                   (*_bfd_error_handler)
5791                     (_("%s: undefined version: %s"),
5792                      d->pattern, t->name);
5793                   all_defined = FALSE;
5794                 }
5795
5796           if (!all_defined)
5797             {
5798               bfd_set_error (bfd_error_bad_value);
5799               return FALSE;
5800             }
5801         }
5802
5803       /* Find all symbols which were defined in a dynamic object and make
5804          the backend pick a reasonable value for them.  */
5805       elf_link_hash_traverse (elf_hash_table (info),
5806                               _bfd_elf_adjust_dynamic_symbol,
5807                               &eif);
5808       if (eif.failed)
5809         return FALSE;
5810
5811       /* Add some entries to the .dynamic section.  We fill in some of the
5812          values later, in bfd_elf_final_link, but we must add the entries
5813          now so that we know the final size of the .dynamic section.  */
5814
5815       /* If there are initialization and/or finalization functions to
5816          call then add the corresponding DT_INIT/DT_FINI entries.  */
5817       h = (info->init_function
5818            ? elf_link_hash_lookup (elf_hash_table (info),
5819                                    info->init_function, FALSE,
5820                                    FALSE, FALSE)
5821            : NULL);
5822       if (h != NULL
5823           && (h->ref_regular
5824               || h->def_regular))
5825         {
5826           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5827             return FALSE;
5828         }
5829       h = (info->fini_function
5830            ? elf_link_hash_lookup (elf_hash_table (info),
5831                                    info->fini_function, FALSE,
5832                                    FALSE, FALSE)
5833            : NULL);
5834       if (h != NULL
5835           && (h->ref_regular
5836               || h->def_regular))
5837         {
5838           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5839             return FALSE;
5840         }
5841
5842       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5843       if (s != NULL && s->linker_has_input)
5844         {
5845           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5846           if (! info->executable)
5847             {
5848               bfd *sub;
5849               asection *o;
5850
5851               for (sub = info->input_bfds; sub != NULL;
5852                    sub = sub->link.next)
5853                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5854                   for (o = sub->sections; o != NULL; o = o->next)
5855                     if (elf_section_data (o)->this_hdr.sh_type
5856                         == SHT_PREINIT_ARRAY)
5857                       {
5858                         (*_bfd_error_handler)
5859                           (_("%B: .preinit_array section is not allowed in DSO"),
5860                            sub);
5861                         break;
5862                       }
5863
5864               bfd_set_error (bfd_error_nonrepresentable_section);
5865               return FALSE;
5866             }
5867
5868           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5869               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5870             return FALSE;
5871         }
5872       s = bfd_get_section_by_name (output_bfd, ".init_array");
5873       if (s != NULL && s->linker_has_input)
5874         {
5875           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5876               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5877             return FALSE;
5878         }
5879       s = bfd_get_section_by_name (output_bfd, ".fini_array");
5880       if (s != NULL && s->linker_has_input)
5881         {
5882           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5883               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5884             return FALSE;
5885         }
5886
5887       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
5888       /* If .dynstr is excluded from the link, we don't want any of
5889          these tags.  Strictly, we should be checking each section
5890          individually;  This quick check covers for the case where
5891          someone does a /DISCARD/ : { *(*) }.  */
5892       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5893         {
5894           bfd_size_type strsize;
5895
5896           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5897           if ((info->emit_hash
5898                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5899               || (info->emit_gnu_hash
5900                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5901               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5902               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5903               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5904               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5905                                               bed->s->sizeof_sym))
5906             return FALSE;
5907         }
5908     }
5909
5910   /* The backend must work out the sizes of all the other dynamic
5911      sections.  */
5912   if (dynobj != NULL
5913       && bed->elf_backend_size_dynamic_sections != NULL
5914       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5915     return FALSE;
5916
5917   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5918     return FALSE;
5919
5920   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5921     {
5922       unsigned long section_sym_count;
5923       struct bfd_elf_version_tree *verdefs;
5924       asection *s;
5925
5926       /* Set up the version definition section.  */
5927       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
5928       BFD_ASSERT (s != NULL);
5929
5930       /* We may have created additional version definitions if we are
5931          just linking a regular application.  */
5932       verdefs = info->version_info;
5933
5934       /* Skip anonymous version tag.  */
5935       if (verdefs != NULL && verdefs->vernum == 0)
5936         verdefs = verdefs->next;
5937
5938       if (verdefs == NULL && !info->create_default_symver)
5939         s->flags |= SEC_EXCLUDE;
5940       else
5941         {
5942           unsigned int cdefs;
5943           bfd_size_type size;
5944           struct bfd_elf_version_tree *t;
5945           bfd_byte *p;
5946           Elf_Internal_Verdef def;
5947           Elf_Internal_Verdaux defaux;
5948           struct bfd_link_hash_entry *bh;
5949           struct elf_link_hash_entry *h;
5950           const char *name;
5951
5952           cdefs = 0;
5953           size = 0;
5954
5955           /* Make space for the base version.  */
5956           size += sizeof (Elf_External_Verdef);
5957           size += sizeof (Elf_External_Verdaux);
5958           ++cdefs;
5959
5960           /* Make space for the default version.  */
5961           if (info->create_default_symver)
5962             {
5963               size += sizeof (Elf_External_Verdef);
5964               ++cdefs;
5965             }
5966
5967           for (t = verdefs; t != NULL; t = t->next)
5968             {
5969               struct bfd_elf_version_deps *n;
5970
5971               /* Don't emit base version twice.  */
5972               if (t->vernum == 0)
5973                 continue;
5974
5975               size += sizeof (Elf_External_Verdef);
5976               size += sizeof (Elf_External_Verdaux);
5977               ++cdefs;
5978
5979               for (n = t->deps; n != NULL; n = n->next)
5980                 size += sizeof (Elf_External_Verdaux);
5981             }
5982
5983           s->size = size;
5984           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
5985           if (s->contents == NULL && s->size != 0)
5986             return FALSE;
5987
5988           /* Fill in the version definition section.  */
5989
5990           p = s->contents;
5991
5992           def.vd_version = VER_DEF_CURRENT;
5993           def.vd_flags = VER_FLG_BASE;
5994           def.vd_ndx = 1;
5995           def.vd_cnt = 1;
5996           if (info->create_default_symver)
5997             {
5998               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
5999               def.vd_next = sizeof (Elf_External_Verdef);
6000             }
6001           else
6002             {
6003               def.vd_aux = sizeof (Elf_External_Verdef);
6004               def.vd_next = (sizeof (Elf_External_Verdef)
6005                              + sizeof (Elf_External_Verdaux));
6006             }
6007
6008           if (soname_indx != (bfd_size_type) -1)
6009             {
6010               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6011                                       soname_indx);
6012               def.vd_hash = bfd_elf_hash (soname);
6013               defaux.vda_name = soname_indx;
6014               name = soname;
6015             }
6016           else
6017             {
6018               bfd_size_type indx;
6019
6020               name = lbasename (output_bfd->filename);
6021               def.vd_hash = bfd_elf_hash (name);
6022               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6023                                           name, FALSE);
6024               if (indx == (bfd_size_type) -1)
6025                 return FALSE;
6026               defaux.vda_name = indx;
6027             }
6028           defaux.vda_next = 0;
6029
6030           _bfd_elf_swap_verdef_out (output_bfd, &def,
6031                                     (Elf_External_Verdef *) p);
6032           p += sizeof (Elf_External_Verdef);
6033           if (info->create_default_symver)
6034             {
6035               /* Add a symbol representing this version.  */
6036               bh = NULL;
6037               if (! (_bfd_generic_link_add_one_symbol
6038                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6039                       0, NULL, FALSE,
6040                       get_elf_backend_data (dynobj)->collect, &bh)))
6041                 return FALSE;
6042               h = (struct elf_link_hash_entry *) bh;
6043               h->non_elf = 0;
6044               h->def_regular = 1;
6045               h->type = STT_OBJECT;
6046               h->verinfo.vertree = NULL;
6047
6048               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6049                 return FALSE;
6050
6051               /* Create a duplicate of the base version with the same
6052                  aux block, but different flags.  */
6053               def.vd_flags = 0;
6054               def.vd_ndx = 2;
6055               def.vd_aux = sizeof (Elf_External_Verdef);
6056               if (verdefs)
6057                 def.vd_next = (sizeof (Elf_External_Verdef)
6058                                + sizeof (Elf_External_Verdaux));
6059               else
6060                 def.vd_next = 0;
6061               _bfd_elf_swap_verdef_out (output_bfd, &def,
6062                                         (Elf_External_Verdef *) p);
6063               p += sizeof (Elf_External_Verdef);
6064             }
6065           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6066                                      (Elf_External_Verdaux *) p);
6067           p += sizeof (Elf_External_Verdaux);
6068
6069           for (t = verdefs; t != NULL; t = t->next)
6070             {
6071               unsigned int cdeps;
6072               struct bfd_elf_version_deps *n;
6073
6074               /* Don't emit the base version twice.  */
6075               if (t->vernum == 0)
6076                 continue;
6077
6078               cdeps = 0;
6079               for (n = t->deps; n != NULL; n = n->next)
6080                 ++cdeps;
6081
6082               /* Add a symbol representing this version.  */
6083               bh = NULL;
6084               if (! (_bfd_generic_link_add_one_symbol
6085                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6086                       0, NULL, FALSE,
6087                       get_elf_backend_data (dynobj)->collect, &bh)))
6088                 return FALSE;
6089               h = (struct elf_link_hash_entry *) bh;
6090               h->non_elf = 0;
6091               h->def_regular = 1;
6092               h->type = STT_OBJECT;
6093               h->verinfo.vertree = t;
6094
6095               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6096                 return FALSE;
6097
6098               def.vd_version = VER_DEF_CURRENT;
6099               def.vd_flags = 0;
6100               if (t->globals.list == NULL
6101                   && t->locals.list == NULL
6102                   && ! t->used)
6103                 def.vd_flags |= VER_FLG_WEAK;
6104               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6105               def.vd_cnt = cdeps + 1;
6106               def.vd_hash = bfd_elf_hash (t->name);
6107               def.vd_aux = sizeof (Elf_External_Verdef);
6108               def.vd_next = 0;
6109
6110               /* If a basever node is next, it *must* be the last node in
6111                  the chain, otherwise Verdef construction breaks.  */
6112               if (t->next != NULL && t->next->vernum == 0)
6113                 BFD_ASSERT (t->next->next == NULL);
6114
6115               if (t->next != NULL && t->next->vernum != 0)
6116                 def.vd_next = (sizeof (Elf_External_Verdef)
6117                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6118
6119               _bfd_elf_swap_verdef_out (output_bfd, &def,
6120                                         (Elf_External_Verdef *) p);
6121               p += sizeof (Elf_External_Verdef);
6122
6123               defaux.vda_name = h->dynstr_index;
6124               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6125                                       h->dynstr_index);
6126               defaux.vda_next = 0;
6127               if (t->deps != NULL)
6128                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6129               t->name_indx = defaux.vda_name;
6130
6131               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6132                                          (Elf_External_Verdaux *) p);
6133               p += sizeof (Elf_External_Verdaux);
6134
6135               for (n = t->deps; n != NULL; n = n->next)
6136                 {
6137                   if (n->version_needed == NULL)
6138                     {
6139                       /* This can happen if there was an error in the
6140                          version script.  */
6141                       defaux.vda_name = 0;
6142                     }
6143                   else
6144                     {
6145                       defaux.vda_name = n->version_needed->name_indx;
6146                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6147                                               defaux.vda_name);
6148                     }
6149                   if (n->next == NULL)
6150                     defaux.vda_next = 0;
6151                   else
6152                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6153
6154                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6155                                              (Elf_External_Verdaux *) p);
6156                   p += sizeof (Elf_External_Verdaux);
6157                 }
6158             }
6159
6160           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6161               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6162             return FALSE;
6163
6164           elf_tdata (output_bfd)->cverdefs = cdefs;
6165         }
6166
6167       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6168         {
6169           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6170             return FALSE;
6171         }
6172       else if (info->flags & DF_BIND_NOW)
6173         {
6174           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6175             return FALSE;
6176         }
6177
6178       if (info->flags_1)
6179         {
6180           if (info->executable)
6181             info->flags_1 &= ~ (DF_1_INITFIRST
6182                                 | DF_1_NODELETE
6183                                 | DF_1_NOOPEN);
6184           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6185             return FALSE;
6186         }
6187
6188       /* Work out the size of the version reference section.  */
6189
6190       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6191       BFD_ASSERT (s != NULL);
6192       {
6193         struct elf_find_verdep_info sinfo;
6194
6195         sinfo.info = info;
6196         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6197         if (sinfo.vers == 0)
6198           sinfo.vers = 1;
6199         sinfo.failed = FALSE;
6200
6201         elf_link_hash_traverse (elf_hash_table (info),
6202                                 _bfd_elf_link_find_version_dependencies,
6203                                 &sinfo);
6204         if (sinfo.failed)
6205           return FALSE;
6206
6207         if (elf_tdata (output_bfd)->verref == NULL)
6208           s->flags |= SEC_EXCLUDE;
6209         else
6210           {
6211             Elf_Internal_Verneed *t;
6212             unsigned int size;
6213             unsigned int crefs;
6214             bfd_byte *p;
6215
6216             /* Build the version dependency section.  */
6217             size = 0;
6218             crefs = 0;
6219             for (t = elf_tdata (output_bfd)->verref;
6220                  t != NULL;
6221                  t = t->vn_nextref)
6222               {
6223                 Elf_Internal_Vernaux *a;
6224
6225                 size += sizeof (Elf_External_Verneed);
6226                 ++crefs;
6227                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6228                   size += sizeof (Elf_External_Vernaux);
6229               }
6230
6231             s->size = size;
6232             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6233             if (s->contents == NULL)
6234               return FALSE;
6235
6236             p = s->contents;
6237             for (t = elf_tdata (output_bfd)->verref;
6238                  t != NULL;
6239                  t = t->vn_nextref)
6240               {
6241                 unsigned int caux;
6242                 Elf_Internal_Vernaux *a;
6243                 bfd_size_type indx;
6244
6245                 caux = 0;
6246                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6247                   ++caux;
6248
6249                 t->vn_version = VER_NEED_CURRENT;
6250                 t->vn_cnt = caux;
6251                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6252                                             elf_dt_name (t->vn_bfd) != NULL
6253                                             ? elf_dt_name (t->vn_bfd)
6254                                             : lbasename (t->vn_bfd->filename),
6255                                             FALSE);
6256                 if (indx == (bfd_size_type) -1)
6257                   return FALSE;
6258                 t->vn_file = indx;
6259                 t->vn_aux = sizeof (Elf_External_Verneed);
6260                 if (t->vn_nextref == NULL)
6261                   t->vn_next = 0;
6262                 else
6263                   t->vn_next = (sizeof (Elf_External_Verneed)
6264                                 + caux * sizeof (Elf_External_Vernaux));
6265
6266                 _bfd_elf_swap_verneed_out (output_bfd, t,
6267                                            (Elf_External_Verneed *) p);
6268                 p += sizeof (Elf_External_Verneed);
6269
6270                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6271                   {
6272                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6273                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6274                                                 a->vna_nodename, FALSE);
6275                     if (indx == (bfd_size_type) -1)
6276                       return FALSE;
6277                     a->vna_name = indx;
6278                     if (a->vna_nextptr == NULL)
6279                       a->vna_next = 0;
6280                     else
6281                       a->vna_next = sizeof (Elf_External_Vernaux);
6282
6283                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6284                                                (Elf_External_Vernaux *) p);
6285                     p += sizeof (Elf_External_Vernaux);
6286                   }
6287               }
6288
6289             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6290                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6291               return FALSE;
6292
6293             elf_tdata (output_bfd)->cverrefs = crefs;
6294           }
6295       }
6296
6297       if ((elf_tdata (output_bfd)->cverrefs == 0
6298            && elf_tdata (output_bfd)->cverdefs == 0)
6299           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6300                                              &section_sym_count) == 0)
6301         {
6302           s = bfd_get_linker_section (dynobj, ".gnu.version");
6303           s->flags |= SEC_EXCLUDE;
6304         }
6305     }
6306   return TRUE;
6307 }
6308
6309 /* Find the first non-excluded output section.  We'll use its
6310    section symbol for some emitted relocs.  */
6311 void
6312 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6313 {
6314   asection *s;
6315
6316   for (s = output_bfd->sections; s != NULL; s = s->next)
6317     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6318         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6319       {
6320         elf_hash_table (info)->text_index_section = s;
6321         break;
6322       }
6323 }
6324
6325 /* Find two non-excluded output sections, one for code, one for data.
6326    We'll use their section symbols for some emitted relocs.  */
6327 void
6328 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6329 {
6330   asection *s;
6331
6332   /* Data first, since setting text_index_section changes
6333      _bfd_elf_link_omit_section_dynsym.  */
6334   for (s = output_bfd->sections; s != NULL; s = s->next)
6335     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6336         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6337       {
6338         elf_hash_table (info)->data_index_section = s;
6339         break;
6340       }
6341
6342   for (s = output_bfd->sections; s != NULL; s = s->next)
6343     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6344          == (SEC_ALLOC | SEC_READONLY))
6345         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6346       {
6347         elf_hash_table (info)->text_index_section = s;
6348         break;
6349       }
6350
6351   if (elf_hash_table (info)->text_index_section == NULL)
6352     elf_hash_table (info)->text_index_section
6353       = elf_hash_table (info)->data_index_section;
6354 }
6355
6356 bfd_boolean
6357 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6358 {
6359   const struct elf_backend_data *bed;
6360
6361   if (!is_elf_hash_table (info->hash))
6362     return TRUE;
6363
6364   bed = get_elf_backend_data (output_bfd);
6365   (*bed->elf_backend_init_index_section) (output_bfd, info);
6366
6367   if (elf_hash_table (info)->dynamic_sections_created)
6368     {
6369       bfd *dynobj;
6370       asection *s;
6371       bfd_size_type dynsymcount;
6372       unsigned long section_sym_count;
6373       unsigned int dtagcount;
6374
6375       dynobj = elf_hash_table (info)->dynobj;
6376
6377       /* Assign dynsym indicies.  In a shared library we generate a
6378          section symbol for each output section, which come first.
6379          Next come all of the back-end allocated local dynamic syms,
6380          followed by the rest of the global symbols.  */
6381
6382       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6383                                                     &section_sym_count);
6384
6385       /* Work out the size of the symbol version section.  */
6386       s = bfd_get_linker_section (dynobj, ".gnu.version");
6387       BFD_ASSERT (s != NULL);
6388       if (dynsymcount != 0
6389           && (s->flags & SEC_EXCLUDE) == 0)
6390         {
6391           s->size = dynsymcount * sizeof (Elf_External_Versym);
6392           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6393           if (s->contents == NULL)
6394             return FALSE;
6395
6396           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6397             return FALSE;
6398         }
6399
6400       /* Set the size of the .dynsym and .hash sections.  We counted
6401          the number of dynamic symbols in elf_link_add_object_symbols.
6402          We will build the contents of .dynsym and .hash when we build
6403          the final symbol table, because until then we do not know the
6404          correct value to give the symbols.  We built the .dynstr
6405          section as we went along in elf_link_add_object_symbols.  */
6406       s = bfd_get_linker_section (dynobj, ".dynsym");
6407       BFD_ASSERT (s != NULL);
6408       s->size = dynsymcount * bed->s->sizeof_sym;
6409
6410       if (dynsymcount != 0)
6411         {
6412           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6413           if (s->contents == NULL)
6414             return FALSE;
6415
6416           /* The first entry in .dynsym is a dummy symbol.
6417              Clear all the section syms, in case we don't output them all.  */
6418           ++section_sym_count;
6419           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6420         }
6421
6422       elf_hash_table (info)->bucketcount = 0;
6423
6424       /* Compute the size of the hashing table.  As a side effect this
6425          computes the hash values for all the names we export.  */
6426       if (info->emit_hash)
6427         {
6428           unsigned long int *hashcodes;
6429           struct hash_codes_info hashinf;
6430           bfd_size_type amt;
6431           unsigned long int nsyms;
6432           size_t bucketcount;
6433           size_t hash_entry_size;
6434
6435           /* Compute the hash values for all exported symbols.  At the same
6436              time store the values in an array so that we could use them for
6437              optimizations.  */
6438           amt = dynsymcount * sizeof (unsigned long int);
6439           hashcodes = (unsigned long int *) bfd_malloc (amt);
6440           if (hashcodes == NULL)
6441             return FALSE;
6442           hashinf.hashcodes = hashcodes;
6443           hashinf.error = FALSE;
6444
6445           /* Put all hash values in HASHCODES.  */
6446           elf_link_hash_traverse (elf_hash_table (info),
6447                                   elf_collect_hash_codes, &hashinf);
6448           if (hashinf.error)
6449             {
6450               free (hashcodes);
6451               return FALSE;
6452             }
6453
6454           nsyms = hashinf.hashcodes - hashcodes;
6455           bucketcount
6456             = compute_bucket_count (info, hashcodes, nsyms, 0);
6457           free (hashcodes);
6458
6459           if (bucketcount == 0)
6460             return FALSE;
6461
6462           elf_hash_table (info)->bucketcount = bucketcount;
6463
6464           s = bfd_get_linker_section (dynobj, ".hash");
6465           BFD_ASSERT (s != NULL);
6466           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6467           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6468           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6469           if (s->contents == NULL)
6470             return FALSE;
6471
6472           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6473           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6474                    s->contents + hash_entry_size);
6475         }
6476
6477       if (info->emit_gnu_hash)
6478         {
6479           size_t i, cnt;
6480           unsigned char *contents;
6481           struct collect_gnu_hash_codes cinfo;
6482           bfd_size_type amt;
6483           size_t bucketcount;
6484
6485           memset (&cinfo, 0, sizeof (cinfo));
6486
6487           /* Compute the hash values for all exported symbols.  At the same
6488              time store the values in an array so that we could use them for
6489              optimizations.  */
6490           amt = dynsymcount * 2 * sizeof (unsigned long int);
6491           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6492           if (cinfo.hashcodes == NULL)
6493             return FALSE;
6494
6495           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6496           cinfo.min_dynindx = -1;
6497           cinfo.output_bfd = output_bfd;
6498           cinfo.bed = bed;
6499
6500           /* Put all hash values in HASHCODES.  */
6501           elf_link_hash_traverse (elf_hash_table (info),
6502                                   elf_collect_gnu_hash_codes, &cinfo);
6503           if (cinfo.error)
6504             {
6505               free (cinfo.hashcodes);
6506               return FALSE;
6507             }
6508
6509           bucketcount
6510             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6511
6512           if (bucketcount == 0)
6513             {
6514               free (cinfo.hashcodes);
6515               return FALSE;
6516             }
6517
6518           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6519           BFD_ASSERT (s != NULL);
6520
6521           if (cinfo.nsyms == 0)
6522             {
6523               /* Empty .gnu.hash section is special.  */
6524               BFD_ASSERT (cinfo.min_dynindx == -1);
6525               free (cinfo.hashcodes);
6526               s->size = 5 * 4 + bed->s->arch_size / 8;
6527               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6528               if (contents == NULL)
6529                 return FALSE;
6530               s->contents = contents;
6531               /* 1 empty bucket.  */
6532               bfd_put_32 (output_bfd, 1, contents);
6533               /* SYMIDX above the special symbol 0.  */
6534               bfd_put_32 (output_bfd, 1, contents + 4);
6535               /* Just one word for bitmask.  */
6536               bfd_put_32 (output_bfd, 1, contents + 8);
6537               /* Only hash fn bloom filter.  */
6538               bfd_put_32 (output_bfd, 0, contents + 12);
6539               /* No hashes are valid - empty bitmask.  */
6540               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6541               /* No hashes in the only bucket.  */
6542               bfd_put_32 (output_bfd, 0,
6543                           contents + 16 + bed->s->arch_size / 8);
6544             }
6545           else
6546             {
6547               unsigned long int maskwords, maskbitslog2, x;
6548               BFD_ASSERT (cinfo.min_dynindx != -1);
6549
6550               x = cinfo.nsyms;
6551               maskbitslog2 = 1;
6552               while ((x >>= 1) != 0)
6553                 ++maskbitslog2;
6554               if (maskbitslog2 < 3)
6555                 maskbitslog2 = 5;
6556               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6557                 maskbitslog2 = maskbitslog2 + 3;
6558               else
6559                 maskbitslog2 = maskbitslog2 + 2;
6560               if (bed->s->arch_size == 64)
6561                 {
6562                   if (maskbitslog2 == 5)
6563                     maskbitslog2 = 6;
6564                   cinfo.shift1 = 6;
6565                 }
6566               else
6567                 cinfo.shift1 = 5;
6568               cinfo.mask = (1 << cinfo.shift1) - 1;
6569               cinfo.shift2 = maskbitslog2;
6570               cinfo.maskbits = 1 << maskbitslog2;
6571               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6572               amt = bucketcount * sizeof (unsigned long int) * 2;
6573               amt += maskwords * sizeof (bfd_vma);
6574               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6575               if (cinfo.bitmask == NULL)
6576                 {
6577                   free (cinfo.hashcodes);
6578                   return FALSE;
6579                 }
6580
6581               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6582               cinfo.indx = cinfo.counts + bucketcount;
6583               cinfo.symindx = dynsymcount - cinfo.nsyms;
6584               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6585
6586               /* Determine how often each hash bucket is used.  */
6587               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6588               for (i = 0; i < cinfo.nsyms; ++i)
6589                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6590
6591               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6592                 if (cinfo.counts[i] != 0)
6593                   {
6594                     cinfo.indx[i] = cnt;
6595                     cnt += cinfo.counts[i];
6596                   }
6597               BFD_ASSERT (cnt == dynsymcount);
6598               cinfo.bucketcount = bucketcount;
6599               cinfo.local_indx = cinfo.min_dynindx;
6600
6601               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6602               s->size += cinfo.maskbits / 8;
6603               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6604               if (contents == NULL)
6605                 {
6606                   free (cinfo.bitmask);
6607                   free (cinfo.hashcodes);
6608                   return FALSE;
6609                 }
6610
6611               s->contents = contents;
6612               bfd_put_32 (output_bfd, bucketcount, contents);
6613               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6614               bfd_put_32 (output_bfd, maskwords, contents + 8);
6615               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6616               contents += 16 + cinfo.maskbits / 8;
6617
6618               for (i = 0; i < bucketcount; ++i)
6619                 {
6620                   if (cinfo.counts[i] == 0)
6621                     bfd_put_32 (output_bfd, 0, contents);
6622                   else
6623                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6624                   contents += 4;
6625                 }
6626
6627               cinfo.contents = contents;
6628
6629               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6630               elf_link_hash_traverse (elf_hash_table (info),
6631                                       elf_renumber_gnu_hash_syms, &cinfo);
6632
6633               contents = s->contents + 16;
6634               for (i = 0; i < maskwords; ++i)
6635                 {
6636                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6637                            contents);
6638                   contents += bed->s->arch_size / 8;
6639                 }
6640
6641               free (cinfo.bitmask);
6642               free (cinfo.hashcodes);
6643             }
6644         }
6645
6646       s = bfd_get_linker_section (dynobj, ".dynstr");
6647       BFD_ASSERT (s != NULL);
6648
6649       elf_finalize_dynstr (output_bfd, info);
6650
6651       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6652
6653       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6654         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6655           return FALSE;
6656     }
6657
6658   return TRUE;
6659 }
6660 \f
6661 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6662
6663 static void
6664 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6665                             asection *sec)
6666 {
6667   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6668   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6669 }
6670
6671 /* Finish SHF_MERGE section merging.  */
6672
6673 bfd_boolean
6674 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6675 {
6676   bfd *ibfd;
6677   asection *sec;
6678
6679   if (!is_elf_hash_table (info->hash))
6680     return FALSE;
6681
6682   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6683     if ((ibfd->flags & DYNAMIC) == 0)
6684       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6685         if ((sec->flags & SEC_MERGE) != 0
6686             && !bfd_is_abs_section (sec->output_section))
6687           {
6688             struct bfd_elf_section_data *secdata;
6689
6690             secdata = elf_section_data (sec);
6691             if (! _bfd_add_merge_section (abfd,
6692                                           &elf_hash_table (info)->merge_info,
6693                                           sec, &secdata->sec_info))
6694               return FALSE;
6695             else if (secdata->sec_info)
6696               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6697           }
6698
6699   if (elf_hash_table (info)->merge_info != NULL)
6700     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6701                          merge_sections_remove_hook);
6702   return TRUE;
6703 }
6704
6705 /* Create an entry in an ELF linker hash table.  */
6706
6707 struct bfd_hash_entry *
6708 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6709                             struct bfd_hash_table *table,
6710                             const char *string)
6711 {
6712   /* Allocate the structure if it has not already been allocated by a
6713      subclass.  */
6714   if (entry == NULL)
6715     {
6716       entry = (struct bfd_hash_entry *)
6717           bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6718       if (entry == NULL)
6719         return entry;
6720     }
6721
6722   /* Call the allocation method of the superclass.  */
6723   entry = _bfd_link_hash_newfunc (entry, table, string);
6724   if (entry != NULL)
6725     {
6726       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6727       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6728
6729       /* Set local fields.  */
6730       ret->indx = -1;
6731       ret->dynindx = -1;
6732       ret->got = htab->init_got_refcount;
6733       ret->plt = htab->init_plt_refcount;
6734       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6735                               - offsetof (struct elf_link_hash_entry, size)));
6736       /* Assume that we have been called by a non-ELF symbol reader.
6737          This flag is then reset by the code which reads an ELF input
6738          file.  This ensures that a symbol created by a non-ELF symbol
6739          reader will have the flag set correctly.  */
6740       ret->non_elf = 1;
6741     }
6742
6743   return entry;
6744 }
6745
6746 /* Copy data from an indirect symbol to its direct symbol, hiding the
6747    old indirect symbol.  Also used for copying flags to a weakdef.  */
6748
6749 void
6750 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6751                                   struct elf_link_hash_entry *dir,
6752                                   struct elf_link_hash_entry *ind)
6753 {
6754   struct elf_link_hash_table *htab;
6755
6756   /* Copy down any references that we may have already seen to the
6757      symbol which just became indirect.  */
6758
6759   dir->ref_dynamic |= ind->ref_dynamic;
6760   dir->ref_regular |= ind->ref_regular;
6761   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6762   dir->non_got_ref |= ind->non_got_ref;
6763   dir->needs_plt |= ind->needs_plt;
6764   dir->pointer_equality_needed |= ind->pointer_equality_needed;
6765
6766   if (ind->root.type != bfd_link_hash_indirect)
6767     return;
6768
6769   /* Copy over the global and procedure linkage table refcount entries.
6770      These may have been already set up by a check_relocs routine.  */
6771   htab = elf_hash_table (info);
6772   if (ind->got.refcount > htab->init_got_refcount.refcount)
6773     {
6774       if (dir->got.refcount < 0)
6775         dir->got.refcount = 0;
6776       dir->got.refcount += ind->got.refcount;
6777       ind->got.refcount = htab->init_got_refcount.refcount;
6778     }
6779
6780   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6781     {
6782       if (dir->plt.refcount < 0)
6783         dir->plt.refcount = 0;
6784       dir->plt.refcount += ind->plt.refcount;
6785       ind->plt.refcount = htab->init_plt_refcount.refcount;
6786     }
6787
6788   if (ind->dynindx != -1)
6789     {
6790       if (dir->dynindx != -1)
6791         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6792       dir->dynindx = ind->dynindx;
6793       dir->dynstr_index = ind->dynstr_index;
6794       ind->dynindx = -1;
6795       ind->dynstr_index = 0;
6796     }
6797 }
6798
6799 void
6800 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6801                                 struct elf_link_hash_entry *h,
6802                                 bfd_boolean force_local)
6803 {
6804   /* STT_GNU_IFUNC symbol must go through PLT.  */
6805   if (h->type != STT_GNU_IFUNC)
6806     {
6807       h->plt = elf_hash_table (info)->init_plt_offset;
6808       h->needs_plt = 0;
6809     }
6810   if (force_local)
6811     {
6812       h->forced_local = 1;
6813       if (h->dynindx != -1)
6814         {
6815           h->dynindx = -1;
6816           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6817                                   h->dynstr_index);
6818         }
6819     }
6820 }
6821
6822 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
6823    caller.  */
6824
6825 bfd_boolean
6826 _bfd_elf_link_hash_table_init
6827   (struct elf_link_hash_table *table,
6828    bfd *abfd,
6829    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6830                                       struct bfd_hash_table *,
6831                                       const char *),
6832    unsigned int entsize,
6833    enum elf_target_id target_id)
6834 {
6835   bfd_boolean ret;
6836   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6837
6838   table->init_got_refcount.refcount = can_refcount - 1;
6839   table->init_plt_refcount.refcount = can_refcount - 1;
6840   table->init_got_offset.offset = -(bfd_vma) 1;
6841   table->init_plt_offset.offset = -(bfd_vma) 1;
6842   /* The first dynamic symbol is a dummy.  */
6843   table->dynsymcount = 1;
6844
6845   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6846
6847   table->root.type = bfd_link_elf_hash_table;
6848   table->hash_table_id = target_id;
6849
6850   return ret;
6851 }
6852
6853 /* Create an ELF linker hash table.  */
6854
6855 struct bfd_link_hash_table *
6856 _bfd_elf_link_hash_table_create (bfd *abfd)
6857 {
6858   struct elf_link_hash_table *ret;
6859   bfd_size_type amt = sizeof (struct elf_link_hash_table);
6860
6861   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
6862   if (ret == NULL)
6863     return NULL;
6864
6865   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
6866                                        sizeof (struct elf_link_hash_entry),
6867                                        GENERIC_ELF_DATA))
6868     {
6869       free (ret);
6870       return NULL;
6871     }
6872   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
6873
6874   return &ret->root;
6875 }
6876
6877 /* Destroy an ELF linker hash table.  */
6878
6879 void
6880 _bfd_elf_link_hash_table_free (bfd *obfd)
6881 {
6882   struct elf_link_hash_table *htab;
6883
6884   htab = (struct elf_link_hash_table *) obfd->link.hash;
6885   if (htab->dynstr != NULL)
6886     _bfd_elf_strtab_free (htab->dynstr);
6887   _bfd_merge_sections_free (htab->merge_info);
6888   _bfd_generic_link_hash_table_free (obfd);
6889 }
6890
6891 /* This is a hook for the ELF emulation code in the generic linker to
6892    tell the backend linker what file name to use for the DT_NEEDED
6893    entry for a dynamic object.  */
6894
6895 void
6896 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
6897 {
6898   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6899       && bfd_get_format (abfd) == bfd_object)
6900     elf_dt_name (abfd) = name;
6901 }
6902
6903 int
6904 bfd_elf_get_dyn_lib_class (bfd *abfd)
6905 {
6906   int lib_class;
6907   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6908       && bfd_get_format (abfd) == bfd_object)
6909     lib_class = elf_dyn_lib_class (abfd);
6910   else
6911     lib_class = 0;
6912   return lib_class;
6913 }
6914
6915 void
6916 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
6917 {
6918   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6919       && bfd_get_format (abfd) == bfd_object)
6920     elf_dyn_lib_class (abfd) = lib_class;
6921 }
6922
6923 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
6924    the linker ELF emulation code.  */
6925
6926 struct bfd_link_needed_list *
6927 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
6928                          struct bfd_link_info *info)
6929 {
6930   if (! is_elf_hash_table (info->hash))
6931     return NULL;
6932   return elf_hash_table (info)->needed;
6933 }
6934
6935 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
6936    hook for the linker ELF emulation code.  */
6937
6938 struct bfd_link_needed_list *
6939 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
6940                           struct bfd_link_info *info)
6941 {
6942   if (! is_elf_hash_table (info->hash))
6943     return NULL;
6944   return elf_hash_table (info)->runpath;
6945 }
6946
6947 /* Get the name actually used for a dynamic object for a link.  This
6948    is the SONAME entry if there is one.  Otherwise, it is the string
6949    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
6950
6951 const char *
6952 bfd_elf_get_dt_soname (bfd *abfd)
6953 {
6954   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6955       && bfd_get_format (abfd) == bfd_object)
6956     return elf_dt_name (abfd);
6957   return NULL;
6958 }
6959
6960 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
6961    the ELF linker emulation code.  */
6962
6963 bfd_boolean
6964 bfd_elf_get_bfd_needed_list (bfd *abfd,
6965                              struct bfd_link_needed_list **pneeded)
6966 {
6967   asection *s;
6968   bfd_byte *dynbuf = NULL;
6969   unsigned int elfsec;
6970   unsigned long shlink;
6971   bfd_byte *extdyn, *extdynend;
6972   size_t extdynsize;
6973   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
6974
6975   *pneeded = NULL;
6976
6977   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
6978       || bfd_get_format (abfd) != bfd_object)
6979     return TRUE;
6980
6981   s = bfd_get_section_by_name (abfd, ".dynamic");
6982   if (s == NULL || s->size == 0)
6983     return TRUE;
6984
6985   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
6986     goto error_return;
6987
6988   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
6989   if (elfsec == SHN_BAD)
6990     goto error_return;
6991
6992   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
6993
6994   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
6995   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
6996
6997   extdyn = dynbuf;
6998   extdynend = extdyn + s->size;
6999   for (; extdyn < extdynend; extdyn += extdynsize)
7000     {
7001       Elf_Internal_Dyn dyn;
7002
7003       (*swap_dyn_in) (abfd, extdyn, &dyn);
7004
7005       if (dyn.d_tag == DT_NULL)
7006         break;
7007
7008       if (dyn.d_tag == DT_NEEDED)
7009         {
7010           const char *string;
7011           struct bfd_link_needed_list *l;
7012           unsigned int tagv = dyn.d_un.d_val;
7013           bfd_size_type amt;
7014
7015           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7016           if (string == NULL)
7017             goto error_return;
7018
7019           amt = sizeof *l;
7020           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7021           if (l == NULL)
7022             goto error_return;
7023
7024           l->by = abfd;
7025           l->name = string;
7026           l->next = *pneeded;
7027           *pneeded = l;
7028         }
7029     }
7030
7031   free (dynbuf);
7032
7033   return TRUE;
7034
7035  error_return:
7036   if (dynbuf != NULL)
7037     free (dynbuf);
7038   return FALSE;
7039 }
7040
7041 struct elf_symbuf_symbol
7042 {
7043   unsigned long st_name;        /* Symbol name, index in string tbl */
7044   unsigned char st_info;        /* Type and binding attributes */
7045   unsigned char st_other;       /* Visibilty, and target specific */
7046 };
7047
7048 struct elf_symbuf_head
7049 {
7050   struct elf_symbuf_symbol *ssym;
7051   bfd_size_type count;
7052   unsigned int st_shndx;
7053 };
7054
7055 struct elf_symbol
7056 {
7057   union
7058     {
7059       Elf_Internal_Sym *isym;
7060       struct elf_symbuf_symbol *ssym;
7061     } u;
7062   const char *name;
7063 };
7064
7065 /* Sort references to symbols by ascending section number.  */
7066
7067 static int
7068 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7069 {
7070   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7071   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7072
7073   return s1->st_shndx - s2->st_shndx;
7074 }
7075
7076 static int
7077 elf_sym_name_compare (const void *arg1, const void *arg2)
7078 {
7079   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7080   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7081   return strcmp (s1->name, s2->name);
7082 }
7083
7084 static struct elf_symbuf_head *
7085 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7086 {
7087   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7088   struct elf_symbuf_symbol *ssym;
7089   struct elf_symbuf_head *ssymbuf, *ssymhead;
7090   bfd_size_type i, shndx_count, total_size;
7091
7092   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7093   if (indbuf == NULL)
7094     return NULL;
7095
7096   for (ind = indbuf, i = 0; i < symcount; i++)
7097     if (isymbuf[i].st_shndx != SHN_UNDEF)
7098       *ind++ = &isymbuf[i];
7099   indbufend = ind;
7100
7101   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7102          elf_sort_elf_symbol);
7103
7104   shndx_count = 0;
7105   if (indbufend > indbuf)
7106     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7107       if (ind[0]->st_shndx != ind[1]->st_shndx)
7108         shndx_count++;
7109
7110   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7111                 + (indbufend - indbuf) * sizeof (*ssym));
7112   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7113   if (ssymbuf == NULL)
7114     {
7115       free (indbuf);
7116       return NULL;
7117     }
7118
7119   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7120   ssymbuf->ssym = NULL;
7121   ssymbuf->count = shndx_count;
7122   ssymbuf->st_shndx = 0;
7123   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7124     {
7125       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7126         {
7127           ssymhead++;
7128           ssymhead->ssym = ssym;
7129           ssymhead->count = 0;
7130           ssymhead->st_shndx = (*ind)->st_shndx;
7131         }
7132       ssym->st_name = (*ind)->st_name;
7133       ssym->st_info = (*ind)->st_info;
7134       ssym->st_other = (*ind)->st_other;
7135       ssymhead->count++;
7136     }
7137   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7138               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7139                   == total_size));
7140
7141   free (indbuf);
7142   return ssymbuf;
7143 }
7144
7145 /* Check if 2 sections define the same set of local and global
7146    symbols.  */
7147
7148 static bfd_boolean
7149 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7150                                    struct bfd_link_info *info)
7151 {
7152   bfd *bfd1, *bfd2;
7153   const struct elf_backend_data *bed1, *bed2;
7154   Elf_Internal_Shdr *hdr1, *hdr2;
7155   bfd_size_type symcount1, symcount2;
7156   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7157   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7158   Elf_Internal_Sym *isym, *isymend;
7159   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7160   bfd_size_type count1, count2, i;
7161   unsigned int shndx1, shndx2;
7162   bfd_boolean result;
7163
7164   bfd1 = sec1->owner;
7165   bfd2 = sec2->owner;
7166
7167   /* Both sections have to be in ELF.  */
7168   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7169       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7170     return FALSE;
7171
7172   if (elf_section_type (sec1) != elf_section_type (sec2))
7173     return FALSE;
7174
7175   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7176   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7177   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7178     return FALSE;
7179
7180   bed1 = get_elf_backend_data (bfd1);
7181   bed2 = get_elf_backend_data (bfd2);
7182   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7183   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7184   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7185   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7186
7187   if (symcount1 == 0 || symcount2 == 0)
7188     return FALSE;
7189
7190   result = FALSE;
7191   isymbuf1 = NULL;
7192   isymbuf2 = NULL;
7193   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7194   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7195
7196   if (ssymbuf1 == NULL)
7197     {
7198       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7199                                        NULL, NULL, NULL);
7200       if (isymbuf1 == NULL)
7201         goto done;
7202
7203       if (!info->reduce_memory_overheads)
7204         elf_tdata (bfd1)->symbuf = ssymbuf1
7205           = elf_create_symbuf (symcount1, isymbuf1);
7206     }
7207
7208   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7209     {
7210       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7211                                        NULL, NULL, NULL);
7212       if (isymbuf2 == NULL)
7213         goto done;
7214
7215       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7216         elf_tdata (bfd2)->symbuf = ssymbuf2
7217           = elf_create_symbuf (symcount2, isymbuf2);
7218     }
7219
7220   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7221     {
7222       /* Optimized faster version.  */
7223       bfd_size_type lo, hi, mid;
7224       struct elf_symbol *symp;
7225       struct elf_symbuf_symbol *ssym, *ssymend;
7226
7227       lo = 0;
7228       hi = ssymbuf1->count;
7229       ssymbuf1++;
7230       count1 = 0;
7231       while (lo < hi)
7232         {
7233           mid = (lo + hi) / 2;
7234           if (shndx1 < ssymbuf1[mid].st_shndx)
7235             hi = mid;
7236           else if (shndx1 > ssymbuf1[mid].st_shndx)
7237             lo = mid + 1;
7238           else
7239             {
7240               count1 = ssymbuf1[mid].count;
7241               ssymbuf1 += mid;
7242               break;
7243             }
7244         }
7245
7246       lo = 0;
7247       hi = ssymbuf2->count;
7248       ssymbuf2++;
7249       count2 = 0;
7250       while (lo < hi)
7251         {
7252           mid = (lo + hi) / 2;
7253           if (shndx2 < ssymbuf2[mid].st_shndx)
7254             hi = mid;
7255           else if (shndx2 > ssymbuf2[mid].st_shndx)
7256             lo = mid + 1;
7257           else
7258             {
7259               count2 = ssymbuf2[mid].count;
7260               ssymbuf2 += mid;
7261               break;
7262             }
7263         }
7264
7265       if (count1 == 0 || count2 == 0 || count1 != count2)
7266         goto done;
7267
7268       symtable1 = (struct elf_symbol *)
7269           bfd_malloc (count1 * sizeof (struct elf_symbol));
7270       symtable2 = (struct elf_symbol *)
7271           bfd_malloc (count2 * sizeof (struct elf_symbol));
7272       if (symtable1 == NULL || symtable2 == NULL)
7273         goto done;
7274
7275       symp = symtable1;
7276       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7277            ssym < ssymend; ssym++, symp++)
7278         {
7279           symp->u.ssym = ssym;
7280           symp->name = bfd_elf_string_from_elf_section (bfd1,
7281                                                         hdr1->sh_link,
7282                                                         ssym->st_name);
7283         }
7284
7285       symp = symtable2;
7286       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7287            ssym < ssymend; ssym++, symp++)
7288         {
7289           symp->u.ssym = ssym;
7290           symp->name = bfd_elf_string_from_elf_section (bfd2,
7291                                                         hdr2->sh_link,
7292                                                         ssym->st_name);
7293         }
7294
7295       /* Sort symbol by name.  */
7296       qsort (symtable1, count1, sizeof (struct elf_symbol),
7297              elf_sym_name_compare);
7298       qsort (symtable2, count1, sizeof (struct elf_symbol),
7299              elf_sym_name_compare);
7300
7301       for (i = 0; i < count1; i++)
7302         /* Two symbols must have the same binding, type and name.  */
7303         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7304             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7305             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7306           goto done;
7307
7308       result = TRUE;
7309       goto done;
7310     }
7311
7312   symtable1 = (struct elf_symbol *)
7313       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7314   symtable2 = (struct elf_symbol *)
7315       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7316   if (symtable1 == NULL || symtable2 == NULL)
7317     goto done;
7318
7319   /* Count definitions in the section.  */
7320   count1 = 0;
7321   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7322     if (isym->st_shndx == shndx1)
7323       symtable1[count1++].u.isym = isym;
7324
7325   count2 = 0;
7326   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7327     if (isym->st_shndx == shndx2)
7328       symtable2[count2++].u.isym = isym;
7329
7330   if (count1 == 0 || count2 == 0 || count1 != count2)
7331     goto done;
7332
7333   for (i = 0; i < count1; i++)
7334     symtable1[i].name
7335       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7336                                          symtable1[i].u.isym->st_name);
7337
7338   for (i = 0; i < count2; i++)
7339     symtable2[i].name
7340       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7341                                          symtable2[i].u.isym->st_name);
7342
7343   /* Sort symbol by name.  */
7344   qsort (symtable1, count1, sizeof (struct elf_symbol),
7345          elf_sym_name_compare);
7346   qsort (symtable2, count1, sizeof (struct elf_symbol),
7347          elf_sym_name_compare);
7348
7349   for (i = 0; i < count1; i++)
7350     /* Two symbols must have the same binding, type and name.  */
7351     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7352         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7353         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7354       goto done;
7355
7356   result = TRUE;
7357
7358 done:
7359   if (symtable1)
7360     free (symtable1);
7361   if (symtable2)
7362     free (symtable2);
7363   if (isymbuf1)
7364     free (isymbuf1);
7365   if (isymbuf2)
7366     free (isymbuf2);
7367
7368   return result;
7369 }
7370
7371 /* Return TRUE if 2 section types are compatible.  */
7372
7373 bfd_boolean
7374 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7375                                  bfd *bbfd, const asection *bsec)
7376 {
7377   if (asec == NULL
7378       || bsec == NULL
7379       || abfd->xvec->flavour != bfd_target_elf_flavour
7380       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7381     return TRUE;
7382
7383   return elf_section_type (asec) == elf_section_type (bsec);
7384 }
7385 \f
7386 /* Final phase of ELF linker.  */
7387
7388 /* A structure we use to avoid passing large numbers of arguments.  */
7389
7390 struct elf_final_link_info
7391 {
7392   /* General link information.  */
7393   struct bfd_link_info *info;
7394   /* Output BFD.  */
7395   bfd *output_bfd;
7396   /* Symbol string table.  */
7397   struct bfd_strtab_hash *symstrtab;
7398   /* .dynsym section.  */
7399   asection *dynsym_sec;
7400   /* .hash section.  */
7401   asection *hash_sec;
7402   /* symbol version section (.gnu.version).  */
7403   asection *symver_sec;
7404   /* Buffer large enough to hold contents of any section.  */
7405   bfd_byte *contents;
7406   /* Buffer large enough to hold external relocs of any section.  */
7407   void *external_relocs;
7408   /* Buffer large enough to hold internal relocs of any section.  */
7409   Elf_Internal_Rela *internal_relocs;
7410   /* Buffer large enough to hold external local symbols of any input
7411      BFD.  */
7412   bfd_byte *external_syms;
7413   /* And a buffer for symbol section indices.  */
7414   Elf_External_Sym_Shndx *locsym_shndx;
7415   /* Buffer large enough to hold internal local symbols of any input
7416      BFD.  */
7417   Elf_Internal_Sym *internal_syms;
7418   /* Array large enough to hold a symbol index for each local symbol
7419      of any input BFD.  */
7420   long *indices;
7421   /* Array large enough to hold a section pointer for each local
7422      symbol of any input BFD.  */
7423   asection **sections;
7424   /* Buffer to hold swapped out symbols.  */
7425   bfd_byte *symbuf;
7426   /* And one for symbol section indices.  */
7427   Elf_External_Sym_Shndx *symshndxbuf;
7428   /* Number of swapped out symbols in buffer.  */
7429   size_t symbuf_count;
7430   /* Number of symbols which fit in symbuf.  */
7431   size_t symbuf_size;
7432   /* And same for symshndxbuf.  */
7433   size_t shndxbuf_size;
7434   /* Number of STT_FILE syms seen.  */
7435   size_t filesym_count;
7436 };
7437
7438 /* This struct is used to pass information to elf_link_output_extsym.  */
7439
7440 struct elf_outext_info
7441 {
7442   bfd_boolean failed;
7443   bfd_boolean localsyms;
7444   bfd_boolean need_second_pass;
7445   bfd_boolean second_pass;
7446   bfd_boolean file_sym_done;
7447   struct elf_final_link_info *flinfo;
7448 };
7449
7450
7451 /* Support for evaluating a complex relocation.
7452
7453    Complex relocations are generalized, self-describing relocations.  The
7454    implementation of them consists of two parts: complex symbols, and the
7455    relocations themselves.
7456
7457    The relocations are use a reserved elf-wide relocation type code (R_RELC
7458    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7459    information (start bit, end bit, word width, etc) into the addend.  This
7460    information is extracted from CGEN-generated operand tables within gas.
7461
7462    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7463    internal) representing prefix-notation expressions, including but not
7464    limited to those sorts of expressions normally encoded as addends in the
7465    addend field.  The symbol mangling format is:
7466
7467    <node> := <literal>
7468           |  <unary-operator> ':' <node>
7469           |  <binary-operator> ':' <node> ':' <node>
7470           ;
7471
7472    <literal> := 's' <digits=N> ':' <N character symbol name>
7473              |  'S' <digits=N> ':' <N character section name>
7474              |  '#' <hexdigits>
7475              ;
7476
7477    <binary-operator> := as in C
7478    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7479
7480 static void
7481 set_symbol_value (bfd *bfd_with_globals,
7482                   Elf_Internal_Sym *isymbuf,
7483                   size_t locsymcount,
7484                   size_t symidx,
7485                   bfd_vma val)
7486 {
7487   struct elf_link_hash_entry **sym_hashes;
7488   struct elf_link_hash_entry *h;
7489   size_t extsymoff = locsymcount;
7490
7491   if (symidx < locsymcount)
7492     {
7493       Elf_Internal_Sym *sym;
7494
7495       sym = isymbuf + symidx;
7496       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7497         {
7498           /* It is a local symbol: move it to the
7499              "absolute" section and give it a value.  */
7500           sym->st_shndx = SHN_ABS;
7501           sym->st_value = val;
7502           return;
7503         }
7504       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7505       extsymoff = 0;
7506     }
7507
7508   /* It is a global symbol: set its link type
7509      to "defined" and give it a value.  */
7510
7511   sym_hashes = elf_sym_hashes (bfd_with_globals);
7512   h = sym_hashes [symidx - extsymoff];
7513   while (h->root.type == bfd_link_hash_indirect
7514          || h->root.type == bfd_link_hash_warning)
7515     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7516   h->root.type = bfd_link_hash_defined;
7517   h->root.u.def.value = val;
7518   h->root.u.def.section = bfd_abs_section_ptr;
7519 }
7520
7521 static bfd_boolean
7522 resolve_symbol (const char *name,
7523                 bfd *input_bfd,
7524                 struct elf_final_link_info *flinfo,
7525                 bfd_vma *result,
7526                 Elf_Internal_Sym *isymbuf,
7527                 size_t locsymcount)
7528 {
7529   Elf_Internal_Sym *sym;
7530   struct bfd_link_hash_entry *global_entry;
7531   const char *candidate = NULL;
7532   Elf_Internal_Shdr *symtab_hdr;
7533   size_t i;
7534
7535   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7536
7537   for (i = 0; i < locsymcount; ++ i)
7538     {
7539       sym = isymbuf + i;
7540
7541       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7542         continue;
7543
7544       candidate = bfd_elf_string_from_elf_section (input_bfd,
7545                                                    symtab_hdr->sh_link,
7546                                                    sym->st_name);
7547 #ifdef DEBUG
7548       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7549               name, candidate, (unsigned long) sym->st_value);
7550 #endif
7551       if (candidate && strcmp (candidate, name) == 0)
7552         {
7553           asection *sec = flinfo->sections [i];
7554
7555           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7556           *result += sec->output_offset + sec->output_section->vma;
7557 #ifdef DEBUG
7558           printf ("Found symbol with value %8.8lx\n",
7559                   (unsigned long) *result);
7560 #endif
7561           return TRUE;
7562         }
7563     }
7564
7565   /* Hmm, haven't found it yet. perhaps it is a global.  */
7566   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7567                                        FALSE, FALSE, TRUE);
7568   if (!global_entry)
7569     return FALSE;
7570
7571   if (global_entry->type == bfd_link_hash_defined
7572       || global_entry->type == bfd_link_hash_defweak)
7573     {
7574       *result = (global_entry->u.def.value
7575                  + global_entry->u.def.section->output_section->vma
7576                  + global_entry->u.def.section->output_offset);
7577 #ifdef DEBUG
7578       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7579               global_entry->root.string, (unsigned long) *result);
7580 #endif
7581       return TRUE;
7582     }
7583
7584   return FALSE;
7585 }
7586
7587 static bfd_boolean
7588 resolve_section (const char *name,
7589                  asection *sections,
7590                  bfd_vma *result)
7591 {
7592   asection *curr;
7593   unsigned int len;
7594
7595   for (curr = sections; curr; curr = curr->next)
7596     if (strcmp (curr->name, name) == 0)
7597       {
7598         *result = curr->vma;
7599         return TRUE;
7600       }
7601
7602   /* Hmm. still haven't found it. try pseudo-section names.  */
7603   for (curr = sections; curr; curr = curr->next)
7604     {
7605       len = strlen (curr->name);
7606       if (len > strlen (name))
7607         continue;
7608
7609       if (strncmp (curr->name, name, len) == 0)
7610         {
7611           if (strncmp (".end", name + len, 4) == 0)
7612             {
7613               *result = curr->vma + curr->size;
7614               return TRUE;
7615             }
7616
7617           /* Insert more pseudo-section names here, if you like.  */
7618         }
7619     }
7620
7621   return FALSE;
7622 }
7623
7624 static void
7625 undefined_reference (const char *reftype, const char *name)
7626 {
7627   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7628                       reftype, name);
7629 }
7630
7631 static bfd_boolean
7632 eval_symbol (bfd_vma *result,
7633              const char **symp,
7634              bfd *input_bfd,
7635              struct elf_final_link_info *flinfo,
7636              bfd_vma dot,
7637              Elf_Internal_Sym *isymbuf,
7638              size_t locsymcount,
7639              int signed_p)
7640 {
7641   size_t len;
7642   size_t symlen;
7643   bfd_vma a;
7644   bfd_vma b;
7645   char symbuf[4096];
7646   const char *sym = *symp;
7647   const char *symend;
7648   bfd_boolean symbol_is_section = FALSE;
7649
7650   len = strlen (sym);
7651   symend = sym + len;
7652
7653   if (len < 1 || len > sizeof (symbuf))
7654     {
7655       bfd_set_error (bfd_error_invalid_operation);
7656       return FALSE;
7657     }
7658
7659   switch (* sym)
7660     {
7661     case '.':
7662       *result = dot;
7663       *symp = sym + 1;
7664       return TRUE;
7665
7666     case '#':
7667       ++sym;
7668       *result = strtoul (sym, (char **) symp, 16);
7669       return TRUE;
7670
7671     case 'S':
7672       symbol_is_section = TRUE;
7673     case 's':
7674       ++sym;
7675       symlen = strtol (sym, (char **) symp, 10);
7676       sym = *symp + 1; /* Skip the trailing ':'.  */
7677
7678       if (symend < sym || symlen + 1 > sizeof (symbuf))
7679         {
7680           bfd_set_error (bfd_error_invalid_operation);
7681           return FALSE;
7682         }
7683
7684       memcpy (symbuf, sym, symlen);
7685       symbuf[symlen] = '\0';
7686       *symp = sym + symlen;
7687
7688       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7689          the symbol as a section, or vice-versa. so we're pretty liberal in our
7690          interpretation here; section means "try section first", not "must be a
7691          section", and likewise with symbol.  */
7692
7693       if (symbol_is_section)
7694         {
7695           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7696               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7697                                   isymbuf, locsymcount))
7698             {
7699               undefined_reference ("section", symbuf);
7700               return FALSE;
7701             }
7702         }
7703       else
7704         {
7705           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7706                                isymbuf, locsymcount)
7707               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7708                                    result))
7709             {
7710               undefined_reference ("symbol", symbuf);
7711               return FALSE;
7712             }
7713         }
7714
7715       return TRUE;
7716
7717       /* All that remains are operators.  */
7718
7719 #define UNARY_OP(op)                                            \
7720   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7721     {                                                           \
7722       sym += strlen (#op);                                      \
7723       if (*sym == ':')                                          \
7724         ++sym;                                                  \
7725       *symp = sym;                                              \
7726       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7727                         isymbuf, locsymcount, signed_p))        \
7728         return FALSE;                                           \
7729       if (signed_p)                                             \
7730         *result = op ((bfd_signed_vma) a);                      \
7731       else                                                      \
7732         *result = op a;                                         \
7733       return TRUE;                                              \
7734     }
7735
7736 #define BINARY_OP(op)                                           \
7737   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7738     {                                                           \
7739       sym += strlen (#op);                                      \
7740       if (*sym == ':')                                          \
7741         ++sym;                                                  \
7742       *symp = sym;                                              \
7743       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7744                         isymbuf, locsymcount, signed_p))        \
7745         return FALSE;                                           \
7746       ++*symp;                                                  \
7747       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7748                         isymbuf, locsymcount, signed_p))        \
7749         return FALSE;                                           \
7750       if (signed_p)                                             \
7751         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7752       else                                                      \
7753         *result = a op b;                                       \
7754       return TRUE;                                              \
7755     }
7756
7757     default:
7758       UNARY_OP  (0-);
7759       BINARY_OP (<<);
7760       BINARY_OP (>>);
7761       BINARY_OP (==);
7762       BINARY_OP (!=);
7763       BINARY_OP (<=);
7764       BINARY_OP (>=);
7765       BINARY_OP (&&);
7766       BINARY_OP (||);
7767       UNARY_OP  (~);
7768       UNARY_OP  (!);
7769       BINARY_OP (*);
7770       BINARY_OP (/);
7771       BINARY_OP (%);
7772       BINARY_OP (^);
7773       BINARY_OP (|);
7774       BINARY_OP (&);
7775       BINARY_OP (+);
7776       BINARY_OP (-);
7777       BINARY_OP (<);
7778       BINARY_OP (>);
7779 #undef UNARY_OP
7780 #undef BINARY_OP
7781       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7782       bfd_set_error (bfd_error_invalid_operation);
7783       return FALSE;
7784     }
7785 }
7786
7787 static void
7788 put_value (bfd_vma size,
7789            unsigned long chunksz,
7790            bfd *input_bfd,
7791            bfd_vma x,
7792            bfd_byte *location)
7793 {
7794   location += (size - chunksz);
7795
7796   for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
7797     {
7798       switch (chunksz)
7799         {
7800         default:
7801         case 0:
7802           abort ();
7803         case 1:
7804           bfd_put_8 (input_bfd, x, location);
7805           break;
7806         case 2:
7807           bfd_put_16 (input_bfd, x, location);
7808           break;
7809         case 4:
7810           bfd_put_32 (input_bfd, x, location);
7811           break;
7812         case 8:
7813 #ifdef BFD64
7814           bfd_put_64 (input_bfd, x, location);
7815 #else
7816           abort ();
7817 #endif
7818           break;
7819         }
7820     }
7821 }
7822
7823 static bfd_vma
7824 get_value (bfd_vma size,
7825            unsigned long chunksz,
7826            bfd *input_bfd,
7827            bfd_byte *location)
7828 {
7829   int shift;
7830   bfd_vma x = 0;
7831
7832   /* Sanity checks.  */
7833   BFD_ASSERT (chunksz <= sizeof (x)
7834               && size >= chunksz
7835               && chunksz != 0
7836               && (size % chunksz) == 0
7837               && input_bfd != NULL
7838               && location != NULL);
7839
7840   if (chunksz == sizeof (x))
7841     {
7842       BFD_ASSERT (size == chunksz);
7843
7844       /* Make sure that we do not perform an undefined shift operation.
7845          We know that size == chunksz so there will only be one iteration
7846          of the loop below.  */
7847       shift = 0;
7848     }
7849   else
7850     shift = 8 * chunksz;
7851
7852   for (; size; size -= chunksz, location += chunksz)
7853     {
7854       switch (chunksz)
7855         {
7856         case 1:
7857           x = (x << shift) | bfd_get_8 (input_bfd, location);
7858           break;
7859         case 2:
7860           x = (x << shift) | bfd_get_16 (input_bfd, location);
7861           break;
7862         case 4:
7863           x = (x << shift) | bfd_get_32 (input_bfd, location);
7864           break;
7865 #ifdef BFD64
7866         case 8:
7867           x = (x << shift) | bfd_get_64 (input_bfd, location);
7868           break;
7869 #endif
7870         default:
7871           abort ();
7872         }
7873     }
7874   return x;
7875 }
7876
7877 static void
7878 decode_complex_addend (unsigned long *start,   /* in bits */
7879                        unsigned long *oplen,   /* in bits */
7880                        unsigned long *len,     /* in bits */
7881                        unsigned long *wordsz,  /* in bytes */
7882                        unsigned long *chunksz, /* in bytes */
7883                        unsigned long *lsb0_p,
7884                        unsigned long *signed_p,
7885                        unsigned long *trunc_p,
7886                        unsigned long encoded)
7887 {
7888   * start     =  encoded        & 0x3F;
7889   * len       = (encoded >>  6) & 0x3F;
7890   * oplen     = (encoded >> 12) & 0x3F;
7891   * wordsz    = (encoded >> 18) & 0xF;
7892   * chunksz   = (encoded >> 22) & 0xF;
7893   * lsb0_p    = (encoded >> 27) & 1;
7894   * signed_p  = (encoded >> 28) & 1;
7895   * trunc_p   = (encoded >> 29) & 1;
7896 }
7897
7898 bfd_reloc_status_type
7899 bfd_elf_perform_complex_relocation (bfd *input_bfd,
7900                                     asection *input_section ATTRIBUTE_UNUSED,
7901                                     bfd_byte *contents,
7902                                     Elf_Internal_Rela *rel,
7903                                     bfd_vma relocation)
7904 {
7905   bfd_vma shift, x, mask;
7906   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
7907   bfd_reloc_status_type r;
7908
7909   /*  Perform this reloc, since it is complex.
7910       (this is not to say that it necessarily refers to a complex
7911       symbol; merely that it is a self-describing CGEN based reloc.
7912       i.e. the addend has the complete reloc information (bit start, end,
7913       word size, etc) encoded within it.).  */
7914
7915   decode_complex_addend (&start, &oplen, &len, &wordsz,
7916                          &chunksz, &lsb0_p, &signed_p,
7917                          &trunc_p, rel->r_addend);
7918
7919   mask = (((1L << (len - 1)) - 1) << 1) | 1;
7920
7921   if (lsb0_p)
7922     shift = (start + 1) - len;
7923   else
7924     shift = (8 * wordsz) - (start + len);
7925
7926   /* FIXME: octets_per_byte.  */
7927   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7928
7929 #ifdef DEBUG
7930   printf ("Doing complex reloc: "
7931           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7932           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7933           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7934           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7935           oplen, (unsigned long) x, (unsigned long) mask,
7936           (unsigned long) relocation);
7937 #endif
7938
7939   r = bfd_reloc_ok;
7940   if (! trunc_p)
7941     /* Now do an overflow check.  */
7942     r = bfd_check_overflow ((signed_p
7943                              ? complain_overflow_signed
7944                              : complain_overflow_unsigned),
7945                             len, 0, (8 * wordsz),
7946                             relocation);
7947
7948   /* Do the deed.  */
7949   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7950
7951 #ifdef DEBUG
7952   printf ("           relocation: %8.8lx\n"
7953           "         shifted mask: %8.8lx\n"
7954           " shifted/masked reloc: %8.8lx\n"
7955           "               result: %8.8lx\n",
7956           (unsigned long) relocation, (unsigned long) (mask << shift),
7957           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
7958 #endif
7959   /* FIXME: octets_per_byte.  */
7960   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7961   return r;
7962 }
7963
7964 /* qsort comparison functions sorting external relocs by r_offset.  */
7965
7966 static int
7967 cmp_ext32l_r_offset (const void *p, const void *q)
7968 {
7969   union aligned32
7970   {
7971     uint32_t v;
7972     unsigned char c[4];
7973   };
7974   const union aligned32 *a
7975     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
7976   const union aligned32 *b
7977     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
7978
7979   uint32_t aval = (  (uint32_t) a->c[0]
7980                    | (uint32_t) a->c[1] << 8
7981                    | (uint32_t) a->c[2] << 16
7982                    | (uint32_t) a->c[3] << 24);
7983   uint32_t bval = (  (uint32_t) b->c[0]
7984                    | (uint32_t) b->c[1] << 8
7985                    | (uint32_t) b->c[2] << 16
7986                    | (uint32_t) b->c[3] << 24);
7987   if (aval < bval)
7988     return -1;
7989   else if (aval > bval)
7990     return 1;
7991   return 0;
7992 }
7993
7994 static int
7995 cmp_ext32b_r_offset (const void *p, const void *q)
7996 {
7997   union aligned32
7998   {
7999     uint32_t v;
8000     unsigned char c[4];
8001   };
8002   const union aligned32 *a
8003     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8004   const union aligned32 *b
8005     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8006
8007   uint32_t aval = (  (uint32_t) a->c[0] << 24
8008                    | (uint32_t) a->c[1] << 16
8009                    | (uint32_t) a->c[2] << 8
8010                    | (uint32_t) a->c[3]);
8011   uint32_t bval = (  (uint32_t) b->c[0] << 24
8012                    | (uint32_t) b->c[1] << 16
8013                    | (uint32_t) b->c[2] << 8
8014                    | (uint32_t) b->c[3]);
8015   if (aval < bval)
8016     return -1;
8017   else if (aval > bval)
8018     return 1;
8019   return 0;
8020 }
8021
8022 #ifdef BFD_HOST_64_BIT
8023 static int
8024 cmp_ext64l_r_offset (const void *p, const void *q)
8025 {
8026   union aligned64
8027   {
8028     uint64_t v;
8029     unsigned char c[8];
8030   };
8031   const union aligned64 *a
8032     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8033   const union aligned64 *b
8034     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8035
8036   uint64_t aval = (  (uint64_t) a->c[0]
8037                    | (uint64_t) a->c[1] << 8
8038                    | (uint64_t) a->c[2] << 16
8039                    | (uint64_t) a->c[3] << 24
8040                    | (uint64_t) a->c[4] << 32
8041                    | (uint64_t) a->c[5] << 40
8042                    | (uint64_t) a->c[6] << 48
8043                    | (uint64_t) a->c[7] << 56);
8044   uint64_t bval = (  (uint64_t) b->c[0]
8045                    | (uint64_t) b->c[1] << 8
8046                    | (uint64_t) b->c[2] << 16
8047                    | (uint64_t) b->c[3] << 24
8048                    | (uint64_t) b->c[4] << 32
8049                    | (uint64_t) b->c[5] << 40
8050                    | (uint64_t) b->c[6] << 48
8051                    | (uint64_t) b->c[7] << 56);
8052   if (aval < bval)
8053     return -1;
8054   else if (aval > bval)
8055     return 1;
8056   return 0;
8057 }
8058
8059 static int
8060 cmp_ext64b_r_offset (const void *p, const void *q)
8061 {
8062   union aligned64
8063   {
8064     uint64_t v;
8065     unsigned char c[8];
8066   };
8067   const union aligned64 *a
8068     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8069   const union aligned64 *b
8070     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8071
8072   uint64_t aval = (  (uint64_t) a->c[0] << 56
8073                    | (uint64_t) a->c[1] << 48
8074                    | (uint64_t) a->c[2] << 40
8075                    | (uint64_t) a->c[3] << 32
8076                    | (uint64_t) a->c[4] << 24
8077                    | (uint64_t) a->c[5] << 16
8078                    | (uint64_t) a->c[6] << 8
8079                    | (uint64_t) a->c[7]);
8080   uint64_t bval = (  (uint64_t) b->c[0] << 56
8081                    | (uint64_t) b->c[1] << 48
8082                    | (uint64_t) b->c[2] << 40
8083                    | (uint64_t) b->c[3] << 32
8084                    | (uint64_t) b->c[4] << 24
8085                    | (uint64_t) b->c[5] << 16
8086                    | (uint64_t) b->c[6] << 8
8087                    | (uint64_t) b->c[7]);
8088   if (aval < bval)
8089     return -1;
8090   else if (aval > bval)
8091     return 1;
8092   return 0;
8093 }
8094 #endif
8095
8096 /* When performing a relocatable link, the input relocations are
8097    preserved.  But, if they reference global symbols, the indices
8098    referenced must be updated.  Update all the relocations found in
8099    RELDATA.  */
8100
8101 static void
8102 elf_link_adjust_relocs (bfd *abfd,
8103                         struct bfd_elf_section_reloc_data *reldata,
8104                         bfd_boolean sort)
8105 {
8106   unsigned int i;
8107   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8108   bfd_byte *erela;
8109   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8110   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8111   bfd_vma r_type_mask;
8112   int r_sym_shift;
8113   unsigned int count = reldata->count;
8114   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8115
8116   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8117     {
8118       swap_in = bed->s->swap_reloc_in;
8119       swap_out = bed->s->swap_reloc_out;
8120     }
8121   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8122     {
8123       swap_in = bed->s->swap_reloca_in;
8124       swap_out = bed->s->swap_reloca_out;
8125     }
8126   else
8127     abort ();
8128
8129   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8130     abort ();
8131
8132   if (bed->s->arch_size == 32)
8133     {
8134       r_type_mask = 0xff;
8135       r_sym_shift = 8;
8136     }
8137   else
8138     {
8139       r_type_mask = 0xffffffff;
8140       r_sym_shift = 32;
8141     }
8142
8143   erela = reldata->hdr->contents;
8144   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8145     {
8146       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8147       unsigned int j;
8148
8149       if (*rel_hash == NULL)
8150         continue;
8151
8152       BFD_ASSERT ((*rel_hash)->indx >= 0);
8153
8154       (*swap_in) (abfd, erela, irela);
8155       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8156         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8157                            | (irela[j].r_info & r_type_mask));
8158       (*swap_out) (abfd, irela, erela);
8159     }
8160
8161   if (sort)
8162     {
8163       int (*compare) (const void *, const void *);
8164
8165       if (bed->s->arch_size == 32)
8166         {
8167           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8168             compare = cmp_ext32l_r_offset;
8169           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8170             compare = cmp_ext32b_r_offset;
8171           else
8172             abort ();
8173         }
8174       else
8175         {
8176 #ifdef BFD_HOST_64_BIT
8177           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8178             compare = cmp_ext64l_r_offset;
8179           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8180             compare = cmp_ext64b_r_offset;
8181           else
8182 #endif
8183             abort ();
8184         }
8185       qsort (reldata->hdr->contents, count, reldata->hdr->sh_entsize, compare);
8186       free (reldata->hashes);
8187       reldata->hashes = NULL;
8188     }
8189 }
8190
8191 struct elf_link_sort_rela
8192 {
8193   union {
8194     bfd_vma offset;
8195     bfd_vma sym_mask;
8196   } u;
8197   enum elf_reloc_type_class type;
8198   /* We use this as an array of size int_rels_per_ext_rel.  */
8199   Elf_Internal_Rela rela[1];
8200 };
8201
8202 static int
8203 elf_link_sort_cmp1 (const void *A, const void *B)
8204 {
8205   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8206   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8207   int relativea, relativeb;
8208
8209   relativea = a->type == reloc_class_relative;
8210   relativeb = b->type == reloc_class_relative;
8211
8212   if (relativea < relativeb)
8213     return 1;
8214   if (relativea > relativeb)
8215     return -1;
8216   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8217     return -1;
8218   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8219     return 1;
8220   if (a->rela->r_offset < b->rela->r_offset)
8221     return -1;
8222   if (a->rela->r_offset > b->rela->r_offset)
8223     return 1;
8224   return 0;
8225 }
8226
8227 static int
8228 elf_link_sort_cmp2 (const void *A, const void *B)
8229 {
8230   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8231   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8232
8233   if (a->type < b->type)
8234     return -1;
8235   if (a->type > b->type)
8236     return 1;
8237   if (a->u.offset < b->u.offset)
8238     return -1;
8239   if (a->u.offset > b->u.offset)
8240     return 1;
8241   if (a->rela->r_offset < b->rela->r_offset)
8242     return -1;
8243   if (a->rela->r_offset > b->rela->r_offset)
8244     return 1;
8245   return 0;
8246 }
8247
8248 static size_t
8249 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8250 {
8251   asection *dynamic_relocs;
8252   asection *rela_dyn;
8253   asection *rel_dyn;
8254   bfd_size_type count, size;
8255   size_t i, ret, sort_elt, ext_size;
8256   bfd_byte *sort, *s_non_relative, *p;
8257   struct elf_link_sort_rela *sq;
8258   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8259   int i2e = bed->s->int_rels_per_ext_rel;
8260   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8261   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8262   struct bfd_link_order *lo;
8263   bfd_vma r_sym_mask;
8264   bfd_boolean use_rela;
8265
8266   /* Find a dynamic reloc section.  */
8267   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8268   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8269   if (rela_dyn != NULL && rela_dyn->size > 0
8270       && rel_dyn != NULL && rel_dyn->size > 0)
8271     {
8272       bfd_boolean use_rela_initialised = FALSE;
8273
8274       /* This is just here to stop gcc from complaining.
8275          It's initialization checking code is not perfect.  */
8276       use_rela = TRUE;
8277
8278       /* Both sections are present.  Examine the sizes
8279          of the indirect sections to help us choose.  */
8280       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8281         if (lo->type == bfd_indirect_link_order)
8282           {
8283             asection *o = lo->u.indirect.section;
8284
8285             if ((o->size % bed->s->sizeof_rela) == 0)
8286               {
8287                 if ((o->size % bed->s->sizeof_rel) == 0)
8288                   /* Section size is divisible by both rel and rela sizes.
8289                      It is of no help to us.  */
8290                   ;
8291                 else
8292                   {
8293                     /* Section size is only divisible by rela.  */
8294                     if (use_rela_initialised && (use_rela == FALSE))
8295                       {
8296                         _bfd_error_handler
8297                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8298                         bfd_set_error (bfd_error_invalid_operation);
8299                         return 0;
8300                       }
8301                     else
8302                       {
8303                         use_rela = TRUE;
8304                         use_rela_initialised = TRUE;
8305                       }
8306                   }
8307               }
8308             else if ((o->size % bed->s->sizeof_rel) == 0)
8309               {
8310                 /* Section size is only divisible by rel.  */
8311                 if (use_rela_initialised && (use_rela == TRUE))
8312                   {
8313                     _bfd_error_handler
8314                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8315                     bfd_set_error (bfd_error_invalid_operation);
8316                     return 0;
8317                   }
8318                 else
8319                   {
8320                     use_rela = FALSE;
8321                     use_rela_initialised = TRUE;
8322                   }
8323               }
8324             else
8325               {
8326                 /* The section size is not divisible by either - something is wrong.  */
8327                 _bfd_error_handler
8328                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8329                 bfd_set_error (bfd_error_invalid_operation);
8330                 return 0;
8331               }
8332           }
8333
8334       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8335         if (lo->type == bfd_indirect_link_order)
8336           {
8337             asection *o = lo->u.indirect.section;
8338
8339             if ((o->size % bed->s->sizeof_rela) == 0)
8340               {
8341                 if ((o->size % bed->s->sizeof_rel) == 0)
8342                   /* Section size is divisible by both rel and rela sizes.
8343                      It is of no help to us.  */
8344                   ;
8345                 else
8346                   {
8347                     /* Section size is only divisible by rela.  */
8348                     if (use_rela_initialised && (use_rela == FALSE))
8349                       {
8350                         _bfd_error_handler
8351                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8352                         bfd_set_error (bfd_error_invalid_operation);
8353                         return 0;
8354                       }
8355                     else
8356                       {
8357                         use_rela = TRUE;
8358                         use_rela_initialised = TRUE;
8359                       }
8360                   }
8361               }
8362             else if ((o->size % bed->s->sizeof_rel) == 0)
8363               {
8364                 /* Section size is only divisible by rel.  */
8365                 if (use_rela_initialised && (use_rela == TRUE))
8366                   {
8367                     _bfd_error_handler
8368                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8369                     bfd_set_error (bfd_error_invalid_operation);
8370                     return 0;
8371                   }
8372                 else
8373                   {
8374                     use_rela = FALSE;
8375                     use_rela_initialised = TRUE;
8376                   }
8377               }
8378             else
8379               {
8380                 /* The section size is not divisible by either - something is wrong.  */
8381                 _bfd_error_handler
8382                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8383                 bfd_set_error (bfd_error_invalid_operation);
8384                 return 0;
8385               }
8386           }
8387
8388       if (! use_rela_initialised)
8389         /* Make a guess.  */
8390         use_rela = TRUE;
8391     }
8392   else if (rela_dyn != NULL && rela_dyn->size > 0)
8393     use_rela = TRUE;
8394   else if (rel_dyn != NULL && rel_dyn->size > 0)
8395     use_rela = FALSE;
8396   else
8397     return 0;
8398
8399   if (use_rela)
8400     {
8401       dynamic_relocs = rela_dyn;
8402       ext_size = bed->s->sizeof_rela;
8403       swap_in = bed->s->swap_reloca_in;
8404       swap_out = bed->s->swap_reloca_out;
8405     }
8406   else
8407     {
8408       dynamic_relocs = rel_dyn;
8409       ext_size = bed->s->sizeof_rel;
8410       swap_in = bed->s->swap_reloc_in;
8411       swap_out = bed->s->swap_reloc_out;
8412     }
8413
8414   size = 0;
8415   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8416     if (lo->type == bfd_indirect_link_order)
8417       size += lo->u.indirect.section->size;
8418
8419   if (size != dynamic_relocs->size)
8420     return 0;
8421
8422   sort_elt = (sizeof (struct elf_link_sort_rela)
8423               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8424
8425   count = dynamic_relocs->size / ext_size;
8426   if (count == 0)
8427     return 0;
8428   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8429
8430   if (sort == NULL)
8431     {
8432       (*info->callbacks->warning)
8433         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8434       return 0;
8435     }
8436
8437   if (bed->s->arch_size == 32)
8438     r_sym_mask = ~(bfd_vma) 0xff;
8439   else
8440     r_sym_mask = ~(bfd_vma) 0xffffffff;
8441
8442   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8443     if (lo->type == bfd_indirect_link_order)
8444       {
8445         bfd_byte *erel, *erelend;
8446         asection *o = lo->u.indirect.section;
8447
8448         if (o->contents == NULL && o->size != 0)
8449           {
8450             /* This is a reloc section that is being handled as a normal
8451                section.  See bfd_section_from_shdr.  We can't combine
8452                relocs in this case.  */
8453             free (sort);
8454             return 0;
8455           }
8456         erel = o->contents;
8457         erelend = o->contents + o->size;
8458         /* FIXME: octets_per_byte.  */
8459         p = sort + o->output_offset / ext_size * sort_elt;
8460
8461         while (erel < erelend)
8462           {
8463             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8464
8465             (*swap_in) (abfd, erel, s->rela);
8466             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8467             s->u.sym_mask = r_sym_mask;
8468             p += sort_elt;
8469             erel += ext_size;
8470           }
8471       }
8472
8473   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8474
8475   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8476     {
8477       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8478       if (s->type != reloc_class_relative)
8479         break;
8480     }
8481   ret = i;
8482   s_non_relative = p;
8483
8484   sq = (struct elf_link_sort_rela *) s_non_relative;
8485   for (; i < count; i++, p += sort_elt)
8486     {
8487       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8488       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8489         sq = sp;
8490       sp->u.offset = sq->rela->r_offset;
8491     }
8492
8493   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8494
8495   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8496     if (lo->type == bfd_indirect_link_order)
8497       {
8498         bfd_byte *erel, *erelend;
8499         asection *o = lo->u.indirect.section;
8500
8501         erel = o->contents;
8502         erelend = o->contents + o->size;
8503         /* FIXME: octets_per_byte.  */
8504         p = sort + o->output_offset / ext_size * sort_elt;
8505         while (erel < erelend)
8506           {
8507             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8508             (*swap_out) (abfd, s->rela, erel);
8509             p += sort_elt;
8510             erel += ext_size;
8511           }
8512       }
8513
8514   free (sort);
8515   *psec = dynamic_relocs;
8516   return ret;
8517 }
8518
8519 /* Flush the output symbols to the file.  */
8520
8521 static bfd_boolean
8522 elf_link_flush_output_syms (struct elf_final_link_info *flinfo,
8523                             const struct elf_backend_data *bed)
8524 {
8525   if (flinfo->symbuf_count > 0)
8526     {
8527       Elf_Internal_Shdr *hdr;
8528       file_ptr pos;
8529       bfd_size_type amt;
8530
8531       hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8532       pos = hdr->sh_offset + hdr->sh_size;
8533       amt = flinfo->symbuf_count * bed->s->sizeof_sym;
8534       if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) != 0
8535           || bfd_bwrite (flinfo->symbuf, amt, flinfo->output_bfd) != amt)
8536         return FALSE;
8537
8538       hdr->sh_size += amt;
8539       flinfo->symbuf_count = 0;
8540     }
8541
8542   return TRUE;
8543 }
8544
8545 /* Add a symbol to the output symbol table.  */
8546
8547 static int
8548 elf_link_output_sym (struct elf_final_link_info *flinfo,
8549                      const char *name,
8550                      Elf_Internal_Sym *elfsym,
8551                      asection *input_sec,
8552                      struct elf_link_hash_entry *h)
8553 {
8554   bfd_byte *dest;
8555   Elf_External_Sym_Shndx *destshndx;
8556   int (*output_symbol_hook)
8557     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8558      struct elf_link_hash_entry *);
8559   const struct elf_backend_data *bed;
8560
8561   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8562
8563   bed = get_elf_backend_data (flinfo->output_bfd);
8564   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8565   if (output_symbol_hook != NULL)
8566     {
8567       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8568       if (ret != 1)
8569         return ret;
8570     }
8571
8572   if (name == NULL || *name == '\0')
8573     elfsym->st_name = 0;
8574   else if (input_sec->flags & SEC_EXCLUDE)
8575     elfsym->st_name = 0;
8576   else
8577     {
8578       elfsym->st_name = (unsigned long) _bfd_stringtab_add (flinfo->symstrtab,
8579                                                             name, TRUE, FALSE);
8580       if (elfsym->st_name == (unsigned long) -1)
8581         return 0;
8582     }
8583
8584   if (flinfo->symbuf_count >= flinfo->symbuf_size)
8585     {
8586       if (! elf_link_flush_output_syms (flinfo, bed))
8587         return 0;
8588     }
8589
8590   dest = flinfo->symbuf + flinfo->symbuf_count * bed->s->sizeof_sym;
8591   destshndx = flinfo->symshndxbuf;
8592   if (destshndx != NULL)
8593     {
8594       if (bfd_get_symcount (flinfo->output_bfd) >= flinfo->shndxbuf_size)
8595         {
8596           bfd_size_type amt;
8597
8598           amt = flinfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
8599           destshndx = (Elf_External_Sym_Shndx *) bfd_realloc (destshndx,
8600                                                               amt * 2);
8601           if (destshndx == NULL)
8602             return 0;
8603           flinfo->symshndxbuf = destshndx;
8604           memset ((char *) destshndx + amt, 0, amt);
8605           flinfo->shndxbuf_size *= 2;
8606         }
8607       destshndx += bfd_get_symcount (flinfo->output_bfd);
8608     }
8609
8610   bed->s->swap_symbol_out (flinfo->output_bfd, elfsym, dest, destshndx);
8611   flinfo->symbuf_count += 1;
8612   bfd_get_symcount (flinfo->output_bfd) += 1;
8613
8614   return 1;
8615 }
8616
8617 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8618
8619 static bfd_boolean
8620 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8621 {
8622   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8623       && sym->st_shndx < SHN_LORESERVE)
8624     {
8625       /* The gABI doesn't support dynamic symbols in output sections
8626          beyond 64k.  */
8627       (*_bfd_error_handler)
8628         (_("%B: Too many sections: %d (>= %d)"),
8629          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8630       bfd_set_error (bfd_error_nonrepresentable_section);
8631       return FALSE;
8632     }
8633   return TRUE;
8634 }
8635
8636 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8637    allowing an unsatisfied unversioned symbol in the DSO to match a
8638    versioned symbol that would normally require an explicit version.
8639    We also handle the case that a DSO references a hidden symbol
8640    which may be satisfied by a versioned symbol in another DSO.  */
8641
8642 static bfd_boolean
8643 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8644                                  const struct elf_backend_data *bed,
8645                                  struct elf_link_hash_entry *h)
8646 {
8647   bfd *abfd;
8648   struct elf_link_loaded_list *loaded;
8649
8650   if (!is_elf_hash_table (info->hash))
8651     return FALSE;
8652
8653   /* Check indirect symbol.  */
8654   while (h->root.type == bfd_link_hash_indirect)
8655     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8656
8657   switch (h->root.type)
8658     {
8659     default:
8660       abfd = NULL;
8661       break;
8662
8663     case bfd_link_hash_undefined:
8664     case bfd_link_hash_undefweak:
8665       abfd = h->root.u.undef.abfd;
8666       if ((abfd->flags & DYNAMIC) == 0
8667           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8668         return FALSE;
8669       break;
8670
8671     case bfd_link_hash_defined:
8672     case bfd_link_hash_defweak:
8673       abfd = h->root.u.def.section->owner;
8674       break;
8675
8676     case bfd_link_hash_common:
8677       abfd = h->root.u.c.p->section->owner;
8678       break;
8679     }
8680   BFD_ASSERT (abfd != NULL);
8681
8682   for (loaded = elf_hash_table (info)->loaded;
8683        loaded != NULL;
8684        loaded = loaded->next)
8685     {
8686       bfd *input;
8687       Elf_Internal_Shdr *hdr;
8688       bfd_size_type symcount;
8689       bfd_size_type extsymcount;
8690       bfd_size_type extsymoff;
8691       Elf_Internal_Shdr *versymhdr;
8692       Elf_Internal_Sym *isym;
8693       Elf_Internal_Sym *isymend;
8694       Elf_Internal_Sym *isymbuf;
8695       Elf_External_Versym *ever;
8696       Elf_External_Versym *extversym;
8697
8698       input = loaded->abfd;
8699
8700       /* We check each DSO for a possible hidden versioned definition.  */
8701       if (input == abfd
8702           || (input->flags & DYNAMIC) == 0
8703           || elf_dynversym (input) == 0)
8704         continue;
8705
8706       hdr = &elf_tdata (input)->dynsymtab_hdr;
8707
8708       symcount = hdr->sh_size / bed->s->sizeof_sym;
8709       if (elf_bad_symtab (input))
8710         {
8711           extsymcount = symcount;
8712           extsymoff = 0;
8713         }
8714       else
8715         {
8716           extsymcount = symcount - hdr->sh_info;
8717           extsymoff = hdr->sh_info;
8718         }
8719
8720       if (extsymcount == 0)
8721         continue;
8722
8723       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8724                                       NULL, NULL, NULL);
8725       if (isymbuf == NULL)
8726         return FALSE;
8727
8728       /* Read in any version definitions.  */
8729       versymhdr = &elf_tdata (input)->dynversym_hdr;
8730       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8731       if (extversym == NULL)
8732         goto error_ret;
8733
8734       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8735           || (bfd_bread (extversym, versymhdr->sh_size, input)
8736               != versymhdr->sh_size))
8737         {
8738           free (extversym);
8739         error_ret:
8740           free (isymbuf);
8741           return FALSE;
8742         }
8743
8744       ever = extversym + extsymoff;
8745       isymend = isymbuf + extsymcount;
8746       for (isym = isymbuf; isym < isymend; isym++, ever++)
8747         {
8748           const char *name;
8749           Elf_Internal_Versym iver;
8750           unsigned short version_index;
8751
8752           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8753               || isym->st_shndx == SHN_UNDEF)
8754             continue;
8755
8756           name = bfd_elf_string_from_elf_section (input,
8757                                                   hdr->sh_link,
8758                                                   isym->st_name);
8759           if (strcmp (name, h->root.root.string) != 0)
8760             continue;
8761
8762           _bfd_elf_swap_versym_in (input, ever, &iver);
8763
8764           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8765               && !(h->def_regular
8766                    && h->forced_local))
8767             {
8768               /* If we have a non-hidden versioned sym, then it should
8769                  have provided a definition for the undefined sym unless
8770                  it is defined in a non-shared object and forced local.
8771                */
8772               abort ();
8773             }
8774
8775           version_index = iver.vs_vers & VERSYM_VERSION;
8776           if (version_index == 1 || version_index == 2)
8777             {
8778               /* This is the base or first version.  We can use it.  */
8779               free (extversym);
8780               free (isymbuf);
8781               return TRUE;
8782             }
8783         }
8784
8785       free (extversym);
8786       free (isymbuf);
8787     }
8788
8789   return FALSE;
8790 }
8791
8792 /* Add an external symbol to the symbol table.  This is called from
8793    the hash table traversal routine.  When generating a shared object,
8794    we go through the symbol table twice.  The first time we output
8795    anything that might have been forced to local scope in a version
8796    script.  The second time we output the symbols that are still
8797    global symbols.  */
8798
8799 static bfd_boolean
8800 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8801 {
8802   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8803   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8804   struct elf_final_link_info *flinfo = eoinfo->flinfo;
8805   bfd_boolean strip;
8806   Elf_Internal_Sym sym;
8807   asection *input_sec;
8808   const struct elf_backend_data *bed;
8809   long indx;
8810   int ret;
8811
8812   if (h->root.type == bfd_link_hash_warning)
8813     {
8814       h = (struct elf_link_hash_entry *) h->root.u.i.link;
8815       if (h->root.type == bfd_link_hash_new)
8816         return TRUE;
8817     }
8818
8819   /* Decide whether to output this symbol in this pass.  */
8820   if (eoinfo->localsyms)
8821     {
8822       if (!h->forced_local)
8823         return TRUE;
8824       if (eoinfo->second_pass
8825           && !((h->root.type == bfd_link_hash_defined
8826                 || h->root.type == bfd_link_hash_defweak)
8827                && h->root.u.def.section->output_section != NULL))
8828         return TRUE;
8829
8830       if (!eoinfo->file_sym_done
8831           && (eoinfo->second_pass ? eoinfo->flinfo->filesym_count == 1
8832                                   : eoinfo->flinfo->filesym_count > 1))
8833         {
8834           /* Output a FILE symbol so that following locals are not associated
8835              with the wrong input file.  */
8836           memset (&sym, 0, sizeof (sym));
8837           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
8838           sym.st_shndx = SHN_ABS;
8839           if (!elf_link_output_sym (eoinfo->flinfo, NULL, &sym,
8840                                     bfd_und_section_ptr, NULL))
8841             return FALSE;
8842
8843           eoinfo->file_sym_done = TRUE;
8844         }
8845     }
8846   else
8847     {
8848       if (h->forced_local)
8849         return TRUE;
8850     }
8851
8852   bed = get_elf_backend_data (flinfo->output_bfd);
8853
8854   if (h->root.type == bfd_link_hash_undefined)
8855     {
8856       /* If we have an undefined symbol reference here then it must have
8857          come from a shared library that is being linked in.  (Undefined
8858          references in regular files have already been handled unless
8859          they are in unreferenced sections which are removed by garbage
8860          collection).  */
8861       bfd_boolean ignore_undef = FALSE;
8862
8863       /* Some symbols may be special in that the fact that they're
8864          undefined can be safely ignored - let backend determine that.  */
8865       if (bed->elf_backend_ignore_undef_symbol)
8866         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
8867
8868       /* If we are reporting errors for this situation then do so now.  */
8869       if (!ignore_undef
8870           && h->ref_dynamic
8871           && (!h->ref_regular || flinfo->info->gc_sections)
8872           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
8873           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
8874         {
8875           if (!(flinfo->info->callbacks->undefined_symbol
8876                 (flinfo->info, h->root.root.string,
8877                  h->ref_regular ? NULL : h->root.u.undef.abfd,
8878                  NULL, 0,
8879                  (flinfo->info->unresolved_syms_in_shared_libs
8880                   == RM_GENERATE_ERROR))))
8881             {
8882               bfd_set_error (bfd_error_bad_value);
8883               eoinfo->failed = TRUE;
8884               return FALSE;
8885             }
8886         }
8887     }
8888
8889   /* We should also warn if a forced local symbol is referenced from
8890      shared libraries.  */
8891   if (!flinfo->info->relocatable
8892       && flinfo->info->executable
8893       && h->forced_local
8894       && h->ref_dynamic
8895       && h->def_regular
8896       && !h->dynamic_def
8897       && h->ref_dynamic_nonweak
8898       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
8899     {
8900       bfd *def_bfd;
8901       const char *msg;
8902       struct elf_link_hash_entry *hi = h;
8903
8904       /* Check indirect symbol.  */
8905       while (hi->root.type == bfd_link_hash_indirect)
8906         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
8907
8908       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
8909         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
8910       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
8911         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
8912       else
8913         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
8914       def_bfd = flinfo->output_bfd;
8915       if (hi->root.u.def.section != bfd_abs_section_ptr)
8916         def_bfd = hi->root.u.def.section->owner;
8917       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
8918                              h->root.root.string);
8919       bfd_set_error (bfd_error_bad_value);
8920       eoinfo->failed = TRUE;
8921       return FALSE;
8922     }
8923
8924   /* We don't want to output symbols that have never been mentioned by
8925      a regular file, or that we have been told to strip.  However, if
8926      h->indx is set to -2, the symbol is used by a reloc and we must
8927      output it.  */
8928   if (h->indx == -2)
8929     strip = FALSE;
8930   else if ((h->def_dynamic
8931             || h->ref_dynamic
8932             || h->root.type == bfd_link_hash_new)
8933            && !h->def_regular
8934            && !h->ref_regular)
8935     strip = TRUE;
8936   else if (flinfo->info->strip == strip_all)
8937     strip = TRUE;
8938   else if (flinfo->info->strip == strip_some
8939            && bfd_hash_lookup (flinfo->info->keep_hash,
8940                                h->root.root.string, FALSE, FALSE) == NULL)
8941     strip = TRUE;
8942   else if ((h->root.type == bfd_link_hash_defined
8943             || h->root.type == bfd_link_hash_defweak)
8944            && ((flinfo->info->strip_discarded
8945                 && discarded_section (h->root.u.def.section))
8946                || (h->root.u.def.section->owner != NULL
8947                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
8948     strip = TRUE;
8949   else if ((h->root.type == bfd_link_hash_undefined
8950             || h->root.type == bfd_link_hash_undefweak)
8951            && h->root.u.undef.abfd != NULL
8952            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
8953     strip = TRUE;
8954   else
8955     strip = FALSE;
8956
8957   /* If we're stripping it, and it's not a dynamic symbol, there's
8958      nothing else to do unless it is a forced local symbol or a
8959      STT_GNU_IFUNC symbol.  */
8960   if (strip
8961       && h->dynindx == -1
8962       && h->type != STT_GNU_IFUNC
8963       && !h->forced_local)
8964     return TRUE;
8965
8966   sym.st_value = 0;
8967   sym.st_size = h->size;
8968   sym.st_other = h->other;
8969   if (h->forced_local)
8970     {
8971       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
8972       /* Turn off visibility on local symbol.  */
8973       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
8974     }
8975   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
8976   else if (h->unique_global && h->def_regular)
8977     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
8978   else if (h->root.type == bfd_link_hash_undefweak
8979            || h->root.type == bfd_link_hash_defweak)
8980     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
8981   else
8982     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
8983   sym.st_target_internal = h->target_internal;
8984
8985   switch (h->root.type)
8986     {
8987     default:
8988     case bfd_link_hash_new:
8989     case bfd_link_hash_warning:
8990       abort ();
8991       return FALSE;
8992
8993     case bfd_link_hash_undefined:
8994     case bfd_link_hash_undefweak:
8995       input_sec = bfd_und_section_ptr;
8996       sym.st_shndx = SHN_UNDEF;
8997       break;
8998
8999     case bfd_link_hash_defined:
9000     case bfd_link_hash_defweak:
9001       {
9002         input_sec = h->root.u.def.section;
9003         if (input_sec->output_section != NULL)
9004           {
9005             if (eoinfo->localsyms && flinfo->filesym_count == 1)
9006               {
9007                 bfd_boolean second_pass_sym
9008                   = (input_sec->owner == flinfo->output_bfd
9009                      || input_sec->owner == NULL
9010                      || (input_sec->flags & SEC_LINKER_CREATED) != 0
9011                      || (input_sec->owner->flags & BFD_LINKER_CREATED) != 0);
9012
9013                 eoinfo->need_second_pass |= second_pass_sym;
9014                 if (eoinfo->second_pass != second_pass_sym)
9015                   return TRUE;
9016               }
9017
9018             sym.st_shndx =
9019               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9020                                                  input_sec->output_section);
9021             if (sym.st_shndx == SHN_BAD)
9022               {
9023                 (*_bfd_error_handler)
9024                   (_("%B: could not find output section %A for input section %A"),
9025                    flinfo->output_bfd, input_sec->output_section, input_sec);
9026                 bfd_set_error (bfd_error_nonrepresentable_section);
9027                 eoinfo->failed = TRUE;
9028                 return FALSE;
9029               }
9030
9031             /* ELF symbols in relocatable files are section relative,
9032                but in nonrelocatable files they are virtual
9033                addresses.  */
9034             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9035             if (!flinfo->info->relocatable)
9036               {
9037                 sym.st_value += input_sec->output_section->vma;
9038                 if (h->type == STT_TLS)
9039                   {
9040                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9041                     if (tls_sec != NULL)
9042                       sym.st_value -= tls_sec->vma;
9043                   }
9044               }
9045           }
9046         else
9047           {
9048             BFD_ASSERT (input_sec->owner == NULL
9049                         || (input_sec->owner->flags & DYNAMIC) != 0);
9050             sym.st_shndx = SHN_UNDEF;
9051             input_sec = bfd_und_section_ptr;
9052           }
9053       }
9054       break;
9055
9056     case bfd_link_hash_common:
9057       input_sec = h->root.u.c.p->section;
9058       sym.st_shndx = bed->common_section_index (input_sec);
9059       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9060       break;
9061
9062     case bfd_link_hash_indirect:
9063       /* These symbols are created by symbol versioning.  They point
9064          to the decorated version of the name.  For example, if the
9065          symbol foo@@GNU_1.2 is the default, which should be used when
9066          foo is used with no version, then we add an indirect symbol
9067          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9068          since the indirected symbol is already in the hash table.  */
9069       return TRUE;
9070     }
9071
9072   /* Give the processor backend a chance to tweak the symbol value,
9073      and also to finish up anything that needs to be done for this
9074      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9075      forced local syms when non-shared is due to a historical quirk.
9076      STT_GNU_IFUNC symbol must go through PLT.  */
9077   if ((h->type == STT_GNU_IFUNC
9078        && h->def_regular
9079        && !flinfo->info->relocatable)
9080       || ((h->dynindx != -1
9081            || h->forced_local)
9082           && ((flinfo->info->shared
9083                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9084                    || h->root.type != bfd_link_hash_undefweak))
9085               || !h->forced_local)
9086           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9087     {
9088       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9089              (flinfo->output_bfd, flinfo->info, h, &sym)))
9090         {
9091           eoinfo->failed = TRUE;
9092           return FALSE;
9093         }
9094     }
9095
9096   /* If we are marking the symbol as undefined, and there are no
9097      non-weak references to this symbol from a regular object, then
9098      mark the symbol as weak undefined; if there are non-weak
9099      references, mark the symbol as strong.  We can't do this earlier,
9100      because it might not be marked as undefined until the
9101      finish_dynamic_symbol routine gets through with it.  */
9102   if (sym.st_shndx == SHN_UNDEF
9103       && h->ref_regular
9104       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9105           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9106     {
9107       int bindtype;
9108       unsigned int type = ELF_ST_TYPE (sym.st_info);
9109
9110       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9111       if (type == STT_GNU_IFUNC)
9112         type = STT_FUNC;
9113
9114       if (h->ref_regular_nonweak)
9115         bindtype = STB_GLOBAL;
9116       else
9117         bindtype = STB_WEAK;
9118       sym.st_info = ELF_ST_INFO (bindtype, type);
9119     }
9120
9121   /* If this is a symbol defined in a dynamic library, don't use the
9122      symbol size from the dynamic library.  Relinking an executable
9123      against a new library may introduce gratuitous changes in the
9124      executable's symbols if we keep the size.  */
9125   if (sym.st_shndx == SHN_UNDEF
9126       && !h->def_regular
9127       && h->def_dynamic)
9128     sym.st_size = 0;
9129
9130   /* If a non-weak symbol with non-default visibility is not defined
9131      locally, it is a fatal error.  */
9132   if (!flinfo->info->relocatable
9133       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9134       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9135       && h->root.type == bfd_link_hash_undefined
9136       && !h->def_regular)
9137     {
9138       const char *msg;
9139
9140       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9141         msg = _("%B: protected symbol `%s' isn't defined");
9142       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9143         msg = _("%B: internal symbol `%s' isn't defined");
9144       else
9145         msg = _("%B: hidden symbol `%s' isn't defined");
9146       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9147       bfd_set_error (bfd_error_bad_value);
9148       eoinfo->failed = TRUE;
9149       return FALSE;
9150     }
9151
9152   /* If this symbol should be put in the .dynsym section, then put it
9153      there now.  We already know the symbol index.  We also fill in
9154      the entry in the .hash section.  */
9155   if (flinfo->dynsym_sec != NULL
9156       && h->dynindx != -1
9157       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9158     {
9159       bfd_byte *esym;
9160
9161       /* Since there is no version information in the dynamic string,
9162          if there is no version info in symbol version section, we will
9163          have a run-time problem.  */
9164       if (h->verinfo.verdef == NULL)
9165         {
9166           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9167
9168           if (p && p [1] != '\0')
9169             {
9170               (*_bfd_error_handler)
9171                 (_("%B: No symbol version section for versioned symbol `%s'"),
9172                  flinfo->output_bfd, h->root.root.string);
9173               eoinfo->failed = TRUE;
9174               return FALSE;
9175             }
9176         }
9177
9178       sym.st_name = h->dynstr_index;
9179       esym = flinfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
9180       if (!check_dynsym (flinfo->output_bfd, &sym))
9181         {
9182           eoinfo->failed = TRUE;
9183           return FALSE;
9184         }
9185       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9186
9187       if (flinfo->hash_sec != NULL)
9188         {
9189           size_t hash_entry_size;
9190           bfd_byte *bucketpos;
9191           bfd_vma chain;
9192           size_t bucketcount;
9193           size_t bucket;
9194
9195           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9196           bucket = h->u.elf_hash_value % bucketcount;
9197
9198           hash_entry_size
9199             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9200           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9201                        + (bucket + 2) * hash_entry_size);
9202           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9203           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9204                    bucketpos);
9205           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9206                    ((bfd_byte *) flinfo->hash_sec->contents
9207                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9208         }
9209
9210       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9211         {
9212           Elf_Internal_Versym iversym;
9213           Elf_External_Versym *eversym;
9214
9215           if (!h->def_regular)
9216             {
9217               if (h->verinfo.verdef == NULL
9218                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9219                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9220                 iversym.vs_vers = 0;
9221               else
9222                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9223             }
9224           else
9225             {
9226               if (h->verinfo.vertree == NULL)
9227                 iversym.vs_vers = 1;
9228               else
9229                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9230               if (flinfo->info->create_default_symver)
9231                 iversym.vs_vers++;
9232             }
9233
9234           if (h->hidden)
9235             iversym.vs_vers |= VERSYM_HIDDEN;
9236
9237           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9238           eversym += h->dynindx;
9239           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9240         }
9241     }
9242
9243   /* If we're stripping it, then it was just a dynamic symbol, and
9244      there's nothing else to do.  */
9245   if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
9246     return TRUE;
9247
9248   indx = bfd_get_symcount (flinfo->output_bfd);
9249   ret = elf_link_output_sym (flinfo, h->root.root.string, &sym, input_sec, h);
9250   if (ret == 0)
9251     {
9252       eoinfo->failed = TRUE;
9253       return FALSE;
9254     }
9255   else if (ret == 1)
9256     h->indx = indx;
9257   else if (h->indx == -2)
9258     abort();
9259
9260   return TRUE;
9261 }
9262
9263 /* Return TRUE if special handling is done for relocs in SEC against
9264    symbols defined in discarded sections.  */
9265
9266 static bfd_boolean
9267 elf_section_ignore_discarded_relocs (asection *sec)
9268 {
9269   const struct elf_backend_data *bed;
9270
9271   switch (sec->sec_info_type)
9272     {
9273     case SEC_INFO_TYPE_STABS:
9274     case SEC_INFO_TYPE_EH_FRAME:
9275       return TRUE;
9276     default:
9277       break;
9278     }
9279
9280   bed = get_elf_backend_data (sec->owner);
9281   if (bed->elf_backend_ignore_discarded_relocs != NULL
9282       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9283     return TRUE;
9284
9285   return FALSE;
9286 }
9287
9288 /* Return a mask saying how ld should treat relocations in SEC against
9289    symbols defined in discarded sections.  If this function returns
9290    COMPLAIN set, ld will issue a warning message.  If this function
9291    returns PRETEND set, and the discarded section was link-once and the
9292    same size as the kept link-once section, ld will pretend that the
9293    symbol was actually defined in the kept section.  Otherwise ld will
9294    zero the reloc (at least that is the intent, but some cooperation by
9295    the target dependent code is needed, particularly for REL targets).  */
9296
9297 unsigned int
9298 _bfd_elf_default_action_discarded (asection *sec)
9299 {
9300   if (sec->flags & SEC_DEBUGGING)
9301     return PRETEND;
9302
9303   if (strcmp (".eh_frame", sec->name) == 0)
9304     return 0;
9305
9306   if (strcmp (".gcc_except_table", sec->name) == 0)
9307     return 0;
9308
9309   return COMPLAIN | PRETEND;
9310 }
9311
9312 /* Find a match between a section and a member of a section group.  */
9313
9314 static asection *
9315 match_group_member (asection *sec, asection *group,
9316                     struct bfd_link_info *info)
9317 {
9318   asection *first = elf_next_in_group (group);
9319   asection *s = first;
9320
9321   while (s != NULL)
9322     {
9323       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9324         return s;
9325
9326       s = elf_next_in_group (s);
9327       if (s == first)
9328         break;
9329     }
9330
9331   return NULL;
9332 }
9333
9334 /* Check if the kept section of a discarded section SEC can be used
9335    to replace it.  Return the replacement if it is OK.  Otherwise return
9336    NULL.  */
9337
9338 asection *
9339 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9340 {
9341   asection *kept;
9342
9343   kept = sec->kept_section;
9344   if (kept != NULL)
9345     {
9346       if ((kept->flags & SEC_GROUP) != 0)
9347         kept = match_group_member (sec, kept, info);
9348       if (kept != NULL
9349           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9350               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9351         kept = NULL;
9352       sec->kept_section = kept;
9353     }
9354   return kept;
9355 }
9356
9357 /* Link an input file into the linker output file.  This function
9358    handles all the sections and relocations of the input file at once.
9359    This is so that we only have to read the local symbols once, and
9360    don't have to keep them in memory.  */
9361
9362 static bfd_boolean
9363 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9364 {
9365   int (*relocate_section)
9366     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9367      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9368   bfd *output_bfd;
9369   Elf_Internal_Shdr *symtab_hdr;
9370   size_t locsymcount;
9371   size_t extsymoff;
9372   Elf_Internal_Sym *isymbuf;
9373   Elf_Internal_Sym *isym;
9374   Elf_Internal_Sym *isymend;
9375   long *pindex;
9376   asection **ppsection;
9377   asection *o;
9378   const struct elf_backend_data *bed;
9379   struct elf_link_hash_entry **sym_hashes;
9380   bfd_size_type address_size;
9381   bfd_vma r_type_mask;
9382   int r_sym_shift;
9383   bfd_boolean have_file_sym = FALSE;
9384
9385   output_bfd = flinfo->output_bfd;
9386   bed = get_elf_backend_data (output_bfd);
9387   relocate_section = bed->elf_backend_relocate_section;
9388
9389   /* If this is a dynamic object, we don't want to do anything here:
9390      we don't want the local symbols, and we don't want the section
9391      contents.  */
9392   if ((input_bfd->flags & DYNAMIC) != 0)
9393     return TRUE;
9394
9395   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9396   if (elf_bad_symtab (input_bfd))
9397     {
9398       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9399       extsymoff = 0;
9400     }
9401   else
9402     {
9403       locsymcount = symtab_hdr->sh_info;
9404       extsymoff = symtab_hdr->sh_info;
9405     }
9406
9407   /* Read the local symbols.  */
9408   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9409   if (isymbuf == NULL && locsymcount != 0)
9410     {
9411       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9412                                       flinfo->internal_syms,
9413                                       flinfo->external_syms,
9414                                       flinfo->locsym_shndx);
9415       if (isymbuf == NULL)
9416         return FALSE;
9417     }
9418
9419   /* Find local symbol sections and adjust values of symbols in
9420      SEC_MERGE sections.  Write out those local symbols we know are
9421      going into the output file.  */
9422   isymend = isymbuf + locsymcount;
9423   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9424        isym < isymend;
9425        isym++, pindex++, ppsection++)
9426     {
9427       asection *isec;
9428       const char *name;
9429       Elf_Internal_Sym osym;
9430       long indx;
9431       int ret;
9432
9433       *pindex = -1;
9434
9435       if (elf_bad_symtab (input_bfd))
9436         {
9437           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9438             {
9439               *ppsection = NULL;
9440               continue;
9441             }
9442         }
9443
9444       if (isym->st_shndx == SHN_UNDEF)
9445         isec = bfd_und_section_ptr;
9446       else if (isym->st_shndx == SHN_ABS)
9447         isec = bfd_abs_section_ptr;
9448       else if (isym->st_shndx == SHN_COMMON)
9449         isec = bfd_com_section_ptr;
9450       else
9451         {
9452           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9453           if (isec == NULL)
9454             {
9455               /* Don't attempt to output symbols with st_shnx in the
9456                  reserved range other than SHN_ABS and SHN_COMMON.  */
9457               *ppsection = NULL;
9458               continue;
9459             }
9460           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9461                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9462             isym->st_value =
9463               _bfd_merged_section_offset (output_bfd, &isec,
9464                                           elf_section_data (isec)->sec_info,
9465                                           isym->st_value);
9466         }
9467
9468       *ppsection = isec;
9469
9470       /* Don't output the first, undefined, symbol.  */
9471       if (ppsection == flinfo->sections)
9472         continue;
9473
9474       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9475         {
9476           /* We never output section symbols.  Instead, we use the
9477              section symbol of the corresponding section in the output
9478              file.  */
9479           continue;
9480         }
9481
9482       /* If we are stripping all symbols, we don't want to output this
9483          one.  */
9484       if (flinfo->info->strip == strip_all)
9485         continue;
9486
9487       /* If we are discarding all local symbols, we don't want to
9488          output this one.  If we are generating a relocatable output
9489          file, then some of the local symbols may be required by
9490          relocs; we output them below as we discover that they are
9491          needed.  */
9492       if (flinfo->info->discard == discard_all)
9493         continue;
9494
9495       /* If this symbol is defined in a section which we are
9496          discarding, we don't need to keep it.  */
9497       if (isym->st_shndx != SHN_UNDEF
9498           && isym->st_shndx < SHN_LORESERVE
9499           && bfd_section_removed_from_list (output_bfd,
9500                                             isec->output_section))
9501         continue;
9502
9503       /* Get the name of the symbol.  */
9504       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9505                                               isym->st_name);
9506       if (name == NULL)
9507         return FALSE;
9508
9509       /* See if we are discarding symbols with this name.  */
9510       if ((flinfo->info->strip == strip_some
9511            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9512                == NULL))
9513           || (((flinfo->info->discard == discard_sec_merge
9514                 && (isec->flags & SEC_MERGE) && !flinfo->info->relocatable)
9515                || flinfo->info->discard == discard_l)
9516               && bfd_is_local_label_name (input_bfd, name)))
9517         continue;
9518
9519       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9520         {
9521           have_file_sym = TRUE;
9522           flinfo->filesym_count += 1;
9523         }
9524       if (!have_file_sym)
9525         {
9526           /* In the absence of debug info, bfd_find_nearest_line uses
9527              FILE symbols to determine the source file for local
9528              function symbols.  Provide a FILE symbol here if input
9529              files lack such, so that their symbols won't be
9530              associated with a previous input file.  It's not the
9531              source file, but the best we can do.  */
9532           have_file_sym = TRUE;
9533           flinfo->filesym_count += 1;
9534           memset (&osym, 0, sizeof (osym));
9535           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9536           osym.st_shndx = SHN_ABS;
9537           if (!elf_link_output_sym (flinfo, input_bfd->filename, &osym,
9538                                     bfd_abs_section_ptr, NULL))
9539             return FALSE;
9540         }
9541
9542       osym = *isym;
9543
9544       /* Adjust the section index for the output file.  */
9545       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9546                                                          isec->output_section);
9547       if (osym.st_shndx == SHN_BAD)
9548         return FALSE;
9549
9550       /* ELF symbols in relocatable files are section relative, but
9551          in executable files they are virtual addresses.  Note that
9552          this code assumes that all ELF sections have an associated
9553          BFD section with a reasonable value for output_offset; below
9554          we assume that they also have a reasonable value for
9555          output_section.  Any special sections must be set up to meet
9556          these requirements.  */
9557       osym.st_value += isec->output_offset;
9558       if (!flinfo->info->relocatable)
9559         {
9560           osym.st_value += isec->output_section->vma;
9561           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9562             {
9563               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9564               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9565               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9566             }
9567         }
9568
9569       indx = bfd_get_symcount (output_bfd);
9570       ret = elf_link_output_sym (flinfo, name, &osym, isec, NULL);
9571       if (ret == 0)
9572         return FALSE;
9573       else if (ret == 1)
9574         *pindex = indx;
9575     }
9576
9577   if (bed->s->arch_size == 32)
9578     {
9579       r_type_mask = 0xff;
9580       r_sym_shift = 8;
9581       address_size = 4;
9582     }
9583   else
9584     {
9585       r_type_mask = 0xffffffff;
9586       r_sym_shift = 32;
9587       address_size = 8;
9588     }
9589
9590   /* Relocate the contents of each section.  */
9591   sym_hashes = elf_sym_hashes (input_bfd);
9592   for (o = input_bfd->sections; o != NULL; o = o->next)
9593     {
9594       bfd_byte *contents;
9595
9596       if (! o->linker_mark)
9597         {
9598           /* This section was omitted from the link.  */
9599           continue;
9600         }
9601
9602       if (flinfo->info->relocatable
9603           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9604         {
9605           /* Deal with the group signature symbol.  */
9606           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9607           unsigned long symndx = sec_data->this_hdr.sh_info;
9608           asection *osec = o->output_section;
9609
9610           if (symndx >= locsymcount
9611               || (elf_bad_symtab (input_bfd)
9612                   && flinfo->sections[symndx] == NULL))
9613             {
9614               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9615               while (h->root.type == bfd_link_hash_indirect
9616                      || h->root.type == bfd_link_hash_warning)
9617                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9618               /* Arrange for symbol to be output.  */
9619               h->indx = -2;
9620               elf_section_data (osec)->this_hdr.sh_info = -2;
9621             }
9622           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9623             {
9624               /* We'll use the output section target_index.  */
9625               asection *sec = flinfo->sections[symndx]->output_section;
9626               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9627             }
9628           else
9629             {
9630               if (flinfo->indices[symndx] == -1)
9631                 {
9632                   /* Otherwise output the local symbol now.  */
9633                   Elf_Internal_Sym sym = isymbuf[symndx];
9634                   asection *sec = flinfo->sections[symndx]->output_section;
9635                   const char *name;
9636                   long indx;
9637                   int ret;
9638
9639                   name = bfd_elf_string_from_elf_section (input_bfd,
9640                                                           symtab_hdr->sh_link,
9641                                                           sym.st_name);
9642                   if (name == NULL)
9643                     return FALSE;
9644
9645                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9646                                                                     sec);
9647                   if (sym.st_shndx == SHN_BAD)
9648                     return FALSE;
9649
9650                   sym.st_value += o->output_offset;
9651
9652                   indx = bfd_get_symcount (output_bfd);
9653                   ret = elf_link_output_sym (flinfo, name, &sym, o, NULL);
9654                   if (ret == 0)
9655                     return FALSE;
9656                   else if (ret == 1)
9657                     flinfo->indices[symndx] = indx;
9658                   else
9659                     abort ();
9660                 }
9661               elf_section_data (osec)->this_hdr.sh_info
9662                 = flinfo->indices[symndx];
9663             }
9664         }
9665
9666       if ((o->flags & SEC_HAS_CONTENTS) == 0
9667           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9668         continue;
9669
9670       if ((o->flags & SEC_LINKER_CREATED) != 0)
9671         {
9672           /* Section was created by _bfd_elf_link_create_dynamic_sections
9673              or somesuch.  */
9674           continue;
9675         }
9676
9677       /* Get the contents of the section.  They have been cached by a
9678          relaxation routine.  Note that o is a section in an input
9679          file, so the contents field will not have been set by any of
9680          the routines which work on output files.  */
9681       if (elf_section_data (o)->this_hdr.contents != NULL)
9682         {
9683           contents = elf_section_data (o)->this_hdr.contents;
9684           if (bed->caches_rawsize
9685               && o->rawsize != 0
9686               && o->rawsize < o->size)
9687             {
9688               memcpy (flinfo->contents, contents, o->rawsize);
9689               contents = flinfo->contents;
9690             }
9691         }
9692       else
9693         {
9694           contents = flinfo->contents;
9695           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9696             return FALSE;
9697         }
9698
9699       if ((o->flags & SEC_RELOC) != 0)
9700         {
9701           Elf_Internal_Rela *internal_relocs;
9702           Elf_Internal_Rela *rel, *relend;
9703           int action_discarded;
9704           int ret;
9705
9706           /* Get the swapped relocs.  */
9707           internal_relocs
9708             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
9709                                          flinfo->internal_relocs, FALSE);
9710           if (internal_relocs == NULL
9711               && o->reloc_count > 0)
9712             return FALSE;
9713
9714           /* We need to reverse-copy input .ctors/.dtors sections if
9715              they are placed in .init_array/.finit_array for output.  */
9716           if (o->size > address_size
9717               && ((strncmp (o->name, ".ctors", 6) == 0
9718                    && strcmp (o->output_section->name,
9719                               ".init_array") == 0)
9720                   || (strncmp (o->name, ".dtors", 6) == 0
9721                       && strcmp (o->output_section->name,
9722                                  ".fini_array") == 0))
9723               && (o->name[6] == 0 || o->name[6] == '.'))
9724             {
9725               if (o->size != o->reloc_count * address_size)
9726                 {
9727                   (*_bfd_error_handler)
9728                     (_("error: %B: size of section %A is not "
9729                        "multiple of address size"),
9730                      input_bfd, o);
9731                   bfd_set_error (bfd_error_on_input);
9732                   return FALSE;
9733                 }
9734               o->flags |= SEC_ELF_REVERSE_COPY;
9735             }
9736
9737           action_discarded = -1;
9738           if (!elf_section_ignore_discarded_relocs (o))
9739             action_discarded = (*bed->action_discarded) (o);
9740
9741           /* Run through the relocs evaluating complex reloc symbols and
9742              looking for relocs against symbols from discarded sections
9743              or section symbols from removed link-once sections.
9744              Complain about relocs against discarded sections.  Zero
9745              relocs against removed link-once sections.  */
9746
9747           rel = internal_relocs;
9748           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9749           for ( ; rel < relend; rel++)
9750             {
9751               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9752               unsigned int s_type;
9753               asection **ps, *sec;
9754               struct elf_link_hash_entry *h = NULL;
9755               const char *sym_name;
9756
9757               if (r_symndx == STN_UNDEF)
9758                 continue;
9759
9760               if (r_symndx >= locsymcount
9761                   || (elf_bad_symtab (input_bfd)
9762                       && flinfo->sections[r_symndx] == NULL))
9763                 {
9764                   h = sym_hashes[r_symndx - extsymoff];
9765
9766                   /* Badly formatted input files can contain relocs that
9767                      reference non-existant symbols.  Check here so that
9768                      we do not seg fault.  */
9769                   if (h == NULL)
9770                     {
9771                       char buffer [32];
9772
9773                       sprintf_vma (buffer, rel->r_info);
9774                       (*_bfd_error_handler)
9775                         (_("error: %B contains a reloc (0x%s) for section %A "
9776                            "that references a non-existent global symbol"),
9777                          input_bfd, o, buffer);
9778                       bfd_set_error (bfd_error_bad_value);
9779                       return FALSE;
9780                     }
9781
9782                   while (h->root.type == bfd_link_hash_indirect
9783                          || h->root.type == bfd_link_hash_warning)
9784                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9785
9786                   s_type = h->type;
9787
9788                   ps = NULL;
9789                   if (h->root.type == bfd_link_hash_defined
9790                       || h->root.type == bfd_link_hash_defweak)
9791                     ps = &h->root.u.def.section;
9792
9793                   sym_name = h->root.root.string;
9794                 }
9795               else
9796                 {
9797                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
9798
9799                   s_type = ELF_ST_TYPE (sym->st_info);
9800                   ps = &flinfo->sections[r_symndx];
9801                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9802                                                sym, *ps);
9803                 }
9804
9805               if ((s_type == STT_RELC || s_type == STT_SRELC)
9806                   && !flinfo->info->relocatable)
9807                 {
9808                   bfd_vma val;
9809                   bfd_vma dot = (rel->r_offset
9810                                  + o->output_offset + o->output_section->vma);
9811 #ifdef DEBUG
9812                   printf ("Encountered a complex symbol!");
9813                   printf (" (input_bfd %s, section %s, reloc %ld\n",
9814                           input_bfd->filename, o->name,
9815                           (long) (rel - internal_relocs));
9816                   printf (" symbol: idx  %8.8lx, name %s\n",
9817                           r_symndx, sym_name);
9818                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
9819                           (unsigned long) rel->r_info,
9820                           (unsigned long) rel->r_offset);
9821 #endif
9822                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
9823                                     isymbuf, locsymcount, s_type == STT_SRELC))
9824                     return FALSE;
9825
9826                   /* Symbol evaluated OK.  Update to absolute value.  */
9827                   set_symbol_value (input_bfd, isymbuf, locsymcount,
9828                                     r_symndx, val);
9829                   continue;
9830                 }
9831
9832               if (action_discarded != -1 && ps != NULL)
9833                 {
9834                   /* Complain if the definition comes from a
9835                      discarded section.  */
9836                   if ((sec = *ps) != NULL && discarded_section (sec))
9837                     {
9838                       BFD_ASSERT (r_symndx != STN_UNDEF);
9839                       if (action_discarded & COMPLAIN)
9840                         (*flinfo->info->callbacks->einfo)
9841                           (_("%X`%s' referenced in section `%A' of %B: "
9842                              "defined in discarded section `%A' of %B\n"),
9843                            sym_name, o, input_bfd, sec, sec->owner);
9844
9845                       /* Try to do the best we can to support buggy old
9846                          versions of gcc.  Pretend that the symbol is
9847                          really defined in the kept linkonce section.
9848                          FIXME: This is quite broken.  Modifying the
9849                          symbol here means we will be changing all later
9850                          uses of the symbol, not just in this section.  */
9851                       if (action_discarded & PRETEND)
9852                         {
9853                           asection *kept;
9854
9855                           kept = _bfd_elf_check_kept_section (sec,
9856                                                               flinfo->info);
9857                           if (kept != NULL)
9858                             {
9859                               *ps = kept;
9860                               continue;
9861                             }
9862                         }
9863                     }
9864                 }
9865             }
9866
9867           /* Relocate the section by invoking a back end routine.
9868
9869              The back end routine is responsible for adjusting the
9870              section contents as necessary, and (if using Rela relocs
9871              and generating a relocatable output file) adjusting the
9872              reloc addend as necessary.
9873
9874              The back end routine does not have to worry about setting
9875              the reloc address or the reloc symbol index.
9876
9877              The back end routine is given a pointer to the swapped in
9878              internal symbols, and can access the hash table entries
9879              for the external symbols via elf_sym_hashes (input_bfd).
9880
9881              When generating relocatable output, the back end routine
9882              must handle STB_LOCAL/STT_SECTION symbols specially.  The
9883              output symbol is going to be a section symbol
9884              corresponding to the output section, which will require
9885              the addend to be adjusted.  */
9886
9887           ret = (*relocate_section) (output_bfd, flinfo->info,
9888                                      input_bfd, o, contents,
9889                                      internal_relocs,
9890                                      isymbuf,
9891                                      flinfo->sections);
9892           if (!ret)
9893             return FALSE;
9894
9895           if (ret == 2
9896               || flinfo->info->relocatable
9897               || flinfo->info->emitrelocations)
9898             {
9899               Elf_Internal_Rela *irela;
9900               Elf_Internal_Rela *irelaend, *irelamid;
9901               bfd_vma last_offset;
9902               struct elf_link_hash_entry **rel_hash;
9903               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
9904               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
9905               unsigned int next_erel;
9906               bfd_boolean rela_normal;
9907               struct bfd_elf_section_data *esdi, *esdo;
9908
9909               esdi = elf_section_data (o);
9910               esdo = elf_section_data (o->output_section);
9911               rela_normal = FALSE;
9912
9913               /* Adjust the reloc addresses and symbol indices.  */
9914
9915               irela = internal_relocs;
9916               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
9917               rel_hash = esdo->rel.hashes + esdo->rel.count;
9918               /* We start processing the REL relocs, if any.  When we reach
9919                  IRELAMID in the loop, we switch to the RELA relocs.  */
9920               irelamid = irela;
9921               if (esdi->rel.hdr != NULL)
9922                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
9923                              * bed->s->int_rels_per_ext_rel);
9924               rel_hash_list = rel_hash;
9925               rela_hash_list = NULL;
9926               last_offset = o->output_offset;
9927               if (!flinfo->info->relocatable)
9928                 last_offset += o->output_section->vma;
9929               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
9930                 {
9931                   unsigned long r_symndx;
9932                   asection *sec;
9933                   Elf_Internal_Sym sym;
9934
9935                   if (next_erel == bed->s->int_rels_per_ext_rel)
9936                     {
9937                       rel_hash++;
9938                       next_erel = 0;
9939                     }
9940
9941                   if (irela == irelamid)
9942                     {
9943                       rel_hash = esdo->rela.hashes + esdo->rela.count;
9944                       rela_hash_list = rel_hash;
9945                       rela_normal = bed->rela_normal;
9946                     }
9947
9948                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
9949                                                              flinfo->info, o,
9950                                                              irela->r_offset);
9951                   if (irela->r_offset >= (bfd_vma) -2)
9952                     {
9953                       /* This is a reloc for a deleted entry or somesuch.
9954                          Turn it into an R_*_NONE reloc, at the same
9955                          offset as the last reloc.  elf_eh_frame.c and
9956                          bfd_elf_discard_info rely on reloc offsets
9957                          being ordered.  */
9958                       irela->r_offset = last_offset;
9959                       irela->r_info = 0;
9960                       irela->r_addend = 0;
9961                       continue;
9962                     }
9963
9964                   irela->r_offset += o->output_offset;
9965
9966                   /* Relocs in an executable have to be virtual addresses.  */
9967                   if (!flinfo->info->relocatable)
9968                     irela->r_offset += o->output_section->vma;
9969
9970                   last_offset = irela->r_offset;
9971
9972                   r_symndx = irela->r_info >> r_sym_shift;
9973                   if (r_symndx == STN_UNDEF)
9974                     continue;
9975
9976                   if (r_symndx >= locsymcount
9977                       || (elf_bad_symtab (input_bfd)
9978                           && flinfo->sections[r_symndx] == NULL))
9979                     {
9980                       struct elf_link_hash_entry *rh;
9981                       unsigned long indx;
9982
9983                       /* This is a reloc against a global symbol.  We
9984                          have not yet output all the local symbols, so
9985                          we do not know the symbol index of any global
9986                          symbol.  We set the rel_hash entry for this
9987                          reloc to point to the global hash table entry
9988                          for this symbol.  The symbol index is then
9989                          set at the end of bfd_elf_final_link.  */
9990                       indx = r_symndx - extsymoff;
9991                       rh = elf_sym_hashes (input_bfd)[indx];
9992                       while (rh->root.type == bfd_link_hash_indirect
9993                              || rh->root.type == bfd_link_hash_warning)
9994                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
9995
9996                       /* Setting the index to -2 tells
9997                          elf_link_output_extsym that this symbol is
9998                          used by a reloc.  */
9999                       BFD_ASSERT (rh->indx < 0);
10000                       rh->indx = -2;
10001
10002                       *rel_hash = rh;
10003
10004                       continue;
10005                     }
10006
10007                   /* This is a reloc against a local symbol.  */
10008
10009                   *rel_hash = NULL;
10010                   sym = isymbuf[r_symndx];
10011                   sec = flinfo->sections[r_symndx];
10012                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10013                     {
10014                       /* I suppose the backend ought to fill in the
10015                          section of any STT_SECTION symbol against a
10016                          processor specific section.  */
10017                       r_symndx = STN_UNDEF;
10018                       if (bfd_is_abs_section (sec))
10019                         ;
10020                       else if (sec == NULL || sec->owner == NULL)
10021                         {
10022                           bfd_set_error (bfd_error_bad_value);
10023                           return FALSE;
10024                         }
10025                       else
10026                         {
10027                           asection *osec = sec->output_section;
10028
10029                           /* If we have discarded a section, the output
10030                              section will be the absolute section.  In
10031                              case of discarded SEC_MERGE sections, use
10032                              the kept section.  relocate_section should
10033                              have already handled discarded linkonce
10034                              sections.  */
10035                           if (bfd_is_abs_section (osec)
10036                               && sec->kept_section != NULL
10037                               && sec->kept_section->output_section != NULL)
10038                             {
10039                               osec = sec->kept_section->output_section;
10040                               irela->r_addend -= osec->vma;
10041                             }
10042
10043                           if (!bfd_is_abs_section (osec))
10044                             {
10045                               r_symndx = osec->target_index;
10046                               if (r_symndx == STN_UNDEF)
10047                                 {
10048                                   irela->r_addend += osec->vma;
10049                                   osec = _bfd_nearby_section (output_bfd, osec,
10050                                                               osec->vma);
10051                                   irela->r_addend -= osec->vma;
10052                                   r_symndx = osec->target_index;
10053                                 }
10054                             }
10055                         }
10056
10057                       /* Adjust the addend according to where the
10058                          section winds up in the output section.  */
10059                       if (rela_normal)
10060                         irela->r_addend += sec->output_offset;
10061                     }
10062                   else
10063                     {
10064                       if (flinfo->indices[r_symndx] == -1)
10065                         {
10066                           unsigned long shlink;
10067                           const char *name;
10068                           asection *osec;
10069                           long indx;
10070
10071                           if (flinfo->info->strip == strip_all)
10072                             {
10073                               /* You can't do ld -r -s.  */
10074                               bfd_set_error (bfd_error_invalid_operation);
10075                               return FALSE;
10076                             }
10077
10078                           /* This symbol was skipped earlier, but
10079                              since it is needed by a reloc, we
10080                              must output it now.  */
10081                           shlink = symtab_hdr->sh_link;
10082                           name = (bfd_elf_string_from_elf_section
10083                                   (input_bfd, shlink, sym.st_name));
10084                           if (name == NULL)
10085                             return FALSE;
10086
10087                           osec = sec->output_section;
10088                           sym.st_shndx =
10089                             _bfd_elf_section_from_bfd_section (output_bfd,
10090                                                                osec);
10091                           if (sym.st_shndx == SHN_BAD)
10092                             return FALSE;
10093
10094                           sym.st_value += sec->output_offset;
10095                           if (!flinfo->info->relocatable)
10096                             {
10097                               sym.st_value += osec->vma;
10098                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10099                                 {
10100                                   /* STT_TLS symbols are relative to PT_TLS
10101                                      segment base.  */
10102                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10103                                               ->tls_sec != NULL);
10104                                   sym.st_value -= (elf_hash_table (flinfo->info)
10105                                                    ->tls_sec->vma);
10106                                 }
10107                             }
10108
10109                           indx = bfd_get_symcount (output_bfd);
10110                           ret = elf_link_output_sym (flinfo, name, &sym, sec,
10111                                                      NULL);
10112                           if (ret == 0)
10113                             return FALSE;
10114                           else if (ret == 1)
10115                             flinfo->indices[r_symndx] = indx;
10116                           else
10117                             abort ();
10118                         }
10119
10120                       r_symndx = flinfo->indices[r_symndx];
10121                     }
10122
10123                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10124                                    | (irela->r_info & r_type_mask));
10125                 }
10126
10127               /* Swap out the relocs.  */
10128               input_rel_hdr = esdi->rel.hdr;
10129               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10130                 {
10131                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10132                                                      input_rel_hdr,
10133                                                      internal_relocs,
10134                                                      rel_hash_list))
10135                     return FALSE;
10136                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10137                                       * bed->s->int_rels_per_ext_rel);
10138                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10139                 }
10140
10141               input_rela_hdr = esdi->rela.hdr;
10142               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10143                 {
10144                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10145                                                      input_rela_hdr,
10146                                                      internal_relocs,
10147                                                      rela_hash_list))
10148                     return FALSE;
10149                 }
10150             }
10151         }
10152
10153       /* Write out the modified section contents.  */
10154       if (bed->elf_backend_write_section
10155           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10156                                                 contents))
10157         {
10158           /* Section written out.  */
10159         }
10160       else switch (o->sec_info_type)
10161         {
10162         case SEC_INFO_TYPE_STABS:
10163           if (! (_bfd_write_section_stabs
10164                  (output_bfd,
10165                   &elf_hash_table (flinfo->info)->stab_info,
10166                   o, &elf_section_data (o)->sec_info, contents)))
10167             return FALSE;
10168           break;
10169         case SEC_INFO_TYPE_MERGE:
10170           if (! _bfd_write_merged_section (output_bfd, o,
10171                                            elf_section_data (o)->sec_info))
10172             return FALSE;
10173           break;
10174         case SEC_INFO_TYPE_EH_FRAME:
10175           {
10176             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10177                                                    o, contents))
10178               return FALSE;
10179           }
10180           break;
10181         default:
10182           {
10183             /* FIXME: octets_per_byte.  */
10184             if (! (o->flags & SEC_EXCLUDE))
10185               {
10186                 file_ptr offset = (file_ptr) o->output_offset;
10187                 bfd_size_type todo = o->size;
10188                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10189                   {
10190                     /* Reverse-copy input section to output.  */
10191                     do
10192                       {
10193                         todo -= address_size;
10194                         if (! bfd_set_section_contents (output_bfd,
10195                                                         o->output_section,
10196                                                         contents + todo,
10197                                                         offset,
10198                                                         address_size))
10199                           return FALSE;
10200                         if (todo == 0)
10201                           break;
10202                         offset += address_size;
10203                       }
10204                     while (1);
10205                   }
10206                 else if (! bfd_set_section_contents (output_bfd,
10207                                                      o->output_section,
10208                                                      contents,
10209                                                      offset, todo))
10210                   return FALSE;
10211               }
10212           }
10213           break;
10214         }
10215     }
10216
10217   return TRUE;
10218 }
10219
10220 /* Generate a reloc when linking an ELF file.  This is a reloc
10221    requested by the linker, and does not come from any input file.  This
10222    is used to build constructor and destructor tables when linking
10223    with -Ur.  */
10224
10225 static bfd_boolean
10226 elf_reloc_link_order (bfd *output_bfd,
10227                       struct bfd_link_info *info,
10228                       asection *output_section,
10229                       struct bfd_link_order *link_order)
10230 {
10231   reloc_howto_type *howto;
10232   long indx;
10233   bfd_vma offset;
10234   bfd_vma addend;
10235   struct bfd_elf_section_reloc_data *reldata;
10236   struct elf_link_hash_entry **rel_hash_ptr;
10237   Elf_Internal_Shdr *rel_hdr;
10238   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10239   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10240   bfd_byte *erel;
10241   unsigned int i;
10242   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10243
10244   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10245   if (howto == NULL)
10246     {
10247       bfd_set_error (bfd_error_bad_value);
10248       return FALSE;
10249     }
10250
10251   addend = link_order->u.reloc.p->addend;
10252
10253   if (esdo->rel.hdr)
10254     reldata = &esdo->rel;
10255   else if (esdo->rela.hdr)
10256     reldata = &esdo->rela;
10257   else
10258     {
10259       reldata = NULL;
10260       BFD_ASSERT (0);
10261     }
10262
10263   /* Figure out the symbol index.  */
10264   rel_hash_ptr = reldata->hashes + reldata->count;
10265   if (link_order->type == bfd_section_reloc_link_order)
10266     {
10267       indx = link_order->u.reloc.p->u.section->target_index;
10268       BFD_ASSERT (indx != 0);
10269       *rel_hash_ptr = NULL;
10270     }
10271   else
10272     {
10273       struct elf_link_hash_entry *h;
10274
10275       /* Treat a reloc against a defined symbol as though it were
10276          actually against the section.  */
10277       h = ((struct elf_link_hash_entry *)
10278            bfd_wrapped_link_hash_lookup (output_bfd, info,
10279                                          link_order->u.reloc.p->u.name,
10280                                          FALSE, FALSE, TRUE));
10281       if (h != NULL
10282           && (h->root.type == bfd_link_hash_defined
10283               || h->root.type == bfd_link_hash_defweak))
10284         {
10285           asection *section;
10286
10287           section = h->root.u.def.section;
10288           indx = section->output_section->target_index;
10289           *rel_hash_ptr = NULL;
10290           /* It seems that we ought to add the symbol value to the
10291              addend here, but in practice it has already been added
10292              because it was passed to constructor_callback.  */
10293           addend += section->output_section->vma + section->output_offset;
10294         }
10295       else if (h != NULL)
10296         {
10297           /* Setting the index to -2 tells elf_link_output_extsym that
10298              this symbol is used by a reloc.  */
10299           h->indx = -2;
10300           *rel_hash_ptr = h;
10301           indx = 0;
10302         }
10303       else
10304         {
10305           if (! ((*info->callbacks->unattached_reloc)
10306                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10307             return FALSE;
10308           indx = 0;
10309         }
10310     }
10311
10312   /* If this is an inplace reloc, we must write the addend into the
10313      object file.  */
10314   if (howto->partial_inplace && addend != 0)
10315     {
10316       bfd_size_type size;
10317       bfd_reloc_status_type rstat;
10318       bfd_byte *buf;
10319       bfd_boolean ok;
10320       const char *sym_name;
10321
10322       size = (bfd_size_type) bfd_get_reloc_size (howto);
10323       buf = (bfd_byte *) bfd_zmalloc (size);
10324       if (buf == NULL && size != 0)
10325         return FALSE;
10326       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10327       switch (rstat)
10328         {
10329         case bfd_reloc_ok:
10330           break;
10331
10332         default:
10333         case bfd_reloc_outofrange:
10334           abort ();
10335
10336         case bfd_reloc_overflow:
10337           if (link_order->type == bfd_section_reloc_link_order)
10338             sym_name = bfd_section_name (output_bfd,
10339                                          link_order->u.reloc.p->u.section);
10340           else
10341             sym_name = link_order->u.reloc.p->u.name;
10342           if (! ((*info->callbacks->reloc_overflow)
10343                  (info, NULL, sym_name, howto->name, addend, NULL,
10344                   NULL, (bfd_vma) 0)))
10345             {
10346               free (buf);
10347               return FALSE;
10348             }
10349           break;
10350         }
10351       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10352                                      link_order->offset, size);
10353       free (buf);
10354       if (! ok)
10355         return FALSE;
10356     }
10357
10358   /* The address of a reloc is relative to the section in a
10359      relocatable file, and is a virtual address in an executable
10360      file.  */
10361   offset = link_order->offset;
10362   if (! info->relocatable)
10363     offset += output_section->vma;
10364
10365   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10366     {
10367       irel[i].r_offset = offset;
10368       irel[i].r_info = 0;
10369       irel[i].r_addend = 0;
10370     }
10371   if (bed->s->arch_size == 32)
10372     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10373   else
10374     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10375
10376   rel_hdr = reldata->hdr;
10377   erel = rel_hdr->contents;
10378   if (rel_hdr->sh_type == SHT_REL)
10379     {
10380       erel += reldata->count * bed->s->sizeof_rel;
10381       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10382     }
10383   else
10384     {
10385       irel[0].r_addend = addend;
10386       erel += reldata->count * bed->s->sizeof_rela;
10387       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10388     }
10389
10390   ++reldata->count;
10391
10392   return TRUE;
10393 }
10394
10395
10396 /* Get the output vma of the section pointed to by the sh_link field.  */
10397
10398 static bfd_vma
10399 elf_get_linked_section_vma (struct bfd_link_order *p)
10400 {
10401   Elf_Internal_Shdr **elf_shdrp;
10402   asection *s;
10403   int elfsec;
10404
10405   s = p->u.indirect.section;
10406   elf_shdrp = elf_elfsections (s->owner);
10407   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10408   elfsec = elf_shdrp[elfsec]->sh_link;
10409   /* PR 290:
10410      The Intel C compiler generates SHT_IA_64_UNWIND with
10411      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10412      sh_info fields.  Hence we could get the situation
10413      where elfsec is 0.  */
10414   if (elfsec == 0)
10415     {
10416       const struct elf_backend_data *bed
10417         = get_elf_backend_data (s->owner);
10418       if (bed->link_order_error_handler)
10419         bed->link_order_error_handler
10420           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10421       return 0;
10422     }
10423   else
10424     {
10425       s = elf_shdrp[elfsec]->bfd_section;
10426       return s->output_section->vma + s->output_offset;
10427     }
10428 }
10429
10430
10431 /* Compare two sections based on the locations of the sections they are
10432    linked to.  Used by elf_fixup_link_order.  */
10433
10434 static int
10435 compare_link_order (const void * a, const void * b)
10436 {
10437   bfd_vma apos;
10438   bfd_vma bpos;
10439
10440   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10441   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10442   if (apos < bpos)
10443     return -1;
10444   return apos > bpos;
10445 }
10446
10447
10448 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10449    order as their linked sections.  Returns false if this could not be done
10450    because an output section includes both ordered and unordered
10451    sections.  Ideally we'd do this in the linker proper.  */
10452
10453 static bfd_boolean
10454 elf_fixup_link_order (bfd *abfd, asection *o)
10455 {
10456   int seen_linkorder;
10457   int seen_other;
10458   int n;
10459   struct bfd_link_order *p;
10460   bfd *sub;
10461   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10462   unsigned elfsec;
10463   struct bfd_link_order **sections;
10464   asection *s, *other_sec, *linkorder_sec;
10465   bfd_vma offset;
10466
10467   other_sec = NULL;
10468   linkorder_sec = NULL;
10469   seen_other = 0;
10470   seen_linkorder = 0;
10471   for (p = o->map_head.link_order; p != NULL; p = p->next)
10472     {
10473       if (p->type == bfd_indirect_link_order)
10474         {
10475           s = p->u.indirect.section;
10476           sub = s->owner;
10477           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10478               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10479               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10480               && elfsec < elf_numsections (sub)
10481               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10482               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10483             {
10484               seen_linkorder++;
10485               linkorder_sec = s;
10486             }
10487           else
10488             {
10489               seen_other++;
10490               other_sec = s;
10491             }
10492         }
10493       else
10494         seen_other++;
10495
10496       if (seen_other && seen_linkorder)
10497         {
10498           if (other_sec && linkorder_sec)
10499             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10500                                    o, linkorder_sec,
10501                                    linkorder_sec->owner, other_sec,
10502                                    other_sec->owner);
10503           else
10504             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10505                                    o);
10506           bfd_set_error (bfd_error_bad_value);
10507           return FALSE;
10508         }
10509     }
10510
10511   if (!seen_linkorder)
10512     return TRUE;
10513
10514   sections = (struct bfd_link_order **)
10515     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10516   if (sections == NULL)
10517     return FALSE;
10518   seen_linkorder = 0;
10519
10520   for (p = o->map_head.link_order; p != NULL; p = p->next)
10521     {
10522       sections[seen_linkorder++] = p;
10523     }
10524   /* Sort the input sections in the order of their linked section.  */
10525   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10526          compare_link_order);
10527
10528   /* Change the offsets of the sections.  */
10529   offset = 0;
10530   for (n = 0; n < seen_linkorder; n++)
10531     {
10532       s = sections[n]->u.indirect.section;
10533       offset &= ~(bfd_vma) 0 << s->alignment_power;
10534       s->output_offset = offset;
10535       sections[n]->offset = offset;
10536       /* FIXME: octets_per_byte.  */
10537       offset += sections[n]->size;
10538     }
10539
10540   free (sections);
10541   return TRUE;
10542 }
10543
10544 static void
10545 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10546 {
10547   asection *o;
10548
10549   if (flinfo->symstrtab != NULL)
10550     _bfd_stringtab_free (flinfo->symstrtab);
10551   if (flinfo->contents != NULL)
10552     free (flinfo->contents);
10553   if (flinfo->external_relocs != NULL)
10554     free (flinfo->external_relocs);
10555   if (flinfo->internal_relocs != NULL)
10556     free (flinfo->internal_relocs);
10557   if (flinfo->external_syms != NULL)
10558     free (flinfo->external_syms);
10559   if (flinfo->locsym_shndx != NULL)
10560     free (flinfo->locsym_shndx);
10561   if (flinfo->internal_syms != NULL)
10562     free (flinfo->internal_syms);
10563   if (flinfo->indices != NULL)
10564     free (flinfo->indices);
10565   if (flinfo->sections != NULL)
10566     free (flinfo->sections);
10567   if (flinfo->symbuf != NULL)
10568     free (flinfo->symbuf);
10569   if (flinfo->symshndxbuf != NULL)
10570     free (flinfo->symshndxbuf);
10571   for (o = obfd->sections; o != NULL; o = o->next)
10572     {
10573       struct bfd_elf_section_data *esdo = elf_section_data (o);
10574       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10575         free (esdo->rel.hashes);
10576       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10577         free (esdo->rela.hashes);
10578     }
10579 }
10580
10581 /* Do the final step of an ELF link.  */
10582
10583 bfd_boolean
10584 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10585 {
10586   bfd_boolean dynamic;
10587   bfd_boolean emit_relocs;
10588   bfd *dynobj;
10589   struct elf_final_link_info flinfo;
10590   asection *o;
10591   struct bfd_link_order *p;
10592   bfd *sub;
10593   bfd_size_type max_contents_size;
10594   bfd_size_type max_external_reloc_size;
10595   bfd_size_type max_internal_reloc_count;
10596   bfd_size_type max_sym_count;
10597   bfd_size_type max_sym_shndx_count;
10598   Elf_Internal_Sym elfsym;
10599   unsigned int i;
10600   Elf_Internal_Shdr *symtab_hdr;
10601   Elf_Internal_Shdr *symtab_shndx_hdr;
10602   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10603   struct elf_outext_info eoinfo;
10604   bfd_boolean merged;
10605   size_t relativecount = 0;
10606   asection *reldyn = 0;
10607   bfd_size_type amt;
10608   asection *attr_section = NULL;
10609   bfd_vma attr_size = 0;
10610   const char *std_attrs_section;
10611
10612   if (! is_elf_hash_table (info->hash))
10613     return FALSE;
10614
10615   if (info->shared)
10616     abfd->flags |= DYNAMIC;
10617
10618   dynamic = elf_hash_table (info)->dynamic_sections_created;
10619   dynobj = elf_hash_table (info)->dynobj;
10620
10621   emit_relocs = (info->relocatable
10622                  || info->emitrelocations);
10623
10624   flinfo.info = info;
10625   flinfo.output_bfd = abfd;
10626   flinfo.symstrtab = _bfd_elf_stringtab_init ();
10627   if (flinfo.symstrtab == NULL)
10628     return FALSE;
10629
10630   if (! dynamic)
10631     {
10632       flinfo.dynsym_sec = NULL;
10633       flinfo.hash_sec = NULL;
10634       flinfo.symver_sec = NULL;
10635     }
10636   else
10637     {
10638       flinfo.dynsym_sec = bfd_get_linker_section (dynobj, ".dynsym");
10639       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
10640       /* Note that dynsym_sec can be NULL (on VMS).  */
10641       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
10642       /* Note that it is OK if symver_sec is NULL.  */
10643     }
10644
10645   flinfo.contents = NULL;
10646   flinfo.external_relocs = NULL;
10647   flinfo.internal_relocs = NULL;
10648   flinfo.external_syms = NULL;
10649   flinfo.locsym_shndx = NULL;
10650   flinfo.internal_syms = NULL;
10651   flinfo.indices = NULL;
10652   flinfo.sections = NULL;
10653   flinfo.symbuf = NULL;
10654   flinfo.symshndxbuf = NULL;
10655   flinfo.symbuf_count = 0;
10656   flinfo.shndxbuf_size = 0;
10657   flinfo.filesym_count = 0;
10658
10659   /* The object attributes have been merged.  Remove the input
10660      sections from the link, and set the contents of the output
10661      secton.  */
10662   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10663   for (o = abfd->sections; o != NULL; o = o->next)
10664     {
10665       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10666           || strcmp (o->name, ".gnu.attributes") == 0)
10667         {
10668           for (p = o->map_head.link_order; p != NULL; p = p->next)
10669             {
10670               asection *input_section;
10671
10672               if (p->type != bfd_indirect_link_order)
10673                 continue;
10674               input_section = p->u.indirect.section;
10675               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10676                  elf_link_input_bfd ignores this section.  */
10677               input_section->flags &= ~SEC_HAS_CONTENTS;
10678             }
10679
10680           attr_size = bfd_elf_obj_attr_size (abfd);
10681           if (attr_size)
10682             {
10683               bfd_set_section_size (abfd, o, attr_size);
10684               attr_section = o;
10685               /* Skip this section later on.  */
10686               o->map_head.link_order = NULL;
10687             }
10688           else
10689             o->flags |= SEC_EXCLUDE;
10690         }
10691     }
10692
10693   /* Count up the number of relocations we will output for each output
10694      section, so that we know the sizes of the reloc sections.  We
10695      also figure out some maximum sizes.  */
10696   max_contents_size = 0;
10697   max_external_reloc_size = 0;
10698   max_internal_reloc_count = 0;
10699   max_sym_count = 0;
10700   max_sym_shndx_count = 0;
10701   merged = FALSE;
10702   for (o = abfd->sections; o != NULL; o = o->next)
10703     {
10704       struct bfd_elf_section_data *esdo = elf_section_data (o);
10705       o->reloc_count = 0;
10706
10707       for (p = o->map_head.link_order; p != NULL; p = p->next)
10708         {
10709           unsigned int reloc_count = 0;
10710           struct bfd_elf_section_data *esdi = NULL;
10711
10712           if (p->type == bfd_section_reloc_link_order
10713               || p->type == bfd_symbol_reloc_link_order)
10714             reloc_count = 1;
10715           else if (p->type == bfd_indirect_link_order)
10716             {
10717               asection *sec;
10718
10719               sec = p->u.indirect.section;
10720               esdi = elf_section_data (sec);
10721
10722               /* Mark all sections which are to be included in the
10723                  link.  This will normally be every section.  We need
10724                  to do this so that we can identify any sections which
10725                  the linker has decided to not include.  */
10726               sec->linker_mark = TRUE;
10727
10728               if (sec->flags & SEC_MERGE)
10729                 merged = TRUE;
10730
10731               if (esdo->this_hdr.sh_type == SHT_REL
10732                   || esdo->this_hdr.sh_type == SHT_RELA)
10733                 /* Some backends use reloc_count in relocation sections
10734                    to count particular types of relocs.  Of course,
10735                    reloc sections themselves can't have relocations.  */
10736                 reloc_count = 0;
10737               else if (info->relocatable || info->emitrelocations)
10738                 reloc_count = sec->reloc_count;
10739               else if (bed->elf_backend_count_relocs)
10740                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10741
10742               if (sec->rawsize > max_contents_size)
10743                 max_contents_size = sec->rawsize;
10744               if (sec->size > max_contents_size)
10745                 max_contents_size = sec->size;
10746
10747               /* We are interested in just local symbols, not all
10748                  symbols.  */
10749               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10750                   && (sec->owner->flags & DYNAMIC) == 0)
10751                 {
10752                   size_t sym_count;
10753
10754                   if (elf_bad_symtab (sec->owner))
10755                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10756                                  / bed->s->sizeof_sym);
10757                   else
10758                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10759
10760                   if (sym_count > max_sym_count)
10761                     max_sym_count = sym_count;
10762
10763                   if (sym_count > max_sym_shndx_count
10764                       && elf_symtab_shndx (sec->owner) != 0)
10765                     max_sym_shndx_count = sym_count;
10766
10767                   if ((sec->flags & SEC_RELOC) != 0)
10768                     {
10769                       size_t ext_size = 0;
10770
10771                       if (esdi->rel.hdr != NULL)
10772                         ext_size = esdi->rel.hdr->sh_size;
10773                       if (esdi->rela.hdr != NULL)
10774                         ext_size += esdi->rela.hdr->sh_size;
10775
10776                       if (ext_size > max_external_reloc_size)
10777                         max_external_reloc_size = ext_size;
10778                       if (sec->reloc_count > max_internal_reloc_count)
10779                         max_internal_reloc_count = sec->reloc_count;
10780                     }
10781                 }
10782             }
10783
10784           if (reloc_count == 0)
10785             continue;
10786
10787           o->reloc_count += reloc_count;
10788
10789           if (p->type == bfd_indirect_link_order
10790               && (info->relocatable || info->emitrelocations))
10791             {
10792               if (esdi->rel.hdr)
10793                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
10794               if (esdi->rela.hdr)
10795                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
10796             }
10797           else
10798             {
10799               if (o->use_rela_p)
10800                 esdo->rela.count += reloc_count;
10801               else
10802                 esdo->rel.count += reloc_count;
10803             }
10804         }
10805
10806       if (o->reloc_count > 0)
10807         o->flags |= SEC_RELOC;
10808       else
10809         {
10810           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
10811              set it (this is probably a bug) and if it is set
10812              assign_section_numbers will create a reloc section.  */
10813           o->flags &=~ SEC_RELOC;
10814         }
10815
10816       /* If the SEC_ALLOC flag is not set, force the section VMA to
10817          zero.  This is done in elf_fake_sections as well, but forcing
10818          the VMA to 0 here will ensure that relocs against these
10819          sections are handled correctly.  */
10820       if ((o->flags & SEC_ALLOC) == 0
10821           && ! o->user_set_vma)
10822         o->vma = 0;
10823     }
10824
10825   if (! info->relocatable && merged)
10826     elf_link_hash_traverse (elf_hash_table (info),
10827                             _bfd_elf_link_sec_merge_syms, abfd);
10828
10829   /* Figure out the file positions for everything but the symbol table
10830      and the relocs.  We set symcount to force assign_section_numbers
10831      to create a symbol table.  */
10832   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
10833   BFD_ASSERT (! abfd->output_has_begun);
10834   if (! _bfd_elf_compute_section_file_positions (abfd, info))
10835     goto error_return;
10836
10837   /* Set sizes, and assign file positions for reloc sections.  */
10838   for (o = abfd->sections; o != NULL; o = o->next)
10839     {
10840       struct bfd_elf_section_data *esdo = elf_section_data (o);
10841       if ((o->flags & SEC_RELOC) != 0)
10842         {
10843           if (esdo->rel.hdr
10844               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
10845             goto error_return;
10846
10847           if (esdo->rela.hdr
10848               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
10849             goto error_return;
10850         }
10851
10852       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
10853          to count upwards while actually outputting the relocations.  */
10854       esdo->rel.count = 0;
10855       esdo->rela.count = 0;
10856     }
10857
10858   /* We have now assigned file positions for all the sections except
10859      .symtab, .strtab, and non-loaded reloc sections.  We start the
10860      .symtab section at the current file position, and write directly
10861      to it.  We build the .strtab section in memory.  */
10862   bfd_get_symcount (abfd) = 0;
10863   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10864   /* sh_name is set in prep_headers.  */
10865   symtab_hdr->sh_type = SHT_SYMTAB;
10866   /* sh_flags, sh_addr and sh_size all start off zero.  */
10867   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
10868   /* sh_link is set in assign_section_numbers.  */
10869   /* sh_info is set below.  */
10870   /* sh_offset is set just below.  */
10871   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
10872
10873   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
10874      continuously seeking to the right position in the file.  */
10875   if (! info->keep_memory || max_sym_count < 20)
10876     flinfo.symbuf_size = 20;
10877   else
10878     flinfo.symbuf_size = max_sym_count;
10879   amt = flinfo.symbuf_size;
10880   amt *= bed->s->sizeof_sym;
10881   flinfo.symbuf = (bfd_byte *) bfd_malloc (amt);
10882   if (flinfo.symbuf == NULL)
10883     goto error_return;
10884   if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
10885     {
10886       /* Wild guess at number of output symbols.  realloc'd as needed.  */
10887       amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
10888       flinfo.shndxbuf_size = amt;
10889       amt *= sizeof (Elf_External_Sym_Shndx);
10890       flinfo.symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
10891       if (flinfo.symshndxbuf == NULL)
10892         goto error_return;
10893     }
10894
10895   if (info->strip != strip_all || emit_relocs)
10896     {
10897       file_ptr off = elf_next_file_pos (abfd);
10898
10899       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
10900
10901       /* Note that at this point elf_next_file_pos (abfd) is
10902          incorrect.  We do not yet know the size of the .symtab section.
10903          We correct next_file_pos below, after we do know the size.  */
10904
10905       /* Start writing out the symbol table.  The first symbol is always a
10906          dummy symbol.  */
10907       elfsym.st_value = 0;
10908       elfsym.st_size = 0;
10909       elfsym.st_info = 0;
10910       elfsym.st_other = 0;
10911       elfsym.st_shndx = SHN_UNDEF;
10912       elfsym.st_target_internal = 0;
10913       if (elf_link_output_sym (&flinfo, NULL, &elfsym, bfd_und_section_ptr,
10914                                NULL) != 1)
10915         goto error_return;
10916
10917       /* Output a symbol for each section.  We output these even if we are
10918          discarding local symbols, since they are used for relocs.  These
10919          symbols have no names.  We store the index of each one in the
10920          index field of the section, so that we can find it again when
10921          outputting relocs.  */
10922
10923       elfsym.st_size = 0;
10924       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10925       elfsym.st_other = 0;
10926       elfsym.st_value = 0;
10927       elfsym.st_target_internal = 0;
10928       for (i = 1; i < elf_numsections (abfd); i++)
10929         {
10930           o = bfd_section_from_elf_index (abfd, i);
10931           if (o != NULL)
10932             {
10933               o->target_index = bfd_get_symcount (abfd);
10934               elfsym.st_shndx = i;
10935               if (!info->relocatable)
10936                 elfsym.st_value = o->vma;
10937               if (elf_link_output_sym (&flinfo, NULL, &elfsym, o, NULL) != 1)
10938                 goto error_return;
10939             }
10940         }
10941     }
10942
10943   /* Allocate some memory to hold information read in from the input
10944      files.  */
10945   if (max_contents_size != 0)
10946     {
10947       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
10948       if (flinfo.contents == NULL)
10949         goto error_return;
10950     }
10951
10952   if (max_external_reloc_size != 0)
10953     {
10954       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
10955       if (flinfo.external_relocs == NULL)
10956         goto error_return;
10957     }
10958
10959   if (max_internal_reloc_count != 0)
10960     {
10961       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
10962       amt *= sizeof (Elf_Internal_Rela);
10963       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
10964       if (flinfo.internal_relocs == NULL)
10965         goto error_return;
10966     }
10967
10968   if (max_sym_count != 0)
10969     {
10970       amt = max_sym_count * bed->s->sizeof_sym;
10971       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
10972       if (flinfo.external_syms == NULL)
10973         goto error_return;
10974
10975       amt = max_sym_count * sizeof (Elf_Internal_Sym);
10976       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
10977       if (flinfo.internal_syms == NULL)
10978         goto error_return;
10979
10980       amt = max_sym_count * sizeof (long);
10981       flinfo.indices = (long int *) bfd_malloc (amt);
10982       if (flinfo.indices == NULL)
10983         goto error_return;
10984
10985       amt = max_sym_count * sizeof (asection *);
10986       flinfo.sections = (asection **) bfd_malloc (amt);
10987       if (flinfo.sections == NULL)
10988         goto error_return;
10989     }
10990
10991   if (max_sym_shndx_count != 0)
10992     {
10993       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
10994       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
10995       if (flinfo.locsym_shndx == NULL)
10996         goto error_return;
10997     }
10998
10999   if (elf_hash_table (info)->tls_sec)
11000     {
11001       bfd_vma base, end = 0;
11002       asection *sec;
11003
11004       for (sec = elf_hash_table (info)->tls_sec;
11005            sec && (sec->flags & SEC_THREAD_LOCAL);
11006            sec = sec->next)
11007         {
11008           bfd_size_type size = sec->size;
11009
11010           if (size == 0
11011               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11012             {
11013               struct bfd_link_order *ord = sec->map_tail.link_order;
11014
11015               if (ord != NULL)
11016                 size = ord->offset + ord->size;
11017             }
11018           end = sec->vma + size;
11019         }
11020       base = elf_hash_table (info)->tls_sec->vma;
11021       /* Only align end of TLS section if static TLS doesn't have special
11022          alignment requirements.  */
11023       if (bed->static_tls_alignment == 1)
11024         end = align_power (end,
11025                            elf_hash_table (info)->tls_sec->alignment_power);
11026       elf_hash_table (info)->tls_size = end - base;
11027     }
11028
11029   /* Reorder SHF_LINK_ORDER sections.  */
11030   for (o = abfd->sections; o != NULL; o = o->next)
11031     {
11032       if (!elf_fixup_link_order (abfd, o))
11033         return FALSE;
11034     }
11035
11036   /* Since ELF permits relocations to be against local symbols, we
11037      must have the local symbols available when we do the relocations.
11038      Since we would rather only read the local symbols once, and we
11039      would rather not keep them in memory, we handle all the
11040      relocations for a single input file at the same time.
11041
11042      Unfortunately, there is no way to know the total number of local
11043      symbols until we have seen all of them, and the local symbol
11044      indices precede the global symbol indices.  This means that when
11045      we are generating relocatable output, and we see a reloc against
11046      a global symbol, we can not know the symbol index until we have
11047      finished examining all the local symbols to see which ones we are
11048      going to output.  To deal with this, we keep the relocations in
11049      memory, and don't output them until the end of the link.  This is
11050      an unfortunate waste of memory, but I don't see a good way around
11051      it.  Fortunately, it only happens when performing a relocatable
11052      link, which is not the common case.  FIXME: If keep_memory is set
11053      we could write the relocs out and then read them again; I don't
11054      know how bad the memory loss will be.  */
11055
11056   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11057     sub->output_has_begun = FALSE;
11058   for (o = abfd->sections; o != NULL; o = o->next)
11059     {
11060       for (p = o->map_head.link_order; p != NULL; p = p->next)
11061         {
11062           if (p->type == bfd_indirect_link_order
11063               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11064                   == bfd_target_elf_flavour)
11065               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11066             {
11067               if (! sub->output_has_begun)
11068                 {
11069                   if (! elf_link_input_bfd (&flinfo, sub))
11070                     goto error_return;
11071                   sub->output_has_begun = TRUE;
11072                 }
11073             }
11074           else if (p->type == bfd_section_reloc_link_order
11075                    || p->type == bfd_symbol_reloc_link_order)
11076             {
11077               if (! elf_reloc_link_order (abfd, info, o, p))
11078                 goto error_return;
11079             }
11080           else
11081             {
11082               if (! _bfd_default_link_order (abfd, info, o, p))
11083                 {
11084                   if (p->type == bfd_indirect_link_order
11085                       && (bfd_get_flavour (sub)
11086                           == bfd_target_elf_flavour)
11087                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11088                           != bed->s->elfclass))
11089                     {
11090                       const char *iclass, *oclass;
11091
11092                       if (bed->s->elfclass == ELFCLASS64)
11093                         {
11094                           iclass = "ELFCLASS32";
11095                           oclass = "ELFCLASS64";
11096                         }
11097                       else
11098                         {
11099                           iclass = "ELFCLASS64";
11100                           oclass = "ELFCLASS32";
11101                         }
11102
11103                       bfd_set_error (bfd_error_wrong_format);
11104                       (*_bfd_error_handler)
11105                         (_("%B: file class %s incompatible with %s"),
11106                          sub, iclass, oclass);
11107                     }
11108
11109                   goto error_return;
11110                 }
11111             }
11112         }
11113     }
11114
11115   /* Free symbol buffer if needed.  */
11116   if (!info->reduce_memory_overheads)
11117     {
11118       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11119         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11120             && elf_tdata (sub)->symbuf)
11121           {
11122             free (elf_tdata (sub)->symbuf);
11123             elf_tdata (sub)->symbuf = NULL;
11124           }
11125     }
11126
11127   /* Output any global symbols that got converted to local in a
11128      version script or due to symbol visibility.  We do this in a
11129      separate step since ELF requires all local symbols to appear
11130      prior to any global symbols.  FIXME: We should only do this if
11131      some global symbols were, in fact, converted to become local.
11132      FIXME: Will this work correctly with the Irix 5 linker?  */
11133   eoinfo.failed = FALSE;
11134   eoinfo.flinfo = &flinfo;
11135   eoinfo.localsyms = TRUE;
11136   eoinfo.need_second_pass = FALSE;
11137   eoinfo.second_pass = FALSE;
11138   eoinfo.file_sym_done = FALSE;
11139   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11140   if (eoinfo.failed)
11141     return FALSE;
11142
11143   if (eoinfo.need_second_pass)
11144     {
11145       eoinfo.second_pass = TRUE;
11146       bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11147       if (eoinfo.failed)
11148         return FALSE;
11149     }
11150
11151   /* If backend needs to output some local symbols not present in the hash
11152      table, do it now.  */
11153   if (bed->elf_backend_output_arch_local_syms
11154       && (info->strip != strip_all || emit_relocs))
11155     {
11156       typedef int (*out_sym_func)
11157         (void *, const char *, Elf_Internal_Sym *, asection *,
11158          struct elf_link_hash_entry *);
11159
11160       if (! ((*bed->elf_backend_output_arch_local_syms)
11161              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
11162         return FALSE;
11163     }
11164
11165   /* That wrote out all the local symbols.  Finish up the symbol table
11166      with the global symbols. Even if we want to strip everything we
11167      can, we still need to deal with those global symbols that got
11168      converted to local in a version script.  */
11169
11170   /* The sh_info field records the index of the first non local symbol.  */
11171   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11172
11173   if (dynamic
11174       && flinfo.dynsym_sec != NULL
11175       && flinfo.dynsym_sec->output_section != bfd_abs_section_ptr)
11176     {
11177       Elf_Internal_Sym sym;
11178       bfd_byte *dynsym = flinfo.dynsym_sec->contents;
11179       long last_local = 0;
11180
11181       /* Write out the section symbols for the output sections.  */
11182       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
11183         {
11184           asection *s;
11185
11186           sym.st_size = 0;
11187           sym.st_name = 0;
11188           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11189           sym.st_other = 0;
11190           sym.st_target_internal = 0;
11191
11192           for (s = abfd->sections; s != NULL; s = s->next)
11193             {
11194               int indx;
11195               bfd_byte *dest;
11196               long dynindx;
11197
11198               dynindx = elf_section_data (s)->dynindx;
11199               if (dynindx <= 0)
11200                 continue;
11201               indx = elf_section_data (s)->this_idx;
11202               BFD_ASSERT (indx > 0);
11203               sym.st_shndx = indx;
11204               if (! check_dynsym (abfd, &sym))
11205                 return FALSE;
11206               sym.st_value = s->vma;
11207               dest = dynsym + dynindx * bed->s->sizeof_sym;
11208               if (last_local < dynindx)
11209                 last_local = dynindx;
11210               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11211             }
11212         }
11213
11214       /* Write out the local dynsyms.  */
11215       if (elf_hash_table (info)->dynlocal)
11216         {
11217           struct elf_link_local_dynamic_entry *e;
11218           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11219             {
11220               asection *s;
11221               bfd_byte *dest;
11222
11223               /* Copy the internal symbol and turn off visibility.
11224                  Note that we saved a word of storage and overwrote
11225                  the original st_name with the dynstr_index.  */
11226               sym = e->isym;
11227               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11228
11229               s = bfd_section_from_elf_index (e->input_bfd,
11230                                               e->isym.st_shndx);
11231               if (s != NULL)
11232                 {
11233                   sym.st_shndx =
11234                     elf_section_data (s->output_section)->this_idx;
11235                   if (! check_dynsym (abfd, &sym))
11236                     return FALSE;
11237                   sym.st_value = (s->output_section->vma
11238                                   + s->output_offset
11239                                   + e->isym.st_value);
11240                 }
11241
11242               if (last_local < e->dynindx)
11243                 last_local = e->dynindx;
11244
11245               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11246               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11247             }
11248         }
11249
11250       elf_section_data (flinfo.dynsym_sec->output_section)->this_hdr.sh_info =
11251         last_local + 1;
11252     }
11253
11254   /* We get the global symbols from the hash table.  */
11255   eoinfo.failed = FALSE;
11256   eoinfo.localsyms = FALSE;
11257   eoinfo.flinfo = &flinfo;
11258   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11259   if (eoinfo.failed)
11260     return FALSE;
11261
11262   /* If backend needs to output some symbols not present in the hash
11263      table, do it now.  */
11264   if (bed->elf_backend_output_arch_syms
11265       && (info->strip != strip_all || emit_relocs))
11266     {
11267       typedef int (*out_sym_func)
11268         (void *, const char *, Elf_Internal_Sym *, asection *,
11269          struct elf_link_hash_entry *);
11270
11271       if (! ((*bed->elf_backend_output_arch_syms)
11272              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
11273         return FALSE;
11274     }
11275
11276   /* Flush all symbols to the file.  */
11277   if (! elf_link_flush_output_syms (&flinfo, bed))
11278     return FALSE;
11279
11280   /* Now we know the size of the symtab section.  */
11281   if (bfd_get_symcount (abfd) > 0)
11282     {
11283       /* Finish up and write out the symbol string table (.strtab)
11284          section.  */
11285       Elf_Internal_Shdr *symstrtab_hdr;
11286       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11287
11288       symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
11289       if (symtab_shndx_hdr->sh_name != 0)
11290         {
11291           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11292           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11293           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11294           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11295           symtab_shndx_hdr->sh_size = amt;
11296
11297           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11298                                                            off, TRUE);
11299
11300           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11301               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11302             return FALSE;
11303         }
11304
11305       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11306       /* sh_name was set in prep_headers.  */
11307       symstrtab_hdr->sh_type = SHT_STRTAB;
11308       symstrtab_hdr->sh_flags = 0;
11309       symstrtab_hdr->sh_addr = 0;
11310       symstrtab_hdr->sh_size = _bfd_stringtab_size (flinfo.symstrtab);
11311       symstrtab_hdr->sh_entsize = 0;
11312       symstrtab_hdr->sh_link = 0;
11313       symstrtab_hdr->sh_info = 0;
11314       /* sh_offset is set just below.  */
11315       symstrtab_hdr->sh_addralign = 1;
11316
11317       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11318                                                        off, TRUE);
11319       elf_next_file_pos (abfd) = off;
11320
11321       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11322           || ! _bfd_stringtab_emit (abfd, flinfo.symstrtab))
11323         return FALSE;
11324     }
11325
11326   /* Adjust the relocs to have the correct symbol indices.  */
11327   for (o = abfd->sections; o != NULL; o = o->next)
11328     {
11329       struct bfd_elf_section_data *esdo = elf_section_data (o);
11330       bfd_boolean sort;
11331       if ((o->flags & SEC_RELOC) == 0)
11332         continue;
11333
11334       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11335       if (esdo->rel.hdr != NULL)
11336         elf_link_adjust_relocs (abfd, &esdo->rel, sort);
11337       if (esdo->rela.hdr != NULL)
11338         elf_link_adjust_relocs (abfd, &esdo->rela, sort);
11339
11340       /* Set the reloc_count field to 0 to prevent write_relocs from
11341          trying to swap the relocs out itself.  */
11342       o->reloc_count = 0;
11343     }
11344
11345   if (dynamic && info->combreloc && dynobj != NULL)
11346     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11347
11348   /* If we are linking against a dynamic object, or generating a
11349      shared library, finish up the dynamic linking information.  */
11350   if (dynamic)
11351     {
11352       bfd_byte *dyncon, *dynconend;
11353
11354       /* Fix up .dynamic entries.  */
11355       o = bfd_get_linker_section (dynobj, ".dynamic");
11356       BFD_ASSERT (o != NULL);
11357
11358       dyncon = o->contents;
11359       dynconend = o->contents + o->size;
11360       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11361         {
11362           Elf_Internal_Dyn dyn;
11363           const char *name;
11364           unsigned int type;
11365
11366           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11367
11368           switch (dyn.d_tag)
11369             {
11370             default:
11371               continue;
11372             case DT_NULL:
11373               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11374                 {
11375                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11376                     {
11377                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11378                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11379                     default: continue;
11380                     }
11381                   dyn.d_un.d_val = relativecount;
11382                   relativecount = 0;
11383                   break;
11384                 }
11385               continue;
11386
11387             case DT_INIT:
11388               name = info->init_function;
11389               goto get_sym;
11390             case DT_FINI:
11391               name = info->fini_function;
11392             get_sym:
11393               {
11394                 struct elf_link_hash_entry *h;
11395
11396                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11397                                           FALSE, FALSE, TRUE);
11398                 if (h != NULL
11399                     && (h->root.type == bfd_link_hash_defined
11400                         || h->root.type == bfd_link_hash_defweak))
11401                   {
11402                     dyn.d_un.d_ptr = h->root.u.def.value;
11403                     o = h->root.u.def.section;
11404                     if (o->output_section != NULL)
11405                       dyn.d_un.d_ptr += (o->output_section->vma
11406                                          + o->output_offset);
11407                     else
11408                       {
11409                         /* The symbol is imported from another shared
11410                            library and does not apply to this one.  */
11411                         dyn.d_un.d_ptr = 0;
11412                       }
11413                     break;
11414                   }
11415               }
11416               continue;
11417
11418             case DT_PREINIT_ARRAYSZ:
11419               name = ".preinit_array";
11420               goto get_size;
11421             case DT_INIT_ARRAYSZ:
11422               name = ".init_array";
11423               goto get_size;
11424             case DT_FINI_ARRAYSZ:
11425               name = ".fini_array";
11426             get_size:
11427               o = bfd_get_section_by_name (abfd, name);
11428               if (o == NULL)
11429                 {
11430                   (*_bfd_error_handler)
11431                     (_("%B: could not find output section %s"), abfd, name);
11432                   goto error_return;
11433                 }
11434               if (o->size == 0)
11435                 (*_bfd_error_handler)
11436                   (_("warning: %s section has zero size"), name);
11437               dyn.d_un.d_val = o->size;
11438               break;
11439
11440             case DT_PREINIT_ARRAY:
11441               name = ".preinit_array";
11442               goto get_vma;
11443             case DT_INIT_ARRAY:
11444               name = ".init_array";
11445               goto get_vma;
11446             case DT_FINI_ARRAY:
11447               name = ".fini_array";
11448               goto get_vma;
11449
11450             case DT_HASH:
11451               name = ".hash";
11452               goto get_vma;
11453             case DT_GNU_HASH:
11454               name = ".gnu.hash";
11455               goto get_vma;
11456             case DT_STRTAB:
11457               name = ".dynstr";
11458               goto get_vma;
11459             case DT_SYMTAB:
11460               name = ".dynsym";
11461               goto get_vma;
11462             case DT_VERDEF:
11463               name = ".gnu.version_d";
11464               goto get_vma;
11465             case DT_VERNEED:
11466               name = ".gnu.version_r";
11467               goto get_vma;
11468             case DT_VERSYM:
11469               name = ".gnu.version";
11470             get_vma:
11471               o = bfd_get_section_by_name (abfd, name);
11472               if (o == NULL)
11473                 {
11474                   (*_bfd_error_handler)
11475                     (_("%B: could not find output section %s"), abfd, name);
11476                   goto error_return;
11477                 }
11478               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11479                 {
11480                   (*_bfd_error_handler)
11481                     (_("warning: section '%s' is being made into a note"), name);
11482                   bfd_set_error (bfd_error_nonrepresentable_section);
11483                   goto error_return;
11484                 }
11485               dyn.d_un.d_ptr = o->vma;
11486               break;
11487
11488             case DT_REL:
11489             case DT_RELA:
11490             case DT_RELSZ:
11491             case DT_RELASZ:
11492               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11493                 type = SHT_REL;
11494               else
11495                 type = SHT_RELA;
11496               dyn.d_un.d_val = 0;
11497               dyn.d_un.d_ptr = 0;
11498               for (i = 1; i < elf_numsections (abfd); i++)
11499                 {
11500                   Elf_Internal_Shdr *hdr;
11501
11502                   hdr = elf_elfsections (abfd)[i];
11503                   if (hdr->sh_type == type
11504                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11505                     {
11506                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11507                         dyn.d_un.d_val += hdr->sh_size;
11508                       else
11509                         {
11510                           if (dyn.d_un.d_ptr == 0
11511                               || hdr->sh_addr < dyn.d_un.d_ptr)
11512                             dyn.d_un.d_ptr = hdr->sh_addr;
11513                         }
11514                     }
11515                 }
11516               break;
11517             }
11518           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11519         }
11520     }
11521
11522   /* If we have created any dynamic sections, then output them.  */
11523   if (dynobj != NULL)
11524     {
11525       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11526         goto error_return;
11527
11528       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11529       if (((info->warn_shared_textrel && info->shared)
11530            || info->error_textrel)
11531           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11532         {
11533           bfd_byte *dyncon, *dynconend;
11534
11535           dyncon = o->contents;
11536           dynconend = o->contents + o->size;
11537           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11538             {
11539               Elf_Internal_Dyn dyn;
11540
11541               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11542
11543               if (dyn.d_tag == DT_TEXTREL)
11544                 {
11545                   if (info->error_textrel)
11546                     info->callbacks->einfo
11547                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11548                   else
11549                     info->callbacks->einfo
11550                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11551                   break;
11552                 }
11553             }
11554         }
11555
11556       for (o = dynobj->sections; o != NULL; o = o->next)
11557         {
11558           if ((o->flags & SEC_HAS_CONTENTS) == 0
11559               || o->size == 0
11560               || o->output_section == bfd_abs_section_ptr)
11561             continue;
11562           if ((o->flags & SEC_LINKER_CREATED) == 0)
11563             {
11564               /* At this point, we are only interested in sections
11565                  created by _bfd_elf_link_create_dynamic_sections.  */
11566               continue;
11567             }
11568           if (elf_hash_table (info)->stab_info.stabstr == o)
11569             continue;
11570           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11571             continue;
11572           if (strcmp (o->name, ".dynstr") != 0)
11573             {
11574               /* FIXME: octets_per_byte.  */
11575               if (! bfd_set_section_contents (abfd, o->output_section,
11576                                               o->contents,
11577                                               (file_ptr) o->output_offset,
11578                                               o->size))
11579                 goto error_return;
11580             }
11581           else
11582             {
11583               /* The contents of the .dynstr section are actually in a
11584                  stringtab.  */
11585               file_ptr off;
11586
11587               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11588               if (bfd_seek (abfd, off, SEEK_SET) != 0
11589                   || ! _bfd_elf_strtab_emit (abfd,
11590                                              elf_hash_table (info)->dynstr))
11591                 goto error_return;
11592             }
11593         }
11594     }
11595
11596   if (info->relocatable)
11597     {
11598       bfd_boolean failed = FALSE;
11599
11600       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11601       if (failed)
11602         goto error_return;
11603     }
11604
11605   /* If we have optimized stabs strings, output them.  */
11606   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11607     {
11608       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11609         goto error_return;
11610     }
11611
11612   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11613     goto error_return;
11614
11615   elf_final_link_free (abfd, &flinfo);
11616
11617   elf_linker (abfd) = TRUE;
11618
11619   if (attr_section)
11620     {
11621       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11622       if (contents == NULL)
11623         return FALSE;   /* Bail out and fail.  */
11624       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11625       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11626       free (contents);
11627     }
11628
11629   return TRUE;
11630
11631  error_return:
11632   elf_final_link_free (abfd, &flinfo);
11633   return FALSE;
11634 }
11635 \f
11636 /* Initialize COOKIE for input bfd ABFD.  */
11637
11638 static bfd_boolean
11639 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11640                    struct bfd_link_info *info, bfd *abfd)
11641 {
11642   Elf_Internal_Shdr *symtab_hdr;
11643   const struct elf_backend_data *bed;
11644
11645   bed = get_elf_backend_data (abfd);
11646   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11647
11648   cookie->abfd = abfd;
11649   cookie->sym_hashes = elf_sym_hashes (abfd);
11650   cookie->bad_symtab = elf_bad_symtab (abfd);
11651   if (cookie->bad_symtab)
11652     {
11653       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11654       cookie->extsymoff = 0;
11655     }
11656   else
11657     {
11658       cookie->locsymcount = symtab_hdr->sh_info;
11659       cookie->extsymoff = symtab_hdr->sh_info;
11660     }
11661
11662   if (bed->s->arch_size == 32)
11663     cookie->r_sym_shift = 8;
11664   else
11665     cookie->r_sym_shift = 32;
11666
11667   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11668   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11669     {
11670       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11671                                               cookie->locsymcount, 0,
11672                                               NULL, NULL, NULL);
11673       if (cookie->locsyms == NULL)
11674         {
11675           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11676           return FALSE;
11677         }
11678       if (info->keep_memory)
11679         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11680     }
11681   return TRUE;
11682 }
11683
11684 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11685
11686 static void
11687 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11688 {
11689   Elf_Internal_Shdr *symtab_hdr;
11690
11691   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11692   if (cookie->locsyms != NULL
11693       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11694     free (cookie->locsyms);
11695 }
11696
11697 /* Initialize the relocation information in COOKIE for input section SEC
11698    of input bfd ABFD.  */
11699
11700 static bfd_boolean
11701 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11702                         struct bfd_link_info *info, bfd *abfd,
11703                         asection *sec)
11704 {
11705   const struct elf_backend_data *bed;
11706
11707   if (sec->reloc_count == 0)
11708     {
11709       cookie->rels = NULL;
11710       cookie->relend = NULL;
11711     }
11712   else
11713     {
11714       bed = get_elf_backend_data (abfd);
11715
11716       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11717                                                 info->keep_memory);
11718       if (cookie->rels == NULL)
11719         return FALSE;
11720       cookie->rel = cookie->rels;
11721       cookie->relend = (cookie->rels
11722                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11723     }
11724   cookie->rel = cookie->rels;
11725   return TRUE;
11726 }
11727
11728 /* Free the memory allocated by init_reloc_cookie_rels,
11729    if appropriate.  */
11730
11731 static void
11732 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11733                         asection *sec)
11734 {
11735   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11736     free (cookie->rels);
11737 }
11738
11739 /* Initialize the whole of COOKIE for input section SEC.  */
11740
11741 static bfd_boolean
11742 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11743                                struct bfd_link_info *info,
11744                                asection *sec)
11745 {
11746   if (!init_reloc_cookie (cookie, info, sec->owner))
11747     goto error1;
11748   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11749     goto error2;
11750   return TRUE;
11751
11752  error2:
11753   fini_reloc_cookie (cookie, sec->owner);
11754  error1:
11755   return FALSE;
11756 }
11757
11758 /* Free the memory allocated by init_reloc_cookie_for_section,
11759    if appropriate.  */
11760
11761 static void
11762 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11763                                asection *sec)
11764 {
11765   fini_reloc_cookie_rels (cookie, sec);
11766   fini_reloc_cookie (cookie, sec->owner);
11767 }
11768 \f
11769 /* Garbage collect unused sections.  */
11770
11771 /* Default gc_mark_hook.  */
11772
11773 asection *
11774 _bfd_elf_gc_mark_hook (asection *sec,
11775                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
11776                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
11777                        struct elf_link_hash_entry *h,
11778                        Elf_Internal_Sym *sym)
11779 {
11780   const char *sec_name;
11781
11782   if (h != NULL)
11783     {
11784       switch (h->root.type)
11785         {
11786         case bfd_link_hash_defined:
11787         case bfd_link_hash_defweak:
11788           return h->root.u.def.section;
11789
11790         case bfd_link_hash_common:
11791           return h->root.u.c.p->section;
11792
11793         case bfd_link_hash_undefined:
11794         case bfd_link_hash_undefweak:
11795           /* To work around a glibc bug, keep all XXX input sections
11796              when there is an as yet undefined reference to __start_XXX
11797              or __stop_XXX symbols.  The linker will later define such
11798              symbols for orphan input sections that have a name
11799              representable as a C identifier.  */
11800           if (strncmp (h->root.root.string, "__start_", 8) == 0)
11801             sec_name = h->root.root.string + 8;
11802           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
11803             sec_name = h->root.root.string + 7;
11804           else
11805             sec_name = NULL;
11806
11807           if (sec_name && *sec_name != '\0')
11808             {
11809               bfd *i;
11810
11811               for (i = info->input_bfds; i; i = i->link.next)
11812                 {
11813                   sec = bfd_get_section_by_name (i, sec_name);
11814                   if (sec)
11815                     sec->flags |= SEC_KEEP;
11816                 }
11817             }
11818           break;
11819
11820         default:
11821           break;
11822         }
11823     }
11824   else
11825     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
11826
11827   return NULL;
11828 }
11829
11830 /* COOKIE->rel describes a relocation against section SEC, which is
11831    a section we've decided to keep.  Return the section that contains
11832    the relocation symbol, or NULL if no section contains it.  */
11833
11834 asection *
11835 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
11836                        elf_gc_mark_hook_fn gc_mark_hook,
11837                        struct elf_reloc_cookie *cookie)
11838 {
11839   unsigned long r_symndx;
11840   struct elf_link_hash_entry *h;
11841
11842   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
11843   if (r_symndx == STN_UNDEF)
11844     return NULL;
11845
11846   if (r_symndx >= cookie->locsymcount
11847       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11848     {
11849       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
11850       if (h == NULL)
11851         {
11852           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
11853                                   sec->owner);
11854           return NULL;
11855         }
11856       while (h->root.type == bfd_link_hash_indirect
11857              || h->root.type == bfd_link_hash_warning)
11858         h = (struct elf_link_hash_entry *) h->root.u.i.link;
11859       h->mark = 1;
11860       /* If this symbol is weak and there is a non-weak definition, we
11861          keep the non-weak definition because many backends put
11862          dynamic reloc info on the non-weak definition for code
11863          handling copy relocs.  */
11864       if (h->u.weakdef != NULL)
11865         h->u.weakdef->mark = 1;
11866       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
11867     }
11868
11869   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
11870                           &cookie->locsyms[r_symndx]);
11871 }
11872
11873 /* COOKIE->rel describes a relocation against section SEC, which is
11874    a section we've decided to keep.  Mark the section that contains
11875    the relocation symbol.  */
11876
11877 bfd_boolean
11878 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
11879                         asection *sec,
11880                         elf_gc_mark_hook_fn gc_mark_hook,
11881                         struct elf_reloc_cookie *cookie)
11882 {
11883   asection *rsec;
11884
11885   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
11886   if (rsec && !rsec->gc_mark)
11887     {
11888       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
11889           || (rsec->owner->flags & DYNAMIC) != 0)
11890         rsec->gc_mark = 1;
11891       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
11892         return FALSE;
11893     }
11894   return TRUE;
11895 }
11896
11897 /* The mark phase of garbage collection.  For a given section, mark
11898    it and any sections in this section's group, and all the sections
11899    which define symbols to which it refers.  */
11900
11901 bfd_boolean
11902 _bfd_elf_gc_mark (struct bfd_link_info *info,
11903                   asection *sec,
11904                   elf_gc_mark_hook_fn gc_mark_hook)
11905 {
11906   bfd_boolean ret;
11907   asection *group_sec, *eh_frame;
11908
11909   sec->gc_mark = 1;
11910
11911   /* Mark all the sections in the group.  */
11912   group_sec = elf_section_data (sec)->next_in_group;
11913   if (group_sec && !group_sec->gc_mark)
11914     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
11915       return FALSE;
11916
11917   /* Look through the section relocs.  */
11918   ret = TRUE;
11919   eh_frame = elf_eh_frame_section (sec->owner);
11920   if ((sec->flags & SEC_RELOC) != 0
11921       && sec->reloc_count > 0
11922       && sec != eh_frame)
11923     {
11924       struct elf_reloc_cookie cookie;
11925
11926       if (!init_reloc_cookie_for_section (&cookie, info, sec))
11927         ret = FALSE;
11928       else
11929         {
11930           for (; cookie.rel < cookie.relend; cookie.rel++)
11931             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
11932               {
11933                 ret = FALSE;
11934                 break;
11935               }
11936           fini_reloc_cookie_for_section (&cookie, sec);
11937         }
11938     }
11939
11940   if (ret && eh_frame && elf_fde_list (sec))
11941     {
11942       struct elf_reloc_cookie cookie;
11943
11944       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
11945         ret = FALSE;
11946       else
11947         {
11948           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
11949                                       gc_mark_hook, &cookie))
11950             ret = FALSE;
11951           fini_reloc_cookie_for_section (&cookie, eh_frame);
11952         }
11953     }
11954
11955   return ret;
11956 }
11957
11958 /* Keep debug and special sections.  */
11959
11960 bfd_boolean
11961 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
11962                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
11963 {
11964   bfd *ibfd;
11965
11966   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
11967     {
11968       asection *isec;
11969       bfd_boolean some_kept;
11970       bfd_boolean debug_frag_seen;
11971
11972       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
11973         continue;
11974
11975       /* Ensure all linker created sections are kept,
11976          see if any other section is already marked,
11977          and note if we have any fragmented debug sections.  */
11978       debug_frag_seen = some_kept = FALSE;
11979       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11980         {
11981           if ((isec->flags & SEC_LINKER_CREATED) != 0)
11982             isec->gc_mark = 1;
11983           else if (isec->gc_mark)
11984             some_kept = TRUE;
11985
11986           if (debug_frag_seen == FALSE
11987               && (isec->flags & SEC_DEBUGGING)
11988               && CONST_STRNEQ (isec->name, ".debug_line."))
11989             debug_frag_seen = TRUE;
11990         }
11991
11992       /* If no section in this file will be kept, then we can
11993          toss out the debug and special sections.  */
11994       if (!some_kept)
11995         continue;
11996
11997       /* Keep debug and special sections like .comment when they are
11998          not part of a group, or when we have single-member groups.  */
11999       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12000         if ((elf_next_in_group (isec) == NULL
12001              || elf_next_in_group (isec) == isec)
12002             && ((isec->flags & SEC_DEBUGGING) != 0
12003                 || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0))
12004           isec->gc_mark = 1;
12005
12006       if (! debug_frag_seen)
12007         continue;
12008
12009       /* Look for CODE sections which are going to be discarded,
12010          and find and discard any fragmented debug sections which
12011          are associated with that code section.  */
12012       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12013         if ((isec->flags & SEC_CODE) != 0
12014             && isec->gc_mark == 0)
12015           {
12016             unsigned int ilen;
12017             asection *dsec;
12018
12019             ilen = strlen (isec->name);
12020
12021             /* Association is determined by the name of the debug section
12022                containing the name of the code section as a suffix.  For
12023                example .debug_line.text.foo is a debug section associated
12024                with .text.foo.  */
12025             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12026               {
12027                 unsigned int dlen;
12028
12029                 if (dsec->gc_mark == 0
12030                     || (dsec->flags & SEC_DEBUGGING) == 0)
12031                   continue;
12032
12033                 dlen = strlen (dsec->name);
12034
12035                 if (dlen > ilen
12036                     && strncmp (dsec->name + (dlen - ilen),
12037                                 isec->name, ilen) == 0)
12038                   {
12039                     dsec->gc_mark = 0;
12040                     break;
12041                   }
12042               }
12043           }
12044     }
12045   return TRUE;
12046 }
12047
12048 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12049
12050 struct elf_gc_sweep_symbol_info
12051 {
12052   struct bfd_link_info *info;
12053   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12054                        bfd_boolean);
12055 };
12056
12057 static bfd_boolean
12058 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12059 {
12060   if (!h->mark
12061       && (((h->root.type == bfd_link_hash_defined
12062             || h->root.type == bfd_link_hash_defweak)
12063            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12064                 && h->root.u.def.section->gc_mark))
12065           || h->root.type == bfd_link_hash_undefined
12066           || h->root.type == bfd_link_hash_undefweak))
12067     {
12068       struct elf_gc_sweep_symbol_info *inf;
12069
12070       inf = (struct elf_gc_sweep_symbol_info *) data;
12071       (*inf->hide_symbol) (inf->info, h, TRUE);
12072       h->def_regular = 0;
12073       h->ref_regular = 0;
12074       h->ref_regular_nonweak = 0;
12075     }
12076
12077   return TRUE;
12078 }
12079
12080 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12081
12082 typedef bfd_boolean (*gc_sweep_hook_fn)
12083   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12084
12085 static bfd_boolean
12086 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12087 {
12088   bfd *sub;
12089   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12090   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12091   unsigned long section_sym_count;
12092   struct elf_gc_sweep_symbol_info sweep_info;
12093
12094   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12095     {
12096       asection *o;
12097
12098       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12099         continue;
12100
12101       for (o = sub->sections; o != NULL; o = o->next)
12102         {
12103           /* When any section in a section group is kept, we keep all
12104              sections in the section group.  If the first member of
12105              the section group is excluded, we will also exclude the
12106              group section.  */
12107           if (o->flags & SEC_GROUP)
12108             {
12109               asection *first = elf_next_in_group (o);
12110               o->gc_mark = first->gc_mark;
12111             }
12112
12113           if (o->gc_mark)
12114             continue;
12115
12116           /* Skip sweeping sections already excluded.  */
12117           if (o->flags & SEC_EXCLUDE)
12118             continue;
12119
12120           /* Since this is early in the link process, it is simple
12121              to remove a section from the output.  */
12122           o->flags |= SEC_EXCLUDE;
12123
12124           if (info->print_gc_sections && o->size != 0)
12125             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12126
12127           /* But we also have to update some of the relocation
12128              info we collected before.  */
12129           if (gc_sweep_hook
12130               && (o->flags & SEC_RELOC) != 0
12131               && o->reloc_count != 0
12132               && !((info->strip == strip_all || info->strip == strip_debugger)
12133                    && (o->flags & SEC_DEBUGGING) != 0)
12134               && !bfd_is_abs_section (o->output_section))
12135             {
12136               Elf_Internal_Rela *internal_relocs;
12137               bfd_boolean r;
12138
12139               internal_relocs
12140                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12141                                              info->keep_memory);
12142               if (internal_relocs == NULL)
12143                 return FALSE;
12144
12145               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12146
12147               if (elf_section_data (o)->relocs != internal_relocs)
12148                 free (internal_relocs);
12149
12150               if (!r)
12151                 return FALSE;
12152             }
12153         }
12154     }
12155
12156   /* Remove the symbols that were in the swept sections from the dynamic
12157      symbol table.  GCFIXME: Anyone know how to get them out of the
12158      static symbol table as well?  */
12159   sweep_info.info = info;
12160   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12161   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12162                           &sweep_info);
12163
12164   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12165   return TRUE;
12166 }
12167
12168 /* Propagate collected vtable information.  This is called through
12169    elf_link_hash_traverse.  */
12170
12171 static bfd_boolean
12172 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12173 {
12174   /* Those that are not vtables.  */
12175   if (h->vtable == NULL || h->vtable->parent == NULL)
12176     return TRUE;
12177
12178   /* Those vtables that do not have parents, we cannot merge.  */
12179   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12180     return TRUE;
12181
12182   /* If we've already been done, exit.  */
12183   if (h->vtable->used && h->vtable->used[-1])
12184     return TRUE;
12185
12186   /* Make sure the parent's table is up to date.  */
12187   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12188
12189   if (h->vtable->used == NULL)
12190     {
12191       /* None of this table's entries were referenced.  Re-use the
12192          parent's table.  */
12193       h->vtable->used = h->vtable->parent->vtable->used;
12194       h->vtable->size = h->vtable->parent->vtable->size;
12195     }
12196   else
12197     {
12198       size_t n;
12199       bfd_boolean *cu, *pu;
12200
12201       /* Or the parent's entries into ours.  */
12202       cu = h->vtable->used;
12203       cu[-1] = TRUE;
12204       pu = h->vtable->parent->vtable->used;
12205       if (pu != NULL)
12206         {
12207           const struct elf_backend_data *bed;
12208           unsigned int log_file_align;
12209
12210           bed = get_elf_backend_data (h->root.u.def.section->owner);
12211           log_file_align = bed->s->log_file_align;
12212           n = h->vtable->parent->vtable->size >> log_file_align;
12213           while (n--)
12214             {
12215               if (*pu)
12216                 *cu = TRUE;
12217               pu++;
12218               cu++;
12219             }
12220         }
12221     }
12222
12223   return TRUE;
12224 }
12225
12226 static bfd_boolean
12227 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12228 {
12229   asection *sec;
12230   bfd_vma hstart, hend;
12231   Elf_Internal_Rela *relstart, *relend, *rel;
12232   const struct elf_backend_data *bed;
12233   unsigned int log_file_align;
12234
12235   /* Take care of both those symbols that do not describe vtables as
12236      well as those that are not loaded.  */
12237   if (h->vtable == NULL || h->vtable->parent == NULL)
12238     return TRUE;
12239
12240   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12241               || h->root.type == bfd_link_hash_defweak);
12242
12243   sec = h->root.u.def.section;
12244   hstart = h->root.u.def.value;
12245   hend = hstart + h->size;
12246
12247   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12248   if (!relstart)
12249     return *(bfd_boolean *) okp = FALSE;
12250   bed = get_elf_backend_data (sec->owner);
12251   log_file_align = bed->s->log_file_align;
12252
12253   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12254
12255   for (rel = relstart; rel < relend; ++rel)
12256     if (rel->r_offset >= hstart && rel->r_offset < hend)
12257       {
12258         /* If the entry is in use, do nothing.  */
12259         if (h->vtable->used
12260             && (rel->r_offset - hstart) < h->vtable->size)
12261           {
12262             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12263             if (h->vtable->used[entry])
12264               continue;
12265           }
12266         /* Otherwise, kill it.  */
12267         rel->r_offset = rel->r_info = rel->r_addend = 0;
12268       }
12269
12270   return TRUE;
12271 }
12272
12273 /* Mark sections containing dynamically referenced symbols.  When
12274    building shared libraries, we must assume that any visible symbol is
12275    referenced.  */
12276
12277 bfd_boolean
12278 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12279 {
12280   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12281   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12282
12283   if ((h->root.type == bfd_link_hash_defined
12284        || h->root.type == bfd_link_hash_defweak)
12285       && (h->ref_dynamic
12286           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12287               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12288               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12289               && (!info->executable
12290                   || info->export_dynamic
12291                   || (h->dynamic
12292                       && d != NULL
12293                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12294               && (strchr (h->root.root.string, ELF_VER_CHR) != NULL
12295                   || !bfd_hide_sym_by_version (info->version_info,
12296                                                h->root.root.string)))))
12297     h->root.u.def.section->flags |= SEC_KEEP;
12298
12299   return TRUE;
12300 }
12301
12302 /* Keep all sections containing symbols undefined on the command-line,
12303    and the section containing the entry symbol.  */
12304
12305 void
12306 _bfd_elf_gc_keep (struct bfd_link_info *info)
12307 {
12308   struct bfd_sym_chain *sym;
12309
12310   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12311     {
12312       struct elf_link_hash_entry *h;
12313
12314       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12315                                 FALSE, FALSE, FALSE);
12316
12317       if (h != NULL
12318           && (h->root.type == bfd_link_hash_defined
12319               || h->root.type == bfd_link_hash_defweak)
12320           && !bfd_is_abs_section (h->root.u.def.section))
12321         h->root.u.def.section->flags |= SEC_KEEP;
12322     }
12323 }
12324
12325 /* Do mark and sweep of unused sections.  */
12326
12327 bfd_boolean
12328 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12329 {
12330   bfd_boolean ok = TRUE;
12331   bfd *sub;
12332   elf_gc_mark_hook_fn gc_mark_hook;
12333   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12334   struct elf_link_hash_table *htab;
12335
12336   if (!bed->can_gc_sections
12337       || !is_elf_hash_table (info->hash))
12338     {
12339       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12340       return TRUE;
12341     }
12342
12343   bed->gc_keep (info);
12344   htab = elf_hash_table (info);
12345
12346   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12347      at the .eh_frame section if we can mark the FDEs individually.  */
12348   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12349     {
12350       asection *sec;
12351       struct elf_reloc_cookie cookie;
12352
12353       sec = bfd_get_section_by_name (sub, ".eh_frame");
12354       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12355         {
12356           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12357           if (elf_section_data (sec)->sec_info
12358               && (sec->flags & SEC_LINKER_CREATED) == 0)
12359             elf_eh_frame_section (sub) = sec;
12360           fini_reloc_cookie_for_section (&cookie, sec);
12361           sec = bfd_get_next_section_by_name (sec);
12362         }
12363     }
12364
12365   /* Apply transitive closure to the vtable entry usage info.  */
12366   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12367   if (!ok)
12368     return FALSE;
12369
12370   /* Kill the vtable relocations that were not used.  */
12371   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12372   if (!ok)
12373     return FALSE;
12374
12375   /* Mark dynamically referenced symbols.  */
12376   if (htab->dynamic_sections_created)
12377     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12378
12379   /* Grovel through relocs to find out who stays ...  */
12380   gc_mark_hook = bed->gc_mark_hook;
12381   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12382     {
12383       asection *o;
12384
12385       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12386         continue;
12387
12388       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12389          Also treat note sections as a root, if the section is not part
12390          of a group.  */
12391       for (o = sub->sections; o != NULL; o = o->next)
12392         if (!o->gc_mark
12393             && (o->flags & SEC_EXCLUDE) == 0
12394             && ((o->flags & SEC_KEEP) != 0
12395                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12396                     && elf_next_in_group (o) == NULL )))
12397           {
12398             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12399               return FALSE;
12400           }
12401     }
12402
12403   /* Allow the backend to mark additional target specific sections.  */
12404   bed->gc_mark_extra_sections (info, gc_mark_hook);
12405
12406   /* ... and mark SEC_EXCLUDE for those that go.  */
12407   return elf_gc_sweep (abfd, info);
12408 }
12409 \f
12410 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12411
12412 bfd_boolean
12413 bfd_elf_gc_record_vtinherit (bfd *abfd,
12414                              asection *sec,
12415                              struct elf_link_hash_entry *h,
12416                              bfd_vma offset)
12417 {
12418   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12419   struct elf_link_hash_entry **search, *child;
12420   bfd_size_type extsymcount;
12421   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12422
12423   /* The sh_info field of the symtab header tells us where the
12424      external symbols start.  We don't care about the local symbols at
12425      this point.  */
12426   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12427   if (!elf_bad_symtab (abfd))
12428     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12429
12430   sym_hashes = elf_sym_hashes (abfd);
12431   sym_hashes_end = sym_hashes + extsymcount;
12432
12433   /* Hunt down the child symbol, which is in this section at the same
12434      offset as the relocation.  */
12435   for (search = sym_hashes; search != sym_hashes_end; ++search)
12436     {
12437       if ((child = *search) != NULL
12438           && (child->root.type == bfd_link_hash_defined
12439               || child->root.type == bfd_link_hash_defweak)
12440           && child->root.u.def.section == sec
12441           && child->root.u.def.value == offset)
12442         goto win;
12443     }
12444
12445   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12446                          abfd, sec, (unsigned long) offset);
12447   bfd_set_error (bfd_error_invalid_operation);
12448   return FALSE;
12449
12450  win:
12451   if (!child->vtable)
12452     {
12453       child->vtable = (struct elf_link_virtual_table_entry *)
12454           bfd_zalloc (abfd, sizeof (*child->vtable));
12455       if (!child->vtable)
12456         return FALSE;
12457     }
12458   if (!h)
12459     {
12460       /* This *should* only be the absolute section.  It could potentially
12461          be that someone has defined a non-global vtable though, which
12462          would be bad.  It isn't worth paging in the local symbols to be
12463          sure though; that case should simply be handled by the assembler.  */
12464
12465       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12466     }
12467   else
12468     child->vtable->parent = h;
12469
12470   return TRUE;
12471 }
12472
12473 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12474
12475 bfd_boolean
12476 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12477                            asection *sec ATTRIBUTE_UNUSED,
12478                            struct elf_link_hash_entry *h,
12479                            bfd_vma addend)
12480 {
12481   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12482   unsigned int log_file_align = bed->s->log_file_align;
12483
12484   if (!h->vtable)
12485     {
12486       h->vtable = (struct elf_link_virtual_table_entry *)
12487           bfd_zalloc (abfd, sizeof (*h->vtable));
12488       if (!h->vtable)
12489         return FALSE;
12490     }
12491
12492   if (addend >= h->vtable->size)
12493     {
12494       size_t size, bytes, file_align;
12495       bfd_boolean *ptr = h->vtable->used;
12496
12497       /* While the symbol is undefined, we have to be prepared to handle
12498          a zero size.  */
12499       file_align = 1 << log_file_align;
12500       if (h->root.type == bfd_link_hash_undefined)
12501         size = addend + file_align;
12502       else
12503         {
12504           size = h->size;
12505           if (addend >= size)
12506             {
12507               /* Oops!  We've got a reference past the defined end of
12508                  the table.  This is probably a bug -- shall we warn?  */
12509               size = addend + file_align;
12510             }
12511         }
12512       size = (size + file_align - 1) & -file_align;
12513
12514       /* Allocate one extra entry for use as a "done" flag for the
12515          consolidation pass.  */
12516       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12517
12518       if (ptr)
12519         {
12520           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12521
12522           if (ptr != NULL)
12523             {
12524               size_t oldbytes;
12525
12526               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12527                           * sizeof (bfd_boolean));
12528               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12529             }
12530         }
12531       else
12532         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12533
12534       if (ptr == NULL)
12535         return FALSE;
12536
12537       /* And arrange for that done flag to be at index -1.  */
12538       h->vtable->used = ptr + 1;
12539       h->vtable->size = size;
12540     }
12541
12542   h->vtable->used[addend >> log_file_align] = TRUE;
12543
12544   return TRUE;
12545 }
12546
12547 /* Map an ELF section header flag to its corresponding string.  */
12548 typedef struct
12549 {
12550   char *flag_name;
12551   flagword flag_value;
12552 } elf_flags_to_name_table;
12553
12554 static elf_flags_to_name_table elf_flags_to_names [] =
12555 {
12556   { "SHF_WRITE", SHF_WRITE },
12557   { "SHF_ALLOC", SHF_ALLOC },
12558   { "SHF_EXECINSTR", SHF_EXECINSTR },
12559   { "SHF_MERGE", SHF_MERGE },
12560   { "SHF_STRINGS", SHF_STRINGS },
12561   { "SHF_INFO_LINK", SHF_INFO_LINK},
12562   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12563   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12564   { "SHF_GROUP", SHF_GROUP },
12565   { "SHF_TLS", SHF_TLS },
12566   { "SHF_MASKOS", SHF_MASKOS },
12567   { "SHF_EXCLUDE", SHF_EXCLUDE },
12568 };
12569
12570 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
12571 bfd_boolean
12572 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12573                               struct flag_info *flaginfo,
12574                               asection *section)
12575 {
12576   const bfd_vma sh_flags = elf_section_flags (section);
12577
12578   if (!flaginfo->flags_initialized)
12579     {
12580       bfd *obfd = info->output_bfd;
12581       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12582       struct flag_info_list *tf = flaginfo->flag_list;
12583       int with_hex = 0;
12584       int without_hex = 0;
12585
12586       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
12587         {
12588           unsigned i;
12589           flagword (*lookup) (char *);
12590
12591           lookup = bed->elf_backend_lookup_section_flags_hook;
12592           if (lookup != NULL)
12593             {
12594               flagword hexval = (*lookup) ((char *) tf->name);
12595
12596               if (hexval != 0)
12597                 {
12598                   if (tf->with == with_flags)
12599                     with_hex |= hexval;
12600                   else if (tf->with == without_flags)
12601                     without_hex |= hexval;
12602                   tf->valid = TRUE;
12603                   continue;
12604                 }
12605             }
12606           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
12607             {
12608               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
12609                 {
12610                   if (tf->with == with_flags)
12611                     with_hex |= elf_flags_to_names[i].flag_value;
12612                   else if (tf->with == without_flags)
12613                     without_hex |= elf_flags_to_names[i].flag_value;
12614                   tf->valid = TRUE;
12615                   break;
12616                 }
12617             }
12618           if (!tf->valid)
12619             {
12620               info->callbacks->einfo
12621                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12622               return FALSE;
12623             }
12624         }
12625       flaginfo->flags_initialized = TRUE;
12626       flaginfo->only_with_flags |= with_hex;
12627       flaginfo->not_with_flags |= without_hex;
12628     }
12629
12630   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
12631     return FALSE;
12632
12633   if ((flaginfo->not_with_flags & sh_flags) != 0)
12634     return FALSE;
12635
12636   return TRUE;
12637 }
12638
12639 struct alloc_got_off_arg {
12640   bfd_vma gotoff;
12641   struct bfd_link_info *info;
12642 };
12643
12644 /* We need a special top-level link routine to convert got reference counts
12645    to real got offsets.  */
12646
12647 static bfd_boolean
12648 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12649 {
12650   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12651   bfd *obfd = gofarg->info->output_bfd;
12652   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12653
12654   if (h->got.refcount > 0)
12655     {
12656       h->got.offset = gofarg->gotoff;
12657       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12658     }
12659   else
12660     h->got.offset = (bfd_vma) -1;
12661
12662   return TRUE;
12663 }
12664
12665 /* And an accompanying bit to work out final got entry offsets once
12666    we're done.  Should be called from final_link.  */
12667
12668 bfd_boolean
12669 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12670                                         struct bfd_link_info *info)
12671 {
12672   bfd *i;
12673   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12674   bfd_vma gotoff;
12675   struct alloc_got_off_arg gofarg;
12676
12677   BFD_ASSERT (abfd == info->output_bfd);
12678
12679   if (! is_elf_hash_table (info->hash))
12680     return FALSE;
12681
12682   /* The GOT offset is relative to the .got section, but the GOT header is
12683      put into the .got.plt section, if the backend uses it.  */
12684   if (bed->want_got_plt)
12685     gotoff = 0;
12686   else
12687     gotoff = bed->got_header_size;
12688
12689   /* Do the local .got entries first.  */
12690   for (i = info->input_bfds; i; i = i->link.next)
12691     {
12692       bfd_signed_vma *local_got;
12693       bfd_size_type j, locsymcount;
12694       Elf_Internal_Shdr *symtab_hdr;
12695
12696       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
12697         continue;
12698
12699       local_got = elf_local_got_refcounts (i);
12700       if (!local_got)
12701         continue;
12702
12703       symtab_hdr = &elf_tdata (i)->symtab_hdr;
12704       if (elf_bad_symtab (i))
12705         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12706       else
12707         locsymcount = symtab_hdr->sh_info;
12708
12709       for (j = 0; j < locsymcount; ++j)
12710         {
12711           if (local_got[j] > 0)
12712             {
12713               local_got[j] = gotoff;
12714               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
12715             }
12716           else
12717             local_got[j] = (bfd_vma) -1;
12718         }
12719     }
12720
12721   /* Then the global .got entries.  .plt refcounts are handled by
12722      adjust_dynamic_symbol  */
12723   gofarg.gotoff = gotoff;
12724   gofarg.info = info;
12725   elf_link_hash_traverse (elf_hash_table (info),
12726                           elf_gc_allocate_got_offsets,
12727                           &gofarg);
12728   return TRUE;
12729 }
12730
12731 /* Many folk need no more in the way of final link than this, once
12732    got entry reference counting is enabled.  */
12733
12734 bfd_boolean
12735 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
12736 {
12737   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
12738     return FALSE;
12739
12740   /* Invoke the regular ELF backend linker to do all the work.  */
12741   return bfd_elf_final_link (abfd, info);
12742 }
12743
12744 bfd_boolean
12745 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
12746 {
12747   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
12748
12749   if (rcookie->bad_symtab)
12750     rcookie->rel = rcookie->rels;
12751
12752   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
12753     {
12754       unsigned long r_symndx;
12755
12756       if (! rcookie->bad_symtab)
12757         if (rcookie->rel->r_offset > offset)
12758           return FALSE;
12759       if (rcookie->rel->r_offset != offset)
12760         continue;
12761
12762       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
12763       if (r_symndx == STN_UNDEF)
12764         return TRUE;
12765
12766       if (r_symndx >= rcookie->locsymcount
12767           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12768         {
12769           struct elf_link_hash_entry *h;
12770
12771           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
12772
12773           while (h->root.type == bfd_link_hash_indirect
12774                  || h->root.type == bfd_link_hash_warning)
12775             h = (struct elf_link_hash_entry *) h->root.u.i.link;
12776
12777           if ((h->root.type == bfd_link_hash_defined
12778                || h->root.type == bfd_link_hash_defweak)
12779               && (h->root.u.def.section->owner != rcookie->abfd
12780                   || h->root.u.def.section->kept_section != NULL
12781                   || discarded_section (h->root.u.def.section)))
12782             return TRUE;
12783         }
12784       else
12785         {
12786           /* It's not a relocation against a global symbol,
12787              but it could be a relocation against a local
12788              symbol for a discarded section.  */
12789           asection *isec;
12790           Elf_Internal_Sym *isym;
12791
12792           /* Need to: get the symbol; get the section.  */
12793           isym = &rcookie->locsyms[r_symndx];
12794           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
12795           if (isec != NULL
12796               && (isec->kept_section != NULL
12797                   || discarded_section (isec)))
12798             return TRUE;
12799         }
12800       return FALSE;
12801     }
12802   return FALSE;
12803 }
12804
12805 /* Discard unneeded references to discarded sections.
12806    Returns -1 on error, 1 if any section's size was changed, 0 if
12807    nothing changed.  This function assumes that the relocations are in
12808    sorted order, which is true for all known assemblers.  */
12809
12810 int
12811 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
12812 {
12813   struct elf_reloc_cookie cookie;
12814   asection *o;
12815   bfd *abfd;
12816   int changed = 0;
12817
12818   if (info->traditional_format
12819       || !is_elf_hash_table (info->hash))
12820     return 0;
12821
12822   o = bfd_get_section_by_name (output_bfd, ".stab");
12823   if (o != NULL)
12824     {
12825       asection *i;
12826
12827       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
12828         {
12829           if (i->size == 0
12830               || i->reloc_count == 0
12831               || i->sec_info_type != SEC_INFO_TYPE_STABS)
12832             continue;
12833
12834           abfd = i->owner;
12835           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12836             continue;
12837
12838           if (!init_reloc_cookie_for_section (&cookie, info, i))
12839             return -1;
12840
12841           if (_bfd_discard_section_stabs (abfd, i,
12842                                           elf_section_data (i)->sec_info,
12843                                           bfd_elf_reloc_symbol_deleted_p,
12844                                           &cookie))
12845             changed = 1;
12846
12847           fini_reloc_cookie_for_section (&cookie, i);
12848         }
12849     }
12850
12851   o = bfd_get_section_by_name (output_bfd, ".eh_frame");
12852   if (o != NULL)
12853     {
12854       asection *i;
12855
12856       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
12857         {
12858           if (i->size == 0)
12859             continue;
12860
12861           abfd = i->owner;
12862           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12863             continue;
12864
12865           if (!init_reloc_cookie_for_section (&cookie, info, i))
12866             return -1;
12867
12868           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
12869           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
12870                                                  bfd_elf_reloc_symbol_deleted_p,
12871                                                  &cookie))
12872             changed = 1;
12873
12874           fini_reloc_cookie_for_section (&cookie, i);
12875         }
12876     }
12877
12878   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
12879     {
12880       const struct elf_backend_data *bed;
12881
12882       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12883         continue;
12884
12885       bed = get_elf_backend_data (abfd);
12886
12887       if (bed->elf_backend_discard_info != NULL)
12888         {
12889           if (!init_reloc_cookie (&cookie, info, abfd))
12890             return -1;
12891
12892           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
12893             changed = 1;
12894
12895           fini_reloc_cookie (&cookie, abfd);
12896         }
12897     }
12898
12899   if (info->eh_frame_hdr
12900       && !info->relocatable
12901       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
12902     changed = 1;
12903
12904   return changed;
12905 }
12906
12907 bfd_boolean
12908 _bfd_elf_section_already_linked (bfd *abfd,
12909                                  asection *sec,
12910                                  struct bfd_link_info *info)
12911 {
12912   flagword flags;
12913   const char *name, *key;
12914   struct bfd_section_already_linked *l;
12915   struct bfd_section_already_linked_hash_entry *already_linked_list;
12916
12917   if (sec->output_section == bfd_abs_section_ptr)
12918     return FALSE;
12919
12920   flags = sec->flags;
12921
12922   /* Return if it isn't a linkonce section.  A comdat group section
12923      also has SEC_LINK_ONCE set.  */
12924   if ((flags & SEC_LINK_ONCE) == 0)
12925     return FALSE;
12926
12927   /* Don't put group member sections on our list of already linked
12928      sections.  They are handled as a group via their group section.  */
12929   if (elf_sec_group (sec) != NULL)
12930     return FALSE;
12931
12932   /* For a SHT_GROUP section, use the group signature as the key.  */
12933   name = sec->name;
12934   if ((flags & SEC_GROUP) != 0
12935       && elf_next_in_group (sec) != NULL
12936       && elf_group_name (elf_next_in_group (sec)) != NULL)
12937     key = elf_group_name (elf_next_in_group (sec));
12938   else
12939     {
12940       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
12941       if (CONST_STRNEQ (name, ".gnu.linkonce.")
12942           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
12943         key++;
12944       else
12945         /* Must be a user linkonce section that doesn't follow gcc's
12946            naming convention.  In this case we won't be matching
12947            single member groups.  */
12948         key = name;
12949     }
12950
12951   already_linked_list = bfd_section_already_linked_table_lookup (key);
12952
12953   for (l = already_linked_list->entry; l != NULL; l = l->next)
12954     {
12955       /* We may have 2 different types of sections on the list: group
12956          sections with a signature of <key> (<key> is some string),
12957          and linkonce sections named .gnu.linkonce.<type>.<key>.
12958          Match like sections.  LTO plugin sections are an exception.
12959          They are always named .gnu.linkonce.t.<key> and match either
12960          type of section.  */
12961       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
12962            && ((flags & SEC_GROUP) != 0
12963                || strcmp (name, l->sec->name) == 0))
12964           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
12965         {
12966           /* The section has already been linked.  See if we should
12967              issue a warning.  */
12968           if (!_bfd_handle_already_linked (sec, l, info))
12969             return FALSE;
12970
12971           if (flags & SEC_GROUP)
12972             {
12973               asection *first = elf_next_in_group (sec);
12974               asection *s = first;
12975
12976               while (s != NULL)
12977                 {
12978                   s->output_section = bfd_abs_section_ptr;
12979                   /* Record which group discards it.  */
12980                   s->kept_section = l->sec;
12981                   s = elf_next_in_group (s);
12982                   /* These lists are circular.  */
12983                   if (s == first)
12984                     break;
12985                 }
12986             }
12987
12988           return TRUE;
12989         }
12990     }
12991
12992   /* A single member comdat group section may be discarded by a
12993      linkonce section and vice versa.  */
12994   if ((flags & SEC_GROUP) != 0)
12995     {
12996       asection *first = elf_next_in_group (sec);
12997
12998       if (first != NULL && elf_next_in_group (first) == first)
12999         /* Check this single member group against linkonce sections.  */
13000         for (l = already_linked_list->entry; l != NULL; l = l->next)
13001           if ((l->sec->flags & SEC_GROUP) == 0
13002               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13003             {
13004               first->output_section = bfd_abs_section_ptr;
13005               first->kept_section = l->sec;
13006               sec->output_section = bfd_abs_section_ptr;
13007               break;
13008             }
13009     }
13010   else
13011     /* Check this linkonce section against single member groups.  */
13012     for (l = already_linked_list->entry; l != NULL; l = l->next)
13013       if (l->sec->flags & SEC_GROUP)
13014         {
13015           asection *first = elf_next_in_group (l->sec);
13016
13017           if (first != NULL
13018               && elf_next_in_group (first) == first
13019               && bfd_elf_match_symbols_in_sections (first, sec, info))
13020             {
13021               sec->output_section = bfd_abs_section_ptr;
13022               sec->kept_section = first;
13023               break;
13024             }
13025         }
13026
13027   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13028      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13029      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13030      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13031      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13032      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13033      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13034      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13035      The reverse order cannot happen as there is never a bfd with only the
13036      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13037      matter as here were are looking only for cross-bfd sections.  */
13038
13039   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13040     for (l = already_linked_list->entry; l != NULL; l = l->next)
13041       if ((l->sec->flags & SEC_GROUP) == 0
13042           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13043         {
13044           if (abfd != l->sec->owner)
13045             sec->output_section = bfd_abs_section_ptr;
13046           break;
13047         }
13048
13049   /* This is the first section with this name.  Record it.  */
13050   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13051     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13052   return sec->output_section == bfd_abs_section_ptr;
13053 }
13054
13055 bfd_boolean
13056 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13057 {
13058   return sym->st_shndx == SHN_COMMON;
13059 }
13060
13061 unsigned int
13062 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13063 {
13064   return SHN_COMMON;
13065 }
13066
13067 asection *
13068 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13069 {
13070   return bfd_com_section_ptr;
13071 }
13072
13073 bfd_vma
13074 _bfd_elf_default_got_elt_size (bfd *abfd,
13075                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13076                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13077                                bfd *ibfd ATTRIBUTE_UNUSED,
13078                                unsigned long symndx ATTRIBUTE_UNUSED)
13079 {
13080   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13081   return bed->s->arch_size / 8;
13082 }
13083
13084 /* Routines to support the creation of dynamic relocs.  */
13085
13086 /* Returns the name of the dynamic reloc section associated with SEC.  */
13087
13088 static const char *
13089 get_dynamic_reloc_section_name (bfd *       abfd,
13090                                 asection *  sec,
13091                                 bfd_boolean is_rela)
13092 {
13093   char *name;
13094   const char *old_name = bfd_get_section_name (NULL, sec);
13095   const char *prefix = is_rela ? ".rela" : ".rel";
13096
13097   if (old_name == NULL)
13098     return NULL;
13099
13100   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13101   sprintf (name, "%s%s", prefix, old_name);
13102
13103   return name;
13104 }
13105
13106 /* Returns the dynamic reloc section associated with SEC.
13107    If necessary compute the name of the dynamic reloc section based
13108    on SEC's name (looked up in ABFD's string table) and the setting
13109    of IS_RELA.  */
13110
13111 asection *
13112 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13113                                     asection *  sec,
13114                                     bfd_boolean is_rela)
13115 {
13116   asection * reloc_sec = elf_section_data (sec)->sreloc;
13117
13118   if (reloc_sec == NULL)
13119     {
13120       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13121
13122       if (name != NULL)
13123         {
13124           reloc_sec = bfd_get_linker_section (abfd, name);
13125
13126           if (reloc_sec != NULL)
13127             elf_section_data (sec)->sreloc = reloc_sec;
13128         }
13129     }
13130
13131   return reloc_sec;
13132 }
13133
13134 /* Returns the dynamic reloc section associated with SEC.  If the
13135    section does not exist it is created and attached to the DYNOBJ
13136    bfd and stored in the SRELOC field of SEC's elf_section_data
13137    structure.
13138
13139    ALIGNMENT is the alignment for the newly created section and
13140    IS_RELA defines whether the name should be .rela.<SEC's name>
13141    or .rel.<SEC's name>.  The section name is looked up in the
13142    string table associated with ABFD.  */
13143
13144 asection *
13145 _bfd_elf_make_dynamic_reloc_section (asection *         sec,
13146                                      bfd *              dynobj,
13147                                      unsigned int       alignment,
13148                                      bfd *              abfd,
13149                                      bfd_boolean        is_rela)
13150 {
13151   asection * reloc_sec = elf_section_data (sec)->sreloc;
13152
13153   if (reloc_sec == NULL)
13154     {
13155       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13156
13157       if (name == NULL)
13158         return NULL;
13159
13160       reloc_sec = bfd_get_linker_section (dynobj, name);
13161
13162       if (reloc_sec == NULL)
13163         {
13164           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13165                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13166           if ((sec->flags & SEC_ALLOC) != 0)
13167             flags |= SEC_ALLOC | SEC_LOAD;
13168
13169           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13170           if (reloc_sec != NULL)
13171             {
13172               /* _bfd_elf_get_sec_type_attr chooses a section type by
13173                  name.  Override as it may be wrong, eg. for a user
13174                  section named "auto" we'll get ".relauto" which is
13175                  seen to be a .rela section.  */
13176               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13177               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13178                 reloc_sec = NULL;
13179             }
13180         }
13181
13182       elf_section_data (sec)->sreloc = reloc_sec;
13183     }
13184
13185   return reloc_sec;
13186 }
13187
13188 /* Copy the ELF symbol type and other attributes for a linker script
13189    assignment from HSRC to HDEST.  Generally this should be treated as
13190    if we found a strong non-dynamic definition for HDEST (except that
13191    ld ignores multiple definition errors).  */
13192 void
13193 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13194                                      struct bfd_link_hash_entry *hdest,
13195                                      struct bfd_link_hash_entry *hsrc)
13196 {
13197   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13198   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13199   Elf_Internal_Sym isym;
13200
13201   ehdest->type = ehsrc->type;
13202   ehdest->target_internal = ehsrc->target_internal;
13203
13204   isym.st_other = ehsrc->other;
13205   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13206 }
13207
13208 /* Append a RELA relocation REL to section S in BFD.  */
13209
13210 void
13211 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13212 {
13213   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13214   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13215   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13216   bed->s->swap_reloca_out (abfd, rel, loc);
13217 }
13218
13219 /* Append a REL relocation REL to section S in BFD.  */
13220
13221 void
13222 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13223 {
13224   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13225   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13226   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13227   bed->s->swap_reloc_out (abfd, rel, loc);
13228 }