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