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