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