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