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