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