OSDN Git Service

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