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