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