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