* elf64-ppc.c (ppc64_elf_func_desc_adjust): Don't emit out-of-line
[platform/upstream/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
4    Free Software Foundation, Inc.
5
6    This file is part of BFD, the Binary File Descriptor library.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22
23 #include "sysdep.h"
24 #include "bfd.h"
25 #include "bfdlink.h"
26 #include "libbfd.h"
27 #define ARCH_SIZE 0
28 #include "elf-bfd.h"
29 #include "safe-ctype.h"
30 #include "libiberty.h"
31 #include "objalloc.h"
32
33 /* This struct is used to pass information to routines called via
34    elf_link_hash_traverse which must return failure.  */
35
36 struct elf_info_failed
37 {
38   struct bfd_link_info *info;
39   bfd_boolean failed;
40 };
41
42 /* This structure is used to pass information to
43    _bfd_elf_link_find_version_dependencies.  */
44
45 struct elf_find_verdep_info
46 {
47   /* General link information.  */
48   struct bfd_link_info *info;
49   /* The number of dependencies.  */
50   unsigned int vers;
51   /* Whether we had a failure.  */
52   bfd_boolean failed;
53 };
54
55 static bfd_boolean _bfd_elf_fix_symbol_flags
56   (struct elf_link_hash_entry *, struct elf_info_failed *);
57
58 /* Define a symbol in a dynamic linkage section.  */
59
60 struct elf_link_hash_entry *
61 _bfd_elf_define_linkage_sym (bfd *abfd,
62                              struct bfd_link_info *info,
63                              asection *sec,
64                              const char *name)
65 {
66   struct elf_link_hash_entry *h;
67   struct bfd_link_hash_entry *bh;
68   const struct elf_backend_data *bed;
69
70   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
71   if (h != NULL)
72     {
73       /* Zap symbol defined in an as-needed lib that wasn't linked.
74          This is a symptom of a larger problem:  Absolute symbols
75          defined in shared libraries can't be overridden, because we
76          lose the link to the bfd which is via the symbol section.  */
77       h->root.type = bfd_link_hash_new;
78     }
79
80   bh = &h->root;
81   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
82                                          sec, 0, NULL, FALSE,
83                                          get_elf_backend_data (abfd)->collect,
84                                          &bh))
85     return NULL;
86   h = (struct elf_link_hash_entry *) bh;
87   h->def_regular = 1;
88   h->non_elf = 0;
89   h->type = STT_OBJECT;
90   h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
91
92   bed = get_elf_backend_data (abfd);
93   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
94   return h;
95 }
96
97 bfd_boolean
98 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
99 {
100   flagword flags;
101   asection *s;
102   struct elf_link_hash_entry *h;
103   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
104   struct elf_link_hash_table *htab = elf_hash_table (info);
105
106   /* This function may be called more than once.  */
107   s = bfd_get_section_by_name (abfd, ".got");
108   if (s != NULL && (s->flags & SEC_LINKER_CREATED) != 0)
109     return TRUE;
110
111   flags = bed->dynamic_sec_flags;
112
113   s = bfd_make_section_anyway_with_flags (abfd,
114                                           (bed->rela_plts_and_copies_p
115                                            ? ".rela.got" : ".rel.got"),
116                                           (bed->dynamic_sec_flags
117                                            | SEC_READONLY));
118   if (s == NULL
119       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
120     return FALSE;
121   htab->srelgot = s;
122
123   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
124   if (s == NULL
125       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
126     return FALSE;
127   htab->sgot = s;
128
129   if (bed->want_got_plt)
130     {
131       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
132       if (s == NULL
133           || !bfd_set_section_alignment (abfd, s,
134                                          bed->s->log_file_align))
135         return FALSE;
136       htab->sgotplt = s;
137     }
138
139   /* The first bit of the global offset table is the header.  */
140   s->size += bed->got_header_size;
141
142   if (bed->want_got_sym)
143     {
144       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
145          (or .got.plt) section.  We don't do this in the linker script
146          because we don't want to define the symbol if we are not creating
147          a global offset table.  */
148       h = _bfd_elf_define_linkage_sym (abfd, info, s,
149                                        "_GLOBAL_OFFSET_TABLE_");
150       elf_hash_table (info)->hgot = h;
151       if (h == NULL)
152         return FALSE;
153     }
154
155   return TRUE;
156 }
157 \f
158 /* Create a strtab to hold the dynamic symbol names.  */
159 static bfd_boolean
160 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
161 {
162   struct elf_link_hash_table *hash_table;
163
164   hash_table = elf_hash_table (info);
165   if (hash_table->dynobj == NULL)
166     hash_table->dynobj = abfd;
167
168   if (hash_table->dynstr == NULL)
169     {
170       hash_table->dynstr = _bfd_elf_strtab_init ();
171       if (hash_table->dynstr == NULL)
172         return FALSE;
173     }
174   return TRUE;
175 }
176
177 /* Create some sections which will be filled in with dynamic linking
178    information.  ABFD is an input file which requires dynamic sections
179    to be created.  The dynamic sections take up virtual memory space
180    when the final executable is run, so we need to create them before
181    addresses are assigned to the output sections.  We work out the
182    actual contents and size of these sections later.  */
183
184 bfd_boolean
185 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
186 {
187   flagword flags;
188   asection *s;
189   const struct elf_backend_data *bed;
190
191   if (! is_elf_hash_table (info->hash))
192     return FALSE;
193
194   if (elf_hash_table (info)->dynamic_sections_created)
195     return TRUE;
196
197   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
198     return FALSE;
199
200   abfd = elf_hash_table (info)->dynobj;
201   bed = get_elf_backend_data (abfd);
202
203   flags = bed->dynamic_sec_flags;
204
205   /* A dynamically linked executable has a .interp section, but a
206      shared library does not.  */
207   if (info->executable)
208     {
209       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
210                                               flags | SEC_READONLY);
211       if (s == NULL)
212         return FALSE;
213     }
214
215   /* Create sections to hold version informations.  These are removed
216      if they are not needed.  */
217   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
218                                           flags | SEC_READONLY);
219   if (s == NULL
220       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
221     return FALSE;
222
223   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
224                                           flags | SEC_READONLY);
225   if (s == NULL
226       || ! bfd_set_section_alignment (abfd, s, 1))
227     return FALSE;
228
229   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
230                                           flags | SEC_READONLY);
231   if (s == NULL
232       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
233     return FALSE;
234
235   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
236                                           flags | SEC_READONLY);
237   if (s == NULL
238       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
239     return FALSE;
240
241   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
242                                           flags | SEC_READONLY);
243   if (s == NULL)
244     return FALSE;
245
246   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
247   if (s == NULL
248       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
249     return FALSE;
250
251   /* The special symbol _DYNAMIC is always set to the start of the
252      .dynamic section.  We could set _DYNAMIC in a linker script, but we
253      only want to define it if we are, in fact, creating a .dynamic
254      section.  We don't want to define it if there is no .dynamic
255      section, since on some ELF platforms the start up code examines it
256      to decide how to initialize the process.  */
257   if (!_bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC"))
258     return FALSE;
259
260   if (info->emit_hash)
261     {
262       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
263                                               flags | SEC_READONLY);
264       if (s == NULL
265           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
266         return FALSE;
267       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
268     }
269
270   if (info->emit_gnu_hash)
271     {
272       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
273                                               flags | SEC_READONLY);
274       if (s == NULL
275           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
276         return FALSE;
277       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
278          4 32-bit words followed by variable count of 64-bit words, then
279          variable count of 32-bit words.  */
280       if (bed->s->arch_size == 64)
281         elf_section_data (s)->this_hdr.sh_entsize = 0;
282       else
283         elf_section_data (s)->this_hdr.sh_entsize = 4;
284     }
285
286   /* Let the backend create the rest of the sections.  This lets the
287      backend set the right flags.  The backend will normally create
288      the .got and .plt sections.  */
289   if (bed->elf_backend_create_dynamic_sections == NULL
290       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
291     return FALSE;
292
293   elf_hash_table (info)->dynamic_sections_created = TRUE;
294
295   return TRUE;
296 }
297
298 /* Create dynamic sections when linking against a dynamic object.  */
299
300 bfd_boolean
301 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
302 {
303   flagword flags, pltflags;
304   struct elf_link_hash_entry *h;
305   asection *s;
306   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
307   struct elf_link_hash_table *htab = elf_hash_table (info);
308
309   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
310      .rel[a].bss sections.  */
311   flags = bed->dynamic_sec_flags;
312
313   pltflags = flags;
314   if (bed->plt_not_loaded)
315     /* We do not clear SEC_ALLOC here because we still want the OS to
316        allocate space for the section; it's just that there's nothing
317        to read in from the object file.  */
318     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
319   else
320     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
321   if (bed->plt_readonly)
322     pltflags |= SEC_READONLY;
323
324   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
325   if (s == NULL
326       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
327     return FALSE;
328   htab->splt = s;
329
330   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
331      .plt section.  */
332   if (bed->want_plt_sym)
333     {
334       h = _bfd_elf_define_linkage_sym (abfd, info, s,
335                                        "_PROCEDURE_LINKAGE_TABLE_");
336       elf_hash_table (info)->hplt = h;
337       if (h == NULL)
338         return FALSE;
339     }
340
341   s = bfd_make_section_anyway_with_flags (abfd,
342                                           (bed->rela_plts_and_copies_p
343                                            ? ".rela.plt" : ".rel.plt"),
344                                           flags | SEC_READONLY);
345   if (s == NULL
346       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
347     return FALSE;
348   htab->srelplt = s;
349
350   if (! _bfd_elf_create_got_section (abfd, info))
351     return FALSE;
352
353   if (bed->want_dynbss)
354     {
355       /* The .dynbss section is a place to put symbols which are defined
356          by dynamic objects, are referenced by regular objects, and are
357          not functions.  We must allocate space for them in the process
358          image and use a R_*_COPY reloc to tell the dynamic linker to
359          initialize them at run time.  The linker script puts the .dynbss
360          section into the .bss section of the final image.  */
361       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
362                                               (SEC_ALLOC | SEC_LINKER_CREATED));
363       if (s == NULL)
364         return FALSE;
365
366       /* The .rel[a].bss section holds copy relocs.  This section is not
367          normally needed.  We need to create it here, though, so that the
368          linker will map it to an output section.  We can't just create it
369          only if we need it, because we will not know whether we need it
370          until we have seen all the input files, and the first time the
371          main linker code calls BFD after examining all the input files
372          (size_dynamic_sections) the input sections have already been
373          mapped to the output sections.  If the section turns out not to
374          be needed, we can discard it later.  We will never need this
375          section when generating a shared object, since they do not use
376          copy relocs.  */
377       if (! info->shared)
378         {
379           s = bfd_make_section_anyway_with_flags (abfd,
380                                                   (bed->rela_plts_and_copies_p
381                                                    ? ".rela.bss" : ".rel.bss"),
382                                                   flags | SEC_READONLY);
383           if (s == NULL
384               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
385             return FALSE;
386         }
387     }
388
389   return TRUE;
390 }
391 \f
392 /* Record a new dynamic symbol.  We record the dynamic symbols as we
393    read the input files, since we need to have a list of all of them
394    before we can determine the final sizes of the output sections.
395    Note that we may actually call this function even though we are not
396    going to output any dynamic symbols; in some cases we know that a
397    symbol should be in the dynamic symbol table, but only if there is
398    one.  */
399
400 bfd_boolean
401 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
402                                     struct elf_link_hash_entry *h)
403 {
404   if (h->dynindx == -1)
405     {
406       struct elf_strtab_hash *dynstr;
407       char *p;
408       const char *name;
409       bfd_size_type indx;
410
411       /* XXX: The ABI draft says the linker must turn hidden and
412          internal symbols into STB_LOCAL symbols when producing the
413          DSO. However, if ld.so honors st_other in the dynamic table,
414          this would not be necessary.  */
415       switch (ELF_ST_VISIBILITY (h->other))
416         {
417         case STV_INTERNAL:
418         case STV_HIDDEN:
419           if (h->root.type != bfd_link_hash_undefined
420               && h->root.type != bfd_link_hash_undefweak)
421             {
422               h->forced_local = 1;
423               if (!elf_hash_table (info)->is_relocatable_executable)
424                 return TRUE;
425             }
426
427         default:
428           break;
429         }
430
431       h->dynindx = elf_hash_table (info)->dynsymcount;
432       ++elf_hash_table (info)->dynsymcount;
433
434       dynstr = elf_hash_table (info)->dynstr;
435       if (dynstr == NULL)
436         {
437           /* Create a strtab to hold the dynamic symbol names.  */
438           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
439           if (dynstr == NULL)
440             return FALSE;
441         }
442
443       /* We don't put any version information in the dynamic string
444          table.  */
445       name = h->root.root.string;
446       p = strchr (name, ELF_VER_CHR);
447       if (p != NULL)
448         /* We know that the p points into writable memory.  In fact,
449            there are only a few symbols that have read-only names, being
450            those like _GLOBAL_OFFSET_TABLE_ that are created specially
451            by the backends.  Most symbols will have names pointing into
452            an ELF string table read from a file, or to objalloc memory.  */
453         *p = 0;
454
455       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
456
457       if (p != NULL)
458         *p = ELF_VER_CHR;
459
460       if (indx == (bfd_size_type) -1)
461         return FALSE;
462       h->dynstr_index = indx;
463     }
464
465   return TRUE;
466 }
467 \f
468 /* Mark a symbol dynamic.  */
469
470 static void
471 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
472                                   struct elf_link_hash_entry *h,
473                                   Elf_Internal_Sym *sym)
474 {
475   struct bfd_elf_dynamic_list *d = info->dynamic_list;
476
477   /* It may be called more than once on the same H.  */
478   if(h->dynamic || info->relocatable)
479     return;
480
481   if ((info->dynamic_data
482        && (h->type == STT_OBJECT
483            || (sym != NULL
484                && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
485       || (d != NULL
486           && h->root.type == bfd_link_hash_new
487           && (*d->match) (&d->head, NULL, h->root.root.string)))
488     h->dynamic = 1;
489 }
490
491 /* Record an assignment to a symbol made by a linker script.  We need
492    this in case some dynamic object refers to this symbol.  */
493
494 bfd_boolean
495 bfd_elf_record_link_assignment (bfd *output_bfd,
496                                 struct bfd_link_info *info,
497                                 const char *name,
498                                 bfd_boolean provide,
499                                 bfd_boolean hidden)
500 {
501   struct elf_link_hash_entry *h, *hv;
502   struct elf_link_hash_table *htab;
503   const struct elf_backend_data *bed;
504
505   if (!is_elf_hash_table (info->hash))
506     return TRUE;
507
508   htab = elf_hash_table (info);
509   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
510   if (h == NULL)
511     return provide;
512
513   switch (h->root.type)
514     {
515     case bfd_link_hash_defined:
516     case bfd_link_hash_defweak:
517     case bfd_link_hash_common:
518       break;
519     case bfd_link_hash_undefweak:
520     case bfd_link_hash_undefined:
521       /* Since we're defining the symbol, don't let it seem to have not
522          been defined.  record_dynamic_symbol and size_dynamic_sections
523          may depend on this.  */
524       h->root.type = bfd_link_hash_new;
525       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
526         bfd_link_repair_undef_list (&htab->root);
527       break;
528     case bfd_link_hash_new:
529       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
530       h->non_elf = 0;
531       break;
532     case bfd_link_hash_indirect:
533       /* We had a versioned symbol in a dynamic library.  We make the
534          the versioned symbol point to this one.  */
535       bed = get_elf_backend_data (output_bfd);
536       hv = h;
537       while (hv->root.type == bfd_link_hash_indirect
538              || hv->root.type == bfd_link_hash_warning)
539         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
540       /* We don't need to update h->root.u since linker will set them
541          later.  */
542       h->root.type = bfd_link_hash_undefined;
543       hv->root.type = bfd_link_hash_indirect;
544       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
545       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
546       break;
547     case bfd_link_hash_warning:
548       abort ();
549       break;
550     }
551
552   /* If this symbol is being provided by the linker script, and it is
553      currently defined by a dynamic object, but not by a regular
554      object, then mark it as undefined so that the generic linker will
555      force the correct value.  */
556   if (provide
557       && h->def_dynamic
558       && !h->def_regular)
559     h->root.type = bfd_link_hash_undefined;
560
561   /* If this symbol is not being provided by the linker script, and it is
562      currently defined by a dynamic object, but not by a regular object,
563      then clear out any version information because the symbol will not be
564      associated with the dynamic object any more.  */
565   if (!provide
566       && h->def_dynamic
567       && !h->def_regular)
568     h->verinfo.verdef = NULL;
569
570   h->def_regular = 1;
571
572   if (provide && hidden)
573     {
574       bed = get_elf_backend_data (output_bfd);
575       h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
576       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
577     }
578
579   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
580      and executables.  */
581   if (!info->relocatable
582       && h->dynindx != -1
583       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
584           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
585     h->forced_local = 1;
586
587   if ((h->def_dynamic
588        || h->ref_dynamic
589        || info->shared
590        || (info->executable && elf_hash_table (info)->is_relocatable_executable))
591       && h->dynindx == -1)
592     {
593       if (! bfd_elf_link_record_dynamic_symbol (info, h))
594         return FALSE;
595
596       /* If this is a weak defined symbol, and we know a corresponding
597          real symbol from the same dynamic object, make sure the real
598          symbol is also made into a dynamic symbol.  */
599       if (h->u.weakdef != NULL
600           && h->u.weakdef->dynindx == -1)
601         {
602           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
603             return FALSE;
604         }
605     }
606
607   return TRUE;
608 }
609
610 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
611    success, and 2 on a failure caused by attempting to record a symbol
612    in a discarded section, eg. a discarded link-once section symbol.  */
613
614 int
615 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
616                                           bfd *input_bfd,
617                                           long input_indx)
618 {
619   bfd_size_type amt;
620   struct elf_link_local_dynamic_entry *entry;
621   struct elf_link_hash_table *eht;
622   struct elf_strtab_hash *dynstr;
623   unsigned long dynstr_index;
624   char *name;
625   Elf_External_Sym_Shndx eshndx;
626   char esym[sizeof (Elf64_External_Sym)];
627
628   if (! is_elf_hash_table (info->hash))
629     return 0;
630
631   /* See if the entry exists already.  */
632   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
633     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
634       return 1;
635
636   amt = sizeof (*entry);
637   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
638   if (entry == NULL)
639     return 0;
640
641   /* Go find the symbol, so that we can find it's name.  */
642   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
643                              1, input_indx, &entry->isym, esym, &eshndx))
644     {
645       bfd_release (input_bfd, entry);
646       return 0;
647     }
648
649   if (entry->isym.st_shndx != SHN_UNDEF
650       && entry->isym.st_shndx < SHN_LORESERVE)
651     {
652       asection *s;
653
654       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
655       if (s == NULL || bfd_is_abs_section (s->output_section))
656         {
657           /* We can still bfd_release here as nothing has done another
658              bfd_alloc.  We can't do this later in this function.  */
659           bfd_release (input_bfd, entry);
660           return 2;
661         }
662     }
663
664   name = (bfd_elf_string_from_elf_section
665           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
666            entry->isym.st_name));
667
668   dynstr = elf_hash_table (info)->dynstr;
669   if (dynstr == NULL)
670     {
671       /* Create a strtab to hold the dynamic symbol names.  */
672       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
673       if (dynstr == NULL)
674         return 0;
675     }
676
677   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
678   if (dynstr_index == (unsigned long) -1)
679     return 0;
680   entry->isym.st_name = dynstr_index;
681
682   eht = elf_hash_table (info);
683
684   entry->next = eht->dynlocal;
685   eht->dynlocal = entry;
686   entry->input_bfd = input_bfd;
687   entry->input_indx = input_indx;
688   eht->dynsymcount++;
689
690   /* Whatever binding the symbol had before, it's now local.  */
691   entry->isym.st_info
692     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
693
694   /* The dynindx will be set at the end of size_dynamic_sections.  */
695
696   return 1;
697 }
698
699 /* Return the dynindex of a local dynamic symbol.  */
700
701 long
702 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
703                                     bfd *input_bfd,
704                                     long input_indx)
705 {
706   struct elf_link_local_dynamic_entry *e;
707
708   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
709     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
710       return e->dynindx;
711   return -1;
712 }
713
714 /* This function is used to renumber the dynamic symbols, if some of
715    them are removed because they are marked as local.  This is called
716    via elf_link_hash_traverse.  */
717
718 static bfd_boolean
719 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
720                                       void *data)
721 {
722   size_t *count = (size_t *) data;
723
724   if (h->forced_local)
725     return TRUE;
726
727   if (h->dynindx != -1)
728     h->dynindx = ++(*count);
729
730   return TRUE;
731 }
732
733
734 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
735    STB_LOCAL binding.  */
736
737 static bfd_boolean
738 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
739                                             void *data)
740 {
741   size_t *count = (size_t *) data;
742
743   if (!h->forced_local)
744     return TRUE;
745
746   if (h->dynindx != -1)
747     h->dynindx = ++(*count);
748
749   return TRUE;
750 }
751
752 /* Return true if the dynamic symbol for a given section should be
753    omitted when creating a shared library.  */
754 bfd_boolean
755 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
756                                    struct bfd_link_info *info,
757                                    asection *p)
758 {
759   struct elf_link_hash_table *htab;
760
761   switch (elf_section_data (p)->this_hdr.sh_type)
762     {
763     case SHT_PROGBITS:
764     case SHT_NOBITS:
765       /* If sh_type is yet undecided, assume it could be
766          SHT_PROGBITS/SHT_NOBITS.  */
767     case SHT_NULL:
768       htab = elf_hash_table (info);
769       if (p == htab->tls_sec)
770         return FALSE;
771
772       if (htab->text_index_section != NULL)
773         return p != htab->text_index_section && p != htab->data_index_section;
774
775       if (strcmp (p->name, ".got") == 0
776           || strcmp (p->name, ".got.plt") == 0
777           || strcmp (p->name, ".plt") == 0)
778         {
779           asection *ip;
780
781           if (htab->dynobj != NULL
782               && (ip = bfd_get_section_by_name (htab->dynobj, p->name)) != NULL
783               && (ip->flags & SEC_LINKER_CREATED)
784               && ip->output_section == p)
785             return TRUE;
786         }
787       return FALSE;
788
789       /* There shouldn't be section relative relocations
790          against any other section.  */
791     default:
792       return TRUE;
793     }
794 }
795
796 /* Assign dynsym indices.  In a shared library we generate a section
797    symbol for each output section, which come first.  Next come symbols
798    which have been forced to local binding.  Then all of the back-end
799    allocated local dynamic syms, followed by the rest of the global
800    symbols.  */
801
802 static unsigned long
803 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
804                                 struct bfd_link_info *info,
805                                 unsigned long *section_sym_count)
806 {
807   unsigned long dynsymcount = 0;
808
809   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
810     {
811       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
812       asection *p;
813       for (p = output_bfd->sections; p ; p = p->next)
814         if ((p->flags & SEC_EXCLUDE) == 0
815             && (p->flags & SEC_ALLOC) != 0
816             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
817           elf_section_data (p)->dynindx = ++dynsymcount;
818         else
819           elf_section_data (p)->dynindx = 0;
820     }
821   *section_sym_count = dynsymcount;
822
823   elf_link_hash_traverse (elf_hash_table (info),
824                           elf_link_renumber_local_hash_table_dynsyms,
825                           &dynsymcount);
826
827   if (elf_hash_table (info)->dynlocal)
828     {
829       struct elf_link_local_dynamic_entry *p;
830       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
831         p->dynindx = ++dynsymcount;
832     }
833
834   elf_link_hash_traverse (elf_hash_table (info),
835                           elf_link_renumber_hash_table_dynsyms,
836                           &dynsymcount);
837
838   /* There is an unused NULL entry at the head of the table which
839      we must account for in our count.  Unless there weren't any
840      symbols, which means we'll have no table at all.  */
841   if (dynsymcount != 0)
842     ++dynsymcount;
843
844   elf_hash_table (info)->dynsymcount = dynsymcount;
845   return dynsymcount;
846 }
847
848 /* Merge st_other field.  */
849
850 static void
851 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
852                     Elf_Internal_Sym *isym, bfd_boolean definition,
853                     bfd_boolean dynamic)
854 {
855   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
856
857   /* If st_other has a processor-specific meaning, specific
858      code might be needed here. We never merge the visibility
859      attribute with the one from a dynamic object.  */
860   if (bed->elf_backend_merge_symbol_attribute)
861     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
862                                                 dynamic);
863
864   /* If this symbol has default visibility and the user has requested
865      we not re-export it, then mark it as hidden.  */
866   if (definition
867       && !dynamic
868       && (abfd->no_export
869           || (abfd->my_archive && abfd->my_archive->no_export))
870       && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
871     isym->st_other = (STV_HIDDEN
872                       | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
873
874   if (!dynamic && ELF_ST_VISIBILITY (isym->st_other) != 0)
875     {
876       unsigned char hvis, symvis, other, nvis;
877
878       /* Only merge the visibility. Leave the remainder of the
879          st_other field to elf_backend_merge_symbol_attribute.  */
880       other = h->other & ~ELF_ST_VISIBILITY (-1);
881
882       /* Combine visibilities, using the most constraining one.  */
883       hvis = ELF_ST_VISIBILITY (h->other);
884       symvis = ELF_ST_VISIBILITY (isym->st_other);
885       if (! hvis)
886         nvis = symvis;
887       else if (! symvis)
888         nvis = hvis;
889       else
890         nvis = hvis < symvis ? hvis : symvis;
891
892       h->other = other | nvis;
893     }
894 }
895
896 /* This function is called when we want to define a new symbol.  It
897    handles the various cases which arise when we find a definition in
898    a dynamic object, or when there is already a definition in a
899    dynamic object.  The new symbol is described by NAME, SYM, PSEC,
900    and PVALUE.  We set SYM_HASH to the hash table entry.  We set
901    OVERRIDE if the old symbol is overriding a new definition.  We set
902    TYPE_CHANGE_OK if it is OK for the type to change.  We set
903    SIZE_CHANGE_OK if it is OK for the size to change.  By OK to
904    change, we mean that we shouldn't warn if the type or size does
905    change.  We set POLD_ALIGNMENT if an old common symbol in a dynamic
906    object is overridden by a regular object.  */
907
908 bfd_boolean
909 _bfd_elf_merge_symbol (bfd *abfd,
910                        struct bfd_link_info *info,
911                        const char *name,
912                        Elf_Internal_Sym *sym,
913                        asection **psec,
914                        bfd_vma *pvalue,
915                        unsigned int *pold_alignment,
916                        struct elf_link_hash_entry **sym_hash,
917                        bfd_boolean *skip,
918                        bfd_boolean *override,
919                        bfd_boolean *type_change_ok,
920                        bfd_boolean *size_change_ok)
921 {
922   asection *sec, *oldsec;
923   struct elf_link_hash_entry *h;
924   struct elf_link_hash_entry *flip;
925   int bind;
926   bfd *oldbfd;
927   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
928   bfd_boolean newweak, oldweak, newfunc, oldfunc;
929   const struct elf_backend_data *bed;
930
931   *skip = FALSE;
932   *override = FALSE;
933
934   sec = *psec;
935   bind = ELF_ST_BIND (sym->st_info);
936
937   /* Silently discard TLS symbols from --just-syms.  There's no way to
938      combine a static TLS block with a new TLS block for this executable.  */
939   if (ELF_ST_TYPE (sym->st_info) == STT_TLS
940       && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
941     {
942       *skip = TRUE;
943       return TRUE;
944     }
945
946   if (! bfd_is_und_section (sec))
947     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
948   else
949     h = ((struct elf_link_hash_entry *)
950          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
951   if (h == NULL)
952     return FALSE;
953   *sym_hash = h;
954
955   bed = get_elf_backend_data (abfd);
956
957   /* This code is for coping with dynamic objects, and is only useful
958      if we are doing an ELF link.  */
959   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
960     return TRUE;
961
962   /* For merging, we only care about real symbols.  */
963
964   while (h->root.type == bfd_link_hash_indirect
965          || h->root.type == bfd_link_hash_warning)
966     h = (struct elf_link_hash_entry *) h->root.u.i.link;
967
968   /* We have to check it for every instance since the first few may be
969      refereences and not all compilers emit symbol type for undefined
970      symbols.  */
971   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
972
973   /* If we just created the symbol, mark it as being an ELF symbol.
974      Other than that, there is nothing to do--there is no merge issue
975      with a newly defined symbol--so we just return.  */
976
977   if (h->root.type == bfd_link_hash_new)
978     {
979       h->non_elf = 0;
980       return TRUE;
981     }
982
983   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
984      existing symbol.  */
985
986   switch (h->root.type)
987     {
988     default:
989       oldbfd = NULL;
990       oldsec = NULL;
991       break;
992
993     case bfd_link_hash_undefined:
994     case bfd_link_hash_undefweak:
995       oldbfd = h->root.u.undef.abfd;
996       oldsec = NULL;
997       break;
998
999     case bfd_link_hash_defined:
1000     case bfd_link_hash_defweak:
1001       oldbfd = h->root.u.def.section->owner;
1002       oldsec = h->root.u.def.section;
1003       break;
1004
1005     case bfd_link_hash_common:
1006       oldbfd = h->root.u.c.p->section->owner;
1007       oldsec = h->root.u.c.p->section;
1008       break;
1009     }
1010
1011   /* Differentiate strong and weak symbols.  */
1012   newweak = bind == STB_WEAK;
1013   oldweak = (h->root.type == bfd_link_hash_defweak
1014              || h->root.type == bfd_link_hash_undefweak);
1015
1016   /* In cases involving weak versioned symbols, we may wind up trying
1017      to merge a symbol with itself.  Catch that here, to avoid the
1018      confusion that results if we try to override a symbol with
1019      itself.  The additional tests catch cases like
1020      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1021      dynamic object, which we do want to handle here.  */
1022   if (abfd == oldbfd
1023       && (newweak || oldweak)
1024       && ((abfd->flags & DYNAMIC) == 0
1025           || !h->def_regular))
1026     return TRUE;
1027
1028   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1029      respectively, is from a dynamic object.  */
1030
1031   newdyn = (abfd->flags & DYNAMIC) != 0;
1032
1033   olddyn = FALSE;
1034   if (oldbfd != NULL)
1035     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1036   else if (oldsec != NULL)
1037     {
1038       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1039          indices used by MIPS ELF.  */
1040       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1041     }
1042
1043   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1044      respectively, appear to be a definition rather than reference.  */
1045
1046   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1047
1048   olddef = (h->root.type != bfd_link_hash_undefined
1049             && h->root.type != bfd_link_hash_undefweak
1050             && h->root.type != bfd_link_hash_common);
1051
1052   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1053      respectively, appear to be a function.  */
1054
1055   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1056              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1057
1058   oldfunc = (h->type != STT_NOTYPE
1059              && bed->is_function_type (h->type));
1060
1061   /* When we try to create a default indirect symbol from the dynamic
1062      definition with the default version, we skip it if its type and
1063      the type of existing regular definition mismatch.  We only do it
1064      if the existing regular definition won't be dynamic.  */
1065   if (pold_alignment == NULL
1066       && !info->shared
1067       && !info->export_dynamic
1068       && !h->ref_dynamic
1069       && newdyn
1070       && newdef
1071       && !olddyn
1072       && (olddef || h->root.type == bfd_link_hash_common)
1073       && ELF_ST_TYPE (sym->st_info) != h->type
1074       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1075       && h->type != STT_NOTYPE
1076       && !(newfunc && oldfunc))
1077     {
1078       *skip = TRUE;
1079       return TRUE;
1080     }
1081
1082   /* Plugin symbol type isn't currently set.  Stop bogus errors.  */
1083   if (oldbfd != NULL && (oldbfd->flags & BFD_PLUGIN) != 0)
1084     *type_change_ok = TRUE;
1085
1086   /* Check TLS symbol.  We don't check undefined symbol introduced by
1087      "ld -u".  */
1088   else if (oldbfd != NULL
1089            && ELF_ST_TYPE (sym->st_info) != h->type
1090            && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1091     {
1092       bfd *ntbfd, *tbfd;
1093       bfd_boolean ntdef, tdef;
1094       asection *ntsec, *tsec;
1095
1096       if (h->type == STT_TLS)
1097         {
1098           ntbfd = abfd;
1099           ntsec = sec;
1100           ntdef = newdef;
1101           tbfd = oldbfd;
1102           tsec = oldsec;
1103           tdef = olddef;
1104         }
1105       else
1106         {
1107           ntbfd = oldbfd;
1108           ntsec = oldsec;
1109           ntdef = olddef;
1110           tbfd = abfd;
1111           tsec = sec;
1112           tdef = newdef;
1113         }
1114
1115       if (tdef && ntdef)
1116         (*_bfd_error_handler)
1117           (_("%s: TLS definition in %B section %A mismatches non-TLS definition in %B section %A"),
1118            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1119       else if (!tdef && !ntdef)
1120         (*_bfd_error_handler)
1121           (_("%s: TLS reference in %B mismatches non-TLS reference in %B"),
1122            tbfd, ntbfd, h->root.root.string);
1123       else if (tdef)
1124         (*_bfd_error_handler)
1125           (_("%s: TLS definition in %B section %A mismatches non-TLS reference in %B"),
1126            tbfd, tsec, ntbfd, h->root.root.string);
1127       else
1128         (*_bfd_error_handler)
1129           (_("%s: TLS reference in %B mismatches non-TLS definition in %B section %A"),
1130            tbfd, ntbfd, ntsec, h->root.root.string);
1131
1132       bfd_set_error (bfd_error_bad_value);
1133       return FALSE;
1134     }
1135
1136   /* We need to remember if a symbol has a definition in a dynamic
1137      object or is weak in all dynamic objects. Internal and hidden
1138      visibility will make it unavailable to dynamic objects.  */
1139   if (newdyn && !h->dynamic_def)
1140     {
1141       if (!bfd_is_und_section (sec))
1142         h->dynamic_def = 1;
1143       else
1144         {
1145           /* Check if this symbol is weak in all dynamic objects. If it
1146              is the first time we see it in a dynamic object, we mark
1147              if it is weak. Otherwise, we clear it.  */
1148           if (!h->ref_dynamic)
1149             {
1150               if (bind == STB_WEAK)
1151                 h->dynamic_weak = 1;
1152             }
1153           else if (bind != STB_WEAK)
1154             h->dynamic_weak = 0;
1155         }
1156     }
1157
1158   /* If the old symbol has non-default visibility, we ignore the new
1159      definition from a dynamic object.  */
1160   if (newdyn
1161       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1162       && !bfd_is_und_section (sec))
1163     {
1164       *skip = TRUE;
1165       /* Make sure this symbol is dynamic.  */
1166       h->ref_dynamic = 1;
1167       /* A protected symbol has external availability. Make sure it is
1168          recorded as dynamic.
1169
1170          FIXME: Should we check type and size for protected symbol?  */
1171       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1172         return bfd_elf_link_record_dynamic_symbol (info, h);
1173       else
1174         return TRUE;
1175     }
1176   else if (!newdyn
1177            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1178            && h->def_dynamic)
1179     {
1180       /* If the new symbol with non-default visibility comes from a
1181          relocatable file and the old definition comes from a dynamic
1182          object, we remove the old definition.  */
1183       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1184         {
1185           /* Handle the case where the old dynamic definition is
1186              default versioned.  We need to copy the symbol info from
1187              the symbol with default version to the normal one if it
1188              was referenced before.  */
1189           if (h->ref_regular)
1190             {
1191               struct elf_link_hash_entry *vh = *sym_hash;
1192
1193               vh->root.type = h->root.type;
1194               h->root.type = bfd_link_hash_indirect;
1195               (*bed->elf_backend_copy_indirect_symbol) (info, vh, h);
1196               /* Protected symbols will override the dynamic definition
1197                  with default version.  */
1198               if (ELF_ST_VISIBILITY (sym->st_other) == STV_PROTECTED)
1199                 {
1200                   h->root.u.i.link = (struct bfd_link_hash_entry *) vh;
1201                   vh->dynamic_def = 1;
1202                   vh->ref_dynamic = 1;
1203                 }
1204               else
1205                 {
1206                   h->root.type = vh->root.type;
1207                   vh->ref_dynamic = 0;
1208                   /* We have to hide it here since it was made dynamic
1209                      global with extra bits when the symbol info was
1210                      copied from the old dynamic definition.  */
1211                   (*bed->elf_backend_hide_symbol) (info, vh, TRUE);
1212                 }
1213               h = vh;
1214             }
1215           else
1216             h = *sym_hash;
1217         }
1218
1219       /* If the old symbol was undefined before, then it will still be
1220          on the undefs list.  If the new symbol is undefined or
1221          common, we can't make it bfd_link_hash_new here, because new
1222          undefined or common symbols will be added to the undefs list
1223          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1224          added twice to the undefs list.  Also, if the new symbol is
1225          undefweak then we don't want to lose the strong undef.  */
1226       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1227         {
1228           h->root.type = bfd_link_hash_undefined;
1229           h->root.u.undef.abfd = abfd;
1230         }
1231       else
1232         {
1233           h->root.type = bfd_link_hash_new;
1234           h->root.u.undef.abfd = NULL;
1235         }
1236
1237       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1238         {
1239           /* If the new symbol is hidden or internal, completely undo
1240              any dynamic link state.  */
1241           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1242           h->forced_local = 0;
1243           h->ref_dynamic = 0;
1244         }
1245       else
1246         h->ref_dynamic = 1;
1247       h->def_dynamic = 0;
1248       h->dynamic_def = 0;
1249       /* FIXME: Should we check type and size for protected symbol?  */
1250       h->size = 0;
1251       h->type = 0;
1252       return TRUE;
1253     }
1254
1255   if (bind == STB_GNU_UNIQUE)
1256     h->unique_global = 1;
1257
1258   /* If a new weak symbol definition comes from a regular file and the
1259      old symbol comes from a dynamic library, we treat the new one as
1260      strong.  Similarly, an old weak symbol definition from a regular
1261      file is treated as strong when the new symbol comes from a dynamic
1262      library.  Further, an old weak symbol from a dynamic library is
1263      treated as strong if the new symbol is from a dynamic library.
1264      This reflects the way glibc's ld.so works.
1265
1266      Do this before setting *type_change_ok or *size_change_ok so that
1267      we warn properly when dynamic library symbols are overridden.  */
1268
1269   if (newdef && !newdyn && olddyn)
1270     newweak = FALSE;
1271   if (olddef && newdyn)
1272     oldweak = FALSE;
1273
1274   /* Allow changes between different types of function symbol.  */
1275   if (newfunc && oldfunc)
1276     *type_change_ok = TRUE;
1277
1278   /* It's OK to change the type if either the existing symbol or the
1279      new symbol is weak.  A type change is also OK if the old symbol
1280      is undefined and the new symbol is defined.  */
1281
1282   if (oldweak
1283       || newweak
1284       || (newdef
1285           && h->root.type == bfd_link_hash_undefined))
1286     *type_change_ok = TRUE;
1287
1288   /* It's OK to change the size if either the existing symbol or the
1289      new symbol is weak, or if the old symbol is undefined.  */
1290
1291   if (*type_change_ok
1292       || h->root.type == bfd_link_hash_undefined)
1293     *size_change_ok = TRUE;
1294
1295   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1296      symbol, respectively, appears to be a common symbol in a dynamic
1297      object.  If a symbol appears in an uninitialized section, and is
1298      not weak, and is not a function, then it may be a common symbol
1299      which was resolved when the dynamic object was created.  We want
1300      to treat such symbols specially, because they raise special
1301      considerations when setting the symbol size: if the symbol
1302      appears as a common symbol in a regular object, and the size in
1303      the regular object is larger, we must make sure that we use the
1304      larger size.  This problematic case can always be avoided in C,
1305      but it must be handled correctly when using Fortran shared
1306      libraries.
1307
1308      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1309      likewise for OLDDYNCOMMON and OLDDEF.
1310
1311      Note that this test is just a heuristic, and that it is quite
1312      possible to have an uninitialized symbol in a shared object which
1313      is really a definition, rather than a common symbol.  This could
1314      lead to some minor confusion when the symbol really is a common
1315      symbol in some regular object.  However, I think it will be
1316      harmless.  */
1317
1318   if (newdyn
1319       && newdef
1320       && !newweak
1321       && (sec->flags & SEC_ALLOC) != 0
1322       && (sec->flags & SEC_LOAD) == 0
1323       && sym->st_size > 0
1324       && !newfunc)
1325     newdyncommon = TRUE;
1326   else
1327     newdyncommon = FALSE;
1328
1329   if (olddyn
1330       && olddef
1331       && h->root.type == bfd_link_hash_defined
1332       && h->def_dynamic
1333       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1334       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1335       && h->size > 0
1336       && !oldfunc)
1337     olddyncommon = TRUE;
1338   else
1339     olddyncommon = FALSE;
1340
1341   /* We now know everything about the old and new symbols.  We ask the
1342      backend to check if we can merge them.  */
1343   if (bed->merge_symbol
1344       && !bed->merge_symbol (info, sym_hash, h, sym, psec, pvalue,
1345                              pold_alignment, skip, override,
1346                              type_change_ok, size_change_ok,
1347                              &newdyn, &newdef, &newdyncommon, &newweak,
1348                              abfd, &sec,
1349                              &olddyn, &olddef, &olddyncommon, &oldweak,
1350                              oldbfd, &oldsec))
1351     return FALSE;
1352
1353   /* If both the old and the new symbols look like common symbols in a
1354      dynamic object, set the size of the symbol to the larger of the
1355      two.  */
1356
1357   if (olddyncommon
1358       && newdyncommon
1359       && sym->st_size != h->size)
1360     {
1361       /* Since we think we have two common symbols, issue a multiple
1362          common warning if desired.  Note that we only warn if the
1363          size is different.  If the size is the same, we simply let
1364          the old symbol override the new one as normally happens with
1365          symbols defined in dynamic objects.  */
1366
1367       if (! ((*info->callbacks->multiple_common)
1368              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1369         return FALSE;
1370
1371       if (sym->st_size > h->size)
1372         h->size = sym->st_size;
1373
1374       *size_change_ok = TRUE;
1375     }
1376
1377   /* If we are looking at a dynamic object, and we have found a
1378      definition, we need to see if the symbol was already defined by
1379      some other object.  If so, we want to use the existing
1380      definition, and we do not want to report a multiple symbol
1381      definition error; we do this by clobbering *PSEC to be
1382      bfd_und_section_ptr.
1383
1384      We treat a common symbol as a definition if the symbol in the
1385      shared library is a function, since common symbols always
1386      represent variables; this can cause confusion in principle, but
1387      any such confusion would seem to indicate an erroneous program or
1388      shared library.  We also permit a common symbol in a regular
1389      object to override a weak symbol in a shared object.  */
1390
1391   if (newdyn
1392       && newdef
1393       && (olddef
1394           || (h->root.type == bfd_link_hash_common
1395               && (newweak || newfunc))))
1396     {
1397       *override = TRUE;
1398       newdef = FALSE;
1399       newdyncommon = FALSE;
1400
1401       *psec = sec = bfd_und_section_ptr;
1402       *size_change_ok = TRUE;
1403
1404       /* If we get here when the old symbol is a common symbol, then
1405          we are explicitly letting it override a weak symbol or
1406          function in a dynamic object, and we don't want to warn about
1407          a type change.  If the old symbol is a defined symbol, a type
1408          change warning may still be appropriate.  */
1409
1410       if (h->root.type == bfd_link_hash_common)
1411         *type_change_ok = TRUE;
1412     }
1413
1414   /* Handle the special case of an old common symbol merging with a
1415      new symbol which looks like a common symbol in a shared object.
1416      We change *PSEC and *PVALUE to make the new symbol look like a
1417      common symbol, and let _bfd_generic_link_add_one_symbol do the
1418      right thing.  */
1419
1420   if (newdyncommon
1421       && h->root.type == bfd_link_hash_common)
1422     {
1423       *override = TRUE;
1424       newdef = FALSE;
1425       newdyncommon = FALSE;
1426       *pvalue = sym->st_size;
1427       *psec = sec = bed->common_section (oldsec);
1428       *size_change_ok = TRUE;
1429     }
1430
1431   /* Skip weak definitions of symbols that are already defined.  */
1432   if (newdef && olddef && newweak)
1433     {
1434       /* Don't skip new non-IR weak syms.  */
1435       if (!(oldbfd != NULL
1436             && (oldbfd->flags & BFD_PLUGIN) != 0
1437             && (abfd->flags & BFD_PLUGIN) == 0))
1438         *skip = TRUE;
1439
1440       /* Merge st_other.  If the symbol already has a dynamic index,
1441          but visibility says it should not be visible, turn it into a
1442          local symbol.  */
1443       elf_merge_st_other (abfd, h, sym, newdef, newdyn);
1444       if (h->dynindx != -1)
1445         switch (ELF_ST_VISIBILITY (h->other))
1446           {
1447           case STV_INTERNAL:
1448           case STV_HIDDEN:
1449             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1450             break;
1451           }
1452     }
1453
1454   /* If the old symbol is from a dynamic object, and the new symbol is
1455      a definition which is not from a dynamic object, then the new
1456      symbol overrides the old symbol.  Symbols from regular files
1457      always take precedence over symbols from dynamic objects, even if
1458      they are defined after the dynamic object in the link.
1459
1460      As above, we again permit a common symbol in a regular object to
1461      override a definition in a shared object if the shared object
1462      symbol is a function or is weak.  */
1463
1464   flip = NULL;
1465   if (!newdyn
1466       && (newdef
1467           || (bfd_is_com_section (sec)
1468               && (oldweak || oldfunc)))
1469       && olddyn
1470       && olddef
1471       && h->def_dynamic)
1472     {
1473       /* Change the hash table entry to undefined, and let
1474          _bfd_generic_link_add_one_symbol do the right thing with the
1475          new definition.  */
1476
1477       h->root.type = bfd_link_hash_undefined;
1478       h->root.u.undef.abfd = h->root.u.def.section->owner;
1479       *size_change_ok = TRUE;
1480
1481       olddef = FALSE;
1482       olddyncommon = FALSE;
1483
1484       /* We again permit a type change when a common symbol may be
1485          overriding a function.  */
1486
1487       if (bfd_is_com_section (sec))
1488         {
1489           if (oldfunc)
1490             {
1491               /* If a common symbol overrides a function, make sure
1492                  that it isn't defined dynamically nor has type
1493                  function.  */
1494               h->def_dynamic = 0;
1495               h->type = STT_NOTYPE;
1496             }
1497           *type_change_ok = TRUE;
1498         }
1499
1500       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1501         flip = *sym_hash;
1502       else
1503         /* This union may have been set to be non-NULL when this symbol
1504            was seen in a dynamic object.  We must force the union to be
1505            NULL, so that it is correct for a regular symbol.  */
1506         h->verinfo.vertree = NULL;
1507     }
1508
1509   /* Handle the special case of a new common symbol merging with an
1510      old symbol that looks like it might be a common symbol defined in
1511      a shared object.  Note that we have already handled the case in
1512      which a new common symbol should simply override the definition
1513      in the shared library.  */
1514
1515   if (! newdyn
1516       && bfd_is_com_section (sec)
1517       && olddyncommon)
1518     {
1519       /* It would be best if we could set the hash table entry to a
1520          common symbol, but we don't know what to use for the section
1521          or the alignment.  */
1522       if (! ((*info->callbacks->multiple_common)
1523              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1524         return FALSE;
1525
1526       /* If the presumed common symbol in the dynamic object is
1527          larger, pretend that the new symbol has its size.  */
1528
1529       if (h->size > *pvalue)
1530         *pvalue = h->size;
1531
1532       /* We need to remember the alignment required by the symbol
1533          in the dynamic object.  */
1534       BFD_ASSERT (pold_alignment);
1535       *pold_alignment = h->root.u.def.section->alignment_power;
1536
1537       olddef = FALSE;
1538       olddyncommon = FALSE;
1539
1540       h->root.type = bfd_link_hash_undefined;
1541       h->root.u.undef.abfd = h->root.u.def.section->owner;
1542
1543       *size_change_ok = TRUE;
1544       *type_change_ok = TRUE;
1545
1546       if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1547         flip = *sym_hash;
1548       else
1549         h->verinfo.vertree = NULL;
1550     }
1551
1552   if (flip != NULL)
1553     {
1554       /* Handle the case where we had a versioned symbol in a dynamic
1555          library and now find a definition in a normal object.  In this
1556          case, we make the versioned symbol point to the normal one.  */
1557       flip->root.type = h->root.type;
1558       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1559       h->root.type = bfd_link_hash_indirect;
1560       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1561       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1562       if (h->def_dynamic)
1563         {
1564           h->def_dynamic = 0;
1565           flip->ref_dynamic = 1;
1566         }
1567     }
1568
1569   return TRUE;
1570 }
1571
1572 /* This function is called to create an indirect symbol from the
1573    default for the symbol with the default version if needed. The
1574    symbol is described by H, NAME, SYM, PSEC, VALUE, and OVERRIDE.  We
1575    set DYNSYM if the new indirect symbol is dynamic.  */
1576
1577 static bfd_boolean
1578 _bfd_elf_add_default_symbol (bfd *abfd,
1579                              struct bfd_link_info *info,
1580                              struct elf_link_hash_entry *h,
1581                              const char *name,
1582                              Elf_Internal_Sym *sym,
1583                              asection **psec,
1584                              bfd_vma *value,
1585                              bfd_boolean *dynsym,
1586                              bfd_boolean override)
1587 {
1588   bfd_boolean type_change_ok;
1589   bfd_boolean size_change_ok;
1590   bfd_boolean skip;
1591   char *shortname;
1592   struct elf_link_hash_entry *hi;
1593   struct bfd_link_hash_entry *bh;
1594   const struct elf_backend_data *bed;
1595   bfd_boolean collect;
1596   bfd_boolean dynamic;
1597   char *p;
1598   size_t len, shortlen;
1599   asection *sec;
1600
1601   /* If this symbol has a version, and it is the default version, we
1602      create an indirect symbol from the default name to the fully
1603      decorated name.  This will cause external references which do not
1604      specify a version to be bound to this version of the symbol.  */
1605   p = strchr (name, ELF_VER_CHR);
1606   if (p == NULL || p[1] != ELF_VER_CHR)
1607     return TRUE;
1608
1609   if (override)
1610     {
1611       /* We are overridden by an old definition. We need to check if we
1612          need to create the indirect symbol from the default name.  */
1613       hi = elf_link_hash_lookup (elf_hash_table (info), name, TRUE,
1614                                  FALSE, FALSE);
1615       BFD_ASSERT (hi != NULL);
1616       if (hi == h)
1617         return TRUE;
1618       while (hi->root.type == bfd_link_hash_indirect
1619              || hi->root.type == bfd_link_hash_warning)
1620         {
1621           hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1622           if (hi == h)
1623             return TRUE;
1624         }
1625     }
1626
1627   bed = get_elf_backend_data (abfd);
1628   collect = bed->collect;
1629   dynamic = (abfd->flags & DYNAMIC) != 0;
1630
1631   shortlen = p - name;
1632   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1633   if (shortname == NULL)
1634     return FALSE;
1635   memcpy (shortname, name, shortlen);
1636   shortname[shortlen] = '\0';
1637
1638   /* We are going to create a new symbol.  Merge it with any existing
1639      symbol with this name.  For the purposes of the merge, act as
1640      though we were defining the symbol we just defined, although we
1641      actually going to define an indirect symbol.  */
1642   type_change_ok = FALSE;
1643   size_change_ok = FALSE;
1644   sec = *psec;
1645   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1646                               NULL, &hi, &skip, &override,
1647                               &type_change_ok, &size_change_ok))
1648     return FALSE;
1649
1650   if (skip)
1651     goto nondefault;
1652
1653   if (! override)
1654     {
1655       bh = &hi->root;
1656       if (! (_bfd_generic_link_add_one_symbol
1657              (info, abfd, shortname, BSF_INDIRECT, bfd_ind_section_ptr,
1658               0, name, FALSE, collect, &bh)))
1659         return FALSE;
1660       hi = (struct elf_link_hash_entry *) bh;
1661     }
1662   else
1663     {
1664       /* In this case the symbol named SHORTNAME is overriding the
1665          indirect symbol we want to add.  We were planning on making
1666          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1667          is the name without a version.  NAME is the fully versioned
1668          name, and it is the default version.
1669
1670          Overriding means that we already saw a definition for the
1671          symbol SHORTNAME in a regular object, and it is overriding
1672          the symbol defined in the dynamic object.
1673
1674          When this happens, we actually want to change NAME, the
1675          symbol we just added, to refer to SHORTNAME.  This will cause
1676          references to NAME in the shared object to become references
1677          to SHORTNAME in the regular object.  This is what we expect
1678          when we override a function in a shared object: that the
1679          references in the shared object will be mapped to the
1680          definition in the regular object.  */
1681
1682       while (hi->root.type == bfd_link_hash_indirect
1683              || hi->root.type == bfd_link_hash_warning)
1684         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1685
1686       h->root.type = bfd_link_hash_indirect;
1687       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1688       if (h->def_dynamic)
1689         {
1690           h->def_dynamic = 0;
1691           hi->ref_dynamic = 1;
1692           if (hi->ref_regular
1693               || hi->def_regular)
1694             {
1695               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1696                 return FALSE;
1697             }
1698         }
1699
1700       /* Now set HI to H, so that the following code will set the
1701          other fields correctly.  */
1702       hi = h;
1703     }
1704
1705   /* Check if HI is a warning symbol.  */
1706   if (hi->root.type == bfd_link_hash_warning)
1707     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1708
1709   /* If there is a duplicate definition somewhere, then HI may not
1710      point to an indirect symbol.  We will have reported an error to
1711      the user in that case.  */
1712
1713   if (hi->root.type == bfd_link_hash_indirect)
1714     {
1715       struct elf_link_hash_entry *ht;
1716
1717       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1718       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1719
1720       /* See if the new flags lead us to realize that the symbol must
1721          be dynamic.  */
1722       if (! *dynsym)
1723         {
1724           if (! dynamic)
1725             {
1726               if (! info->executable
1727                   || hi->ref_dynamic)
1728                 *dynsym = TRUE;
1729             }
1730           else
1731             {
1732               if (hi->ref_regular)
1733                 *dynsym = TRUE;
1734             }
1735         }
1736     }
1737
1738   /* We also need to define an indirection from the nondefault version
1739      of the symbol.  */
1740
1741 nondefault:
1742   len = strlen (name);
1743   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1744   if (shortname == NULL)
1745     return FALSE;
1746   memcpy (shortname, name, shortlen);
1747   memcpy (shortname + shortlen, p + 1, len - shortlen);
1748
1749   /* Once again, merge with any existing symbol.  */
1750   type_change_ok = FALSE;
1751   size_change_ok = FALSE;
1752   sec = *psec;
1753   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1754                               NULL, &hi, &skip, &override,
1755                               &type_change_ok, &size_change_ok))
1756     return FALSE;
1757
1758   if (skip)
1759     return TRUE;
1760
1761   if (override)
1762     {
1763       /* Here SHORTNAME is a versioned name, so we don't expect to see
1764          the type of override we do in the case above unless it is
1765          overridden by a versioned definition.  */
1766       if (hi->root.type != bfd_link_hash_defined
1767           && hi->root.type != bfd_link_hash_defweak)
1768         (*_bfd_error_handler)
1769           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1770            abfd, shortname);
1771     }
1772   else
1773     {
1774       bh = &hi->root;
1775       if (! (_bfd_generic_link_add_one_symbol
1776              (info, abfd, shortname, BSF_INDIRECT,
1777               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1778         return FALSE;
1779       hi = (struct elf_link_hash_entry *) bh;
1780
1781       /* If there is a duplicate definition somewhere, then HI may not
1782          point to an indirect symbol.  We will have reported an error
1783          to the user in that case.  */
1784
1785       if (hi->root.type == bfd_link_hash_indirect)
1786         {
1787           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1788
1789           /* See if the new flags lead us to realize that the symbol
1790              must be dynamic.  */
1791           if (! *dynsym)
1792             {
1793               if (! dynamic)
1794                 {
1795                   if (! info->executable
1796                       || hi->ref_dynamic)
1797                     *dynsym = TRUE;
1798                 }
1799               else
1800                 {
1801                   if (hi->ref_regular)
1802                     *dynsym = TRUE;
1803                 }
1804             }
1805         }
1806     }
1807
1808   return TRUE;
1809 }
1810 \f
1811 /* This routine is used to export all defined symbols into the dynamic
1812    symbol table.  It is called via elf_link_hash_traverse.  */
1813
1814 static bfd_boolean
1815 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1816 {
1817   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1818
1819   /* Ignore indirect symbols.  These are added by the versioning code.  */
1820   if (h->root.type == bfd_link_hash_indirect)
1821     return TRUE;
1822
1823   /* Ignore this if we won't export it.  */
1824   if (!eif->info->export_dynamic && !h->dynamic)
1825     return TRUE;
1826
1827   if (h->dynindx == -1
1828       && (h->def_regular || h->ref_regular)
1829       && ! bfd_hide_sym_by_version (eif->info->version_info,
1830                                     h->root.root.string))
1831     {
1832       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1833         {
1834           eif->failed = TRUE;
1835           return FALSE;
1836         }
1837     }
1838
1839   return TRUE;
1840 }
1841 \f
1842 /* Look through the symbols which are defined in other shared
1843    libraries and referenced here.  Update the list of version
1844    dependencies.  This will be put into the .gnu.version_r section.
1845    This function is called via elf_link_hash_traverse.  */
1846
1847 static bfd_boolean
1848 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1849                                          void *data)
1850 {
1851   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1852   Elf_Internal_Verneed *t;
1853   Elf_Internal_Vernaux *a;
1854   bfd_size_type amt;
1855
1856   /* We only care about symbols defined in shared objects with version
1857      information.  */
1858   if (!h->def_dynamic
1859       || h->def_regular
1860       || h->dynindx == -1
1861       || h->verinfo.verdef == NULL)
1862     return TRUE;
1863
1864   /* See if we already know about this version.  */
1865   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1866        t != NULL;
1867        t = t->vn_nextref)
1868     {
1869       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1870         continue;
1871
1872       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1873         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1874           return TRUE;
1875
1876       break;
1877     }
1878
1879   /* This is a new version.  Add it to tree we are building.  */
1880
1881   if (t == NULL)
1882     {
1883       amt = sizeof *t;
1884       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
1885       if (t == NULL)
1886         {
1887           rinfo->failed = TRUE;
1888           return FALSE;
1889         }
1890
1891       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1892       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
1893       elf_tdata (rinfo->info->output_bfd)->verref = t;
1894     }
1895
1896   amt = sizeof *a;
1897   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
1898   if (a == NULL)
1899     {
1900       rinfo->failed = TRUE;
1901       return FALSE;
1902     }
1903
1904   /* Note that we are copying a string pointer here, and testing it
1905      above.  If bfd_elf_string_from_elf_section is ever changed to
1906      discard the string data when low in memory, this will have to be
1907      fixed.  */
1908   a->vna_nodename = h->verinfo.verdef->vd_nodename;
1909
1910   a->vna_flags = h->verinfo.verdef->vd_flags;
1911   a->vna_nextptr = t->vn_auxptr;
1912
1913   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1914   ++rinfo->vers;
1915
1916   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1917
1918   t->vn_auxptr = a;
1919
1920   return TRUE;
1921 }
1922
1923 /* Figure out appropriate versions for all the symbols.  We may not
1924    have the version number script until we have read all of the input
1925    files, so until that point we don't know which symbols should be
1926    local.  This function is called via elf_link_hash_traverse.  */
1927
1928 static bfd_boolean
1929 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
1930 {
1931   struct elf_info_failed *sinfo;
1932   struct bfd_link_info *info;
1933   const struct elf_backend_data *bed;
1934   struct elf_info_failed eif;
1935   char *p;
1936   bfd_size_type amt;
1937
1938   sinfo = (struct elf_info_failed *) data;
1939   info = sinfo->info;
1940
1941   /* Fix the symbol flags.  */
1942   eif.failed = FALSE;
1943   eif.info = info;
1944   if (! _bfd_elf_fix_symbol_flags (h, &eif))
1945     {
1946       if (eif.failed)
1947         sinfo->failed = TRUE;
1948       return FALSE;
1949     }
1950
1951   /* We only need version numbers for symbols defined in regular
1952      objects.  */
1953   if (!h->def_regular)
1954     return TRUE;
1955
1956   bed = get_elf_backend_data (info->output_bfd);
1957   p = strchr (h->root.root.string, ELF_VER_CHR);
1958   if (p != NULL && h->verinfo.vertree == NULL)
1959     {
1960       struct bfd_elf_version_tree *t;
1961       bfd_boolean hidden;
1962
1963       hidden = TRUE;
1964
1965       /* There are two consecutive ELF_VER_CHR characters if this is
1966          not a hidden symbol.  */
1967       ++p;
1968       if (*p == ELF_VER_CHR)
1969         {
1970           hidden = FALSE;
1971           ++p;
1972         }
1973
1974       /* If there is no version string, we can just return out.  */
1975       if (*p == '\0')
1976         {
1977           if (hidden)
1978             h->hidden = 1;
1979           return TRUE;
1980         }
1981
1982       /* Look for the version.  If we find it, it is no longer weak.  */
1983       for (t = sinfo->info->version_info; t != NULL; t = t->next)
1984         {
1985           if (strcmp (t->name, p) == 0)
1986             {
1987               size_t len;
1988               char *alc;
1989               struct bfd_elf_version_expr *d;
1990
1991               len = p - h->root.root.string;
1992               alc = (char *) bfd_malloc (len);
1993               if (alc == NULL)
1994                 {
1995                   sinfo->failed = TRUE;
1996                   return FALSE;
1997                 }
1998               memcpy (alc, h->root.root.string, len - 1);
1999               alc[len - 1] = '\0';
2000               if (alc[len - 2] == ELF_VER_CHR)
2001                 alc[len - 2] = '\0';
2002
2003               h->verinfo.vertree = t;
2004               t->used = TRUE;
2005               d = NULL;
2006
2007               if (t->globals.list != NULL)
2008                 d = (*t->match) (&t->globals, NULL, alc);
2009
2010               /* See if there is anything to force this symbol to
2011                  local scope.  */
2012               if (d == NULL && t->locals.list != NULL)
2013                 {
2014                   d = (*t->match) (&t->locals, NULL, alc);
2015                   if (d != NULL
2016                       && h->dynindx != -1
2017                       && ! info->export_dynamic)
2018                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2019                 }
2020
2021               free (alc);
2022               break;
2023             }
2024         }
2025
2026       /* If we are building an application, we need to create a
2027          version node for this version.  */
2028       if (t == NULL && info->executable)
2029         {
2030           struct bfd_elf_version_tree **pp;
2031           int version_index;
2032
2033           /* If we aren't going to export this symbol, we don't need
2034              to worry about it.  */
2035           if (h->dynindx == -1)
2036             return TRUE;
2037
2038           amt = sizeof *t;
2039           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2040           if (t == NULL)
2041             {
2042               sinfo->failed = TRUE;
2043               return FALSE;
2044             }
2045
2046           t->name = p;
2047           t->name_indx = (unsigned int) -1;
2048           t->used = TRUE;
2049
2050           version_index = 1;
2051           /* Don't count anonymous version tag.  */
2052           if (sinfo->info->version_info != NULL
2053               && sinfo->info->version_info->vernum == 0)
2054             version_index = 0;
2055           for (pp = &sinfo->info->version_info;
2056                *pp != NULL;
2057                pp = &(*pp)->next)
2058             ++version_index;
2059           t->vernum = version_index;
2060
2061           *pp = t;
2062
2063           h->verinfo.vertree = t;
2064         }
2065       else if (t == NULL)
2066         {
2067           /* We could not find the version for a symbol when
2068              generating a shared archive.  Return an error.  */
2069           (*_bfd_error_handler)
2070             (_("%B: version node not found for symbol %s"),
2071              info->output_bfd, h->root.root.string);
2072           bfd_set_error (bfd_error_bad_value);
2073           sinfo->failed = TRUE;
2074           return FALSE;
2075         }
2076
2077       if (hidden)
2078         h->hidden = 1;
2079     }
2080
2081   /* If we don't have a version for this symbol, see if we can find
2082      something.  */
2083   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2084     {
2085       bfd_boolean hide;
2086
2087       h->verinfo.vertree
2088         = bfd_find_version_for_sym (sinfo->info->version_info,
2089                                     h->root.root.string, &hide);
2090       if (h->verinfo.vertree != NULL && hide)
2091         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2092     }
2093
2094   return TRUE;
2095 }
2096 \f
2097 /* Read and swap the relocs from the section indicated by SHDR.  This
2098    may be either a REL or a RELA section.  The relocations are
2099    translated into RELA relocations and stored in INTERNAL_RELOCS,
2100    which should have already been allocated to contain enough space.
2101    The EXTERNAL_RELOCS are a buffer where the external form of the
2102    relocations should be stored.
2103
2104    Returns FALSE if something goes wrong.  */
2105
2106 static bfd_boolean
2107 elf_link_read_relocs_from_section (bfd *abfd,
2108                                    asection *sec,
2109                                    Elf_Internal_Shdr *shdr,
2110                                    void *external_relocs,
2111                                    Elf_Internal_Rela *internal_relocs)
2112 {
2113   const struct elf_backend_data *bed;
2114   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2115   const bfd_byte *erela;
2116   const bfd_byte *erelaend;
2117   Elf_Internal_Rela *irela;
2118   Elf_Internal_Shdr *symtab_hdr;
2119   size_t nsyms;
2120
2121   /* Position ourselves at the start of the section.  */
2122   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2123     return FALSE;
2124
2125   /* Read the relocations.  */
2126   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2127     return FALSE;
2128
2129   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2130   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2131
2132   bed = get_elf_backend_data (abfd);
2133
2134   /* Convert the external relocations to the internal format.  */
2135   if (shdr->sh_entsize == bed->s->sizeof_rel)
2136     swap_in = bed->s->swap_reloc_in;
2137   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2138     swap_in = bed->s->swap_reloca_in;
2139   else
2140     {
2141       bfd_set_error (bfd_error_wrong_format);
2142       return FALSE;
2143     }
2144
2145   erela = (const bfd_byte *) external_relocs;
2146   erelaend = erela + shdr->sh_size;
2147   irela = internal_relocs;
2148   while (erela < erelaend)
2149     {
2150       bfd_vma r_symndx;
2151
2152       (*swap_in) (abfd, erela, irela);
2153       r_symndx = ELF32_R_SYM (irela->r_info);
2154       if (bed->s->arch_size == 64)
2155         r_symndx >>= 24;
2156       if (nsyms > 0)
2157         {
2158           if ((size_t) r_symndx >= nsyms)
2159             {
2160               (*_bfd_error_handler)
2161                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2162                    " for offset 0x%lx in section `%A'"),
2163                  abfd, sec,
2164                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2165               bfd_set_error (bfd_error_bad_value);
2166               return FALSE;
2167             }
2168         }
2169       else if (r_symndx != STN_UNDEF)
2170         {
2171           (*_bfd_error_handler)
2172             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2173                " when the object file has no symbol table"),
2174              abfd, sec,
2175              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2176           bfd_set_error (bfd_error_bad_value);
2177           return FALSE;
2178         }
2179       irela += bed->s->int_rels_per_ext_rel;
2180       erela += shdr->sh_entsize;
2181     }
2182
2183   return TRUE;
2184 }
2185
2186 /* Read and swap the relocs for a section O.  They may have been
2187    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2188    not NULL, they are used as buffers to read into.  They are known to
2189    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2190    the return value is allocated using either malloc or bfd_alloc,
2191    according to the KEEP_MEMORY argument.  If O has two relocation
2192    sections (both REL and RELA relocations), then the REL_HDR
2193    relocations will appear first in INTERNAL_RELOCS, followed by the
2194    RELA_HDR relocations.  */
2195
2196 Elf_Internal_Rela *
2197 _bfd_elf_link_read_relocs (bfd *abfd,
2198                            asection *o,
2199                            void *external_relocs,
2200                            Elf_Internal_Rela *internal_relocs,
2201                            bfd_boolean keep_memory)
2202 {
2203   void *alloc1 = NULL;
2204   Elf_Internal_Rela *alloc2 = NULL;
2205   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2206   struct bfd_elf_section_data *esdo = elf_section_data (o);
2207   Elf_Internal_Rela *internal_rela_relocs;
2208
2209   if (esdo->relocs != NULL)
2210     return esdo->relocs;
2211
2212   if (o->reloc_count == 0)
2213     return NULL;
2214
2215   if (internal_relocs == NULL)
2216     {
2217       bfd_size_type size;
2218
2219       size = o->reloc_count;
2220       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2221       if (keep_memory)
2222         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2223       else
2224         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2225       if (internal_relocs == NULL)
2226         goto error_return;
2227     }
2228
2229   if (external_relocs == NULL)
2230     {
2231       bfd_size_type size = 0;
2232
2233       if (esdo->rel.hdr)
2234         size += esdo->rel.hdr->sh_size;
2235       if (esdo->rela.hdr)
2236         size += esdo->rela.hdr->sh_size;
2237
2238       alloc1 = bfd_malloc (size);
2239       if (alloc1 == NULL)
2240         goto error_return;
2241       external_relocs = alloc1;
2242     }
2243
2244   internal_rela_relocs = internal_relocs;
2245   if (esdo->rel.hdr)
2246     {
2247       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2248                                               external_relocs,
2249                                               internal_relocs))
2250         goto error_return;
2251       external_relocs = (((bfd_byte *) external_relocs)
2252                          + esdo->rel.hdr->sh_size);
2253       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2254                                * bed->s->int_rels_per_ext_rel);
2255     }
2256
2257   if (esdo->rela.hdr
2258       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2259                                               external_relocs,
2260                                               internal_rela_relocs)))
2261     goto error_return;
2262
2263   /* Cache the results for next time, if we can.  */
2264   if (keep_memory)
2265     esdo->relocs = internal_relocs;
2266
2267   if (alloc1 != NULL)
2268     free (alloc1);
2269
2270   /* Don't free alloc2, since if it was allocated we are passing it
2271      back (under the name of internal_relocs).  */
2272
2273   return internal_relocs;
2274
2275  error_return:
2276   if (alloc1 != NULL)
2277     free (alloc1);
2278   if (alloc2 != NULL)
2279     {
2280       if (keep_memory)
2281         bfd_release (abfd, alloc2);
2282       else
2283         free (alloc2);
2284     }
2285   return NULL;
2286 }
2287
2288 /* Compute the size of, and allocate space for, REL_HDR which is the
2289    section header for a section containing relocations for O.  */
2290
2291 static bfd_boolean
2292 _bfd_elf_link_size_reloc_section (bfd *abfd,
2293                                   struct bfd_elf_section_reloc_data *reldata)
2294 {
2295   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2296
2297   /* That allows us to calculate the size of the section.  */
2298   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2299
2300   /* The contents field must last into write_object_contents, so we
2301      allocate it with bfd_alloc rather than malloc.  Also since we
2302      cannot be sure that the contents will actually be filled in,
2303      we zero the allocated space.  */
2304   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2305   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2306     return FALSE;
2307
2308   if (reldata->hashes == NULL && reldata->count)
2309     {
2310       struct elf_link_hash_entry **p;
2311
2312       p = (struct elf_link_hash_entry **)
2313           bfd_zmalloc (reldata->count * sizeof (struct elf_link_hash_entry *));
2314       if (p == NULL)
2315         return FALSE;
2316
2317       reldata->hashes = p;
2318     }
2319
2320   return TRUE;
2321 }
2322
2323 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2324    originated from the section given by INPUT_REL_HDR) to the
2325    OUTPUT_BFD.  */
2326
2327 bfd_boolean
2328 _bfd_elf_link_output_relocs (bfd *output_bfd,
2329                              asection *input_section,
2330                              Elf_Internal_Shdr *input_rel_hdr,
2331                              Elf_Internal_Rela *internal_relocs,
2332                              struct elf_link_hash_entry **rel_hash
2333                                ATTRIBUTE_UNUSED)
2334 {
2335   Elf_Internal_Rela *irela;
2336   Elf_Internal_Rela *irelaend;
2337   bfd_byte *erel;
2338   struct bfd_elf_section_reloc_data *output_reldata;
2339   asection *output_section;
2340   const struct elf_backend_data *bed;
2341   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2342   struct bfd_elf_section_data *esdo;
2343
2344   output_section = input_section->output_section;
2345
2346   bed = get_elf_backend_data (output_bfd);
2347   esdo = elf_section_data (output_section);
2348   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2349     {
2350       output_reldata = &esdo->rel;
2351       swap_out = bed->s->swap_reloc_out;
2352     }
2353   else if (esdo->rela.hdr
2354            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2355     {
2356       output_reldata = &esdo->rela;
2357       swap_out = bed->s->swap_reloca_out;
2358     }
2359   else
2360     {
2361       (*_bfd_error_handler)
2362         (_("%B: relocation size mismatch in %B section %A"),
2363          output_bfd, input_section->owner, input_section);
2364       bfd_set_error (bfd_error_wrong_format);
2365       return FALSE;
2366     }
2367
2368   erel = output_reldata->hdr->contents;
2369   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2370   irela = internal_relocs;
2371   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2372                       * bed->s->int_rels_per_ext_rel);
2373   while (irela < irelaend)
2374     {
2375       (*swap_out) (output_bfd, irela, erel);
2376       irela += bed->s->int_rels_per_ext_rel;
2377       erel += input_rel_hdr->sh_entsize;
2378     }
2379
2380   /* Bump the counter, so that we know where to add the next set of
2381      relocations.  */
2382   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2383
2384   return TRUE;
2385 }
2386 \f
2387 /* Make weak undefined symbols in PIE dynamic.  */
2388
2389 bfd_boolean
2390 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2391                                  struct elf_link_hash_entry *h)
2392 {
2393   if (info->pie
2394       && h->dynindx == -1
2395       && h->root.type == bfd_link_hash_undefweak)
2396     return bfd_elf_link_record_dynamic_symbol (info, h);
2397
2398   return TRUE;
2399 }
2400
2401 /* Fix up the flags for a symbol.  This handles various cases which
2402    can only be fixed after all the input files are seen.  This is
2403    currently called by both adjust_dynamic_symbol and
2404    assign_sym_version, which is unnecessary but perhaps more robust in
2405    the face of future changes.  */
2406
2407 static bfd_boolean
2408 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2409                            struct elf_info_failed *eif)
2410 {
2411   const struct elf_backend_data *bed;
2412
2413   /* If this symbol was mentioned in a non-ELF file, try to set
2414      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2415      permit a non-ELF file to correctly refer to a symbol defined in
2416      an ELF dynamic object.  */
2417   if (h->non_elf)
2418     {
2419       while (h->root.type == bfd_link_hash_indirect)
2420         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2421
2422       if (h->root.type != bfd_link_hash_defined
2423           && h->root.type != bfd_link_hash_defweak)
2424         {
2425           h->ref_regular = 1;
2426           h->ref_regular_nonweak = 1;
2427         }
2428       else
2429         {
2430           if (h->root.u.def.section->owner != NULL
2431               && (bfd_get_flavour (h->root.u.def.section->owner)
2432                   == bfd_target_elf_flavour))
2433             {
2434               h->ref_regular = 1;
2435               h->ref_regular_nonweak = 1;
2436             }
2437           else
2438             h->def_regular = 1;
2439         }
2440
2441       if (h->dynindx == -1
2442           && (h->def_dynamic
2443               || h->ref_dynamic))
2444         {
2445           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2446             {
2447               eif->failed = TRUE;
2448               return FALSE;
2449             }
2450         }
2451     }
2452   else
2453     {
2454       /* Unfortunately, NON_ELF is only correct if the symbol
2455          was first seen in a non-ELF file.  Fortunately, if the symbol
2456          was first seen in an ELF file, we're probably OK unless the
2457          symbol was defined in a non-ELF file.  Catch that case here.
2458          FIXME: We're still in trouble if the symbol was first seen in
2459          a dynamic object, and then later in a non-ELF regular object.  */
2460       if ((h->root.type == bfd_link_hash_defined
2461            || h->root.type == bfd_link_hash_defweak)
2462           && !h->def_regular
2463           && (h->root.u.def.section->owner != NULL
2464               ? (bfd_get_flavour (h->root.u.def.section->owner)
2465                  != bfd_target_elf_flavour)
2466               : (bfd_is_abs_section (h->root.u.def.section)
2467                  && !h->def_dynamic)))
2468         h->def_regular = 1;
2469     }
2470
2471   /* Backend specific symbol fixup.  */
2472   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2473   if (bed->elf_backend_fixup_symbol
2474       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2475     return FALSE;
2476
2477   /* If this is a final link, and the symbol was defined as a common
2478      symbol in a regular object file, and there was no definition in
2479      any dynamic object, then the linker will have allocated space for
2480      the symbol in a common section but the DEF_REGULAR
2481      flag will not have been set.  */
2482   if (h->root.type == bfd_link_hash_defined
2483       && !h->def_regular
2484       && h->ref_regular
2485       && !h->def_dynamic
2486       && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
2487     h->def_regular = 1;
2488
2489   /* If -Bsymbolic was used (which means to bind references to global
2490      symbols to the definition within the shared object), and this
2491      symbol was defined in a regular object, then it actually doesn't
2492      need a PLT entry.  Likewise, if the symbol has non-default
2493      visibility.  If the symbol has hidden or internal visibility, we
2494      will force it local.  */
2495   if (h->needs_plt
2496       && eif->info->shared
2497       && is_elf_hash_table (eif->info->hash)
2498       && (SYMBOLIC_BIND (eif->info, h)
2499           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2500       && h->def_regular)
2501     {
2502       bfd_boolean force_local;
2503
2504       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2505                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2506       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2507     }
2508
2509   /* If a weak undefined symbol has non-default visibility, we also
2510      hide it from the dynamic linker.  */
2511   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2512       && h->root.type == bfd_link_hash_undefweak)
2513     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2514
2515   /* If this is a weak defined symbol in a dynamic object, and we know
2516      the real definition in the dynamic object, copy interesting flags
2517      over to the real definition.  */
2518   if (h->u.weakdef != NULL)
2519     {
2520       /* If the real definition is defined by a regular object file,
2521          don't do anything special.  See the longer description in
2522          _bfd_elf_adjust_dynamic_symbol, below.  */
2523       if (h->u.weakdef->def_regular)
2524         h->u.weakdef = NULL;
2525       else
2526         {
2527           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2528
2529           while (h->root.type == bfd_link_hash_indirect)
2530             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2531
2532           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2533                       || h->root.type == bfd_link_hash_defweak);
2534           BFD_ASSERT (weakdef->def_dynamic);
2535           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2536                       || weakdef->root.type == bfd_link_hash_defweak);
2537           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2538         }
2539     }
2540
2541   return TRUE;
2542 }
2543
2544 /* Make the backend pick a good value for a dynamic symbol.  This is
2545    called via elf_link_hash_traverse, and also calls itself
2546    recursively.  */
2547
2548 static bfd_boolean
2549 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2550 {
2551   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2552   bfd *dynobj;
2553   const struct elf_backend_data *bed;
2554
2555   if (! is_elf_hash_table (eif->info->hash))
2556     return FALSE;
2557
2558   /* Ignore indirect symbols.  These are added by the versioning code.  */
2559   if (h->root.type == bfd_link_hash_indirect)
2560     return TRUE;
2561
2562   /* Fix the symbol flags.  */
2563   if (! _bfd_elf_fix_symbol_flags (h, eif))
2564     return FALSE;
2565
2566   /* If this symbol does not require a PLT entry, and it is not
2567      defined by a dynamic object, or is not referenced by a regular
2568      object, ignore it.  We do have to handle a weak defined symbol,
2569      even if no regular object refers to it, if we decided to add it
2570      to the dynamic symbol table.  FIXME: Do we normally need to worry
2571      about symbols which are defined by one dynamic object and
2572      referenced by another one?  */
2573   if (!h->needs_plt
2574       && h->type != STT_GNU_IFUNC
2575       && (h->def_regular
2576           || !h->def_dynamic
2577           || (!h->ref_regular
2578               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2579     {
2580       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2581       return TRUE;
2582     }
2583
2584   /* If we've already adjusted this symbol, don't do it again.  This
2585      can happen via a recursive call.  */
2586   if (h->dynamic_adjusted)
2587     return TRUE;
2588
2589   /* Don't look at this symbol again.  Note that we must set this
2590      after checking the above conditions, because we may look at a
2591      symbol once, decide not to do anything, and then get called
2592      recursively later after REF_REGULAR is set below.  */
2593   h->dynamic_adjusted = 1;
2594
2595   /* If this is a weak definition, and we know a real definition, and
2596      the real symbol is not itself defined by a regular object file,
2597      then get a good value for the real definition.  We handle the
2598      real symbol first, for the convenience of the backend routine.
2599
2600      Note that there is a confusing case here.  If the real definition
2601      is defined by a regular object file, we don't get the real symbol
2602      from the dynamic object, but we do get the weak symbol.  If the
2603      processor backend uses a COPY reloc, then if some routine in the
2604      dynamic object changes the real symbol, we will not see that
2605      change in the corresponding weak symbol.  This is the way other
2606      ELF linkers work as well, and seems to be a result of the shared
2607      library model.
2608
2609      I will clarify this issue.  Most SVR4 shared libraries define the
2610      variable _timezone and define timezone as a weak synonym.  The
2611      tzset call changes _timezone.  If you write
2612        extern int timezone;
2613        int _timezone = 5;
2614        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2615      you might expect that, since timezone is a synonym for _timezone,
2616      the same number will print both times.  However, if the processor
2617      backend uses a COPY reloc, then actually timezone will be copied
2618      into your process image, and, since you define _timezone
2619      yourself, _timezone will not.  Thus timezone and _timezone will
2620      wind up at different memory locations.  The tzset call will set
2621      _timezone, leaving timezone unchanged.  */
2622
2623   if (h->u.weakdef != NULL)
2624     {
2625       /* If we get to this point, there is an implicit reference to
2626          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2627       h->u.weakdef->ref_regular = 1;
2628
2629       /* Ensure that the backend adjust_dynamic_symbol function sees
2630          H->U.WEAKDEF before H by recursively calling ourselves.  */
2631       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2632         return FALSE;
2633     }
2634
2635   /* If a symbol has no type and no size and does not require a PLT
2636      entry, then we are probably about to do the wrong thing here: we
2637      are probably going to create a COPY reloc for an empty object.
2638      This case can arise when a shared object is built with assembly
2639      code, and the assembly code fails to set the symbol type.  */
2640   if (h->size == 0
2641       && h->type == STT_NOTYPE
2642       && !h->needs_plt)
2643     (*_bfd_error_handler)
2644       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2645        h->root.root.string);
2646
2647   dynobj = elf_hash_table (eif->info)->dynobj;
2648   bed = get_elf_backend_data (dynobj);
2649
2650   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2651     {
2652       eif->failed = TRUE;
2653       return FALSE;
2654     }
2655
2656   return TRUE;
2657 }
2658
2659 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2660    DYNBSS.  */
2661
2662 bfd_boolean
2663 _bfd_elf_adjust_dynamic_copy (struct elf_link_hash_entry *h,
2664                               asection *dynbss)
2665 {
2666   unsigned int power_of_two;
2667   bfd_vma mask;
2668   asection *sec = h->root.u.def.section;
2669
2670   /* The section aligment of definition is the maximum alignment
2671      requirement of symbols defined in the section.  Since we don't
2672      know the symbol alignment requirement, we start with the
2673      maximum alignment and check low bits of the symbol address
2674      for the minimum alignment.  */
2675   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2676   mask = ((bfd_vma) 1 << power_of_two) - 1;
2677   while ((h->root.u.def.value & mask) != 0)
2678     {
2679        mask >>= 1;
2680        --power_of_two;
2681     }
2682
2683   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2684                                                 dynbss))
2685     {
2686       /* Adjust the section alignment if needed.  */
2687       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2688                                        power_of_two))
2689         return FALSE;
2690     }
2691
2692   /* We make sure that the symbol will be aligned properly.  */
2693   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2694
2695   /* Define the symbol as being at this point in DYNBSS.  */
2696   h->root.u.def.section = dynbss;
2697   h->root.u.def.value = dynbss->size;
2698
2699   /* Increment the size of DYNBSS to make room for the symbol.  */
2700   dynbss->size += h->size;
2701
2702   return TRUE;
2703 }
2704
2705 /* Adjust all external symbols pointing into SEC_MERGE sections
2706    to reflect the object merging within the sections.  */
2707
2708 static bfd_boolean
2709 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2710 {
2711   asection *sec;
2712
2713   if ((h->root.type == bfd_link_hash_defined
2714        || h->root.type == bfd_link_hash_defweak)
2715       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2716       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2717     {
2718       bfd *output_bfd = (bfd *) data;
2719
2720       h->root.u.def.value =
2721         _bfd_merged_section_offset (output_bfd,
2722                                     &h->root.u.def.section,
2723                                     elf_section_data (sec)->sec_info,
2724                                     h->root.u.def.value);
2725     }
2726
2727   return TRUE;
2728 }
2729
2730 /* Returns false if the symbol referred to by H should be considered
2731    to resolve local to the current module, and true if it should be
2732    considered to bind dynamically.  */
2733
2734 bfd_boolean
2735 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2736                            struct bfd_link_info *info,
2737                            bfd_boolean not_local_protected)
2738 {
2739   bfd_boolean binding_stays_local_p;
2740   const struct elf_backend_data *bed;
2741   struct elf_link_hash_table *hash_table;
2742
2743   if (h == NULL)
2744     return FALSE;
2745
2746   while (h->root.type == bfd_link_hash_indirect
2747          || h->root.type == bfd_link_hash_warning)
2748     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2749
2750   /* If it was forced local, then clearly it's not dynamic.  */
2751   if (h->dynindx == -1)
2752     return FALSE;
2753   if (h->forced_local)
2754     return FALSE;
2755
2756   /* Identify the cases where name binding rules say that a
2757      visible symbol resolves locally.  */
2758   binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2759
2760   switch (ELF_ST_VISIBILITY (h->other))
2761     {
2762     case STV_INTERNAL:
2763     case STV_HIDDEN:
2764       return FALSE;
2765
2766     case STV_PROTECTED:
2767       hash_table = elf_hash_table (info);
2768       if (!is_elf_hash_table (hash_table))
2769         return FALSE;
2770
2771       bed = get_elf_backend_data (hash_table->dynobj);
2772
2773       /* Proper resolution for function pointer equality may require
2774          that these symbols perhaps be resolved dynamically, even though
2775          we should be resolving them to the current module.  */
2776       if (!not_local_protected || !bed->is_function_type (h->type))
2777         binding_stays_local_p = TRUE;
2778       break;
2779
2780     default:
2781       break;
2782     }
2783
2784   /* If it isn't defined locally, then clearly it's dynamic.  */
2785   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2786     return TRUE;
2787
2788   /* Otherwise, the symbol is dynamic if binding rules don't tell
2789      us that it remains local.  */
2790   return !binding_stays_local_p;
2791 }
2792
2793 /* Return true if the symbol referred to by H should be considered
2794    to resolve local to the current module, and false otherwise.  Differs
2795    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2796    undefined symbols.  The two functions are virtually identical except
2797    for the place where forced_local and dynindx == -1 are tested.  If
2798    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2799    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2800    the symbol is local only for defined symbols.
2801    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2802    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2803    treatment of undefined weak symbols.  For those that do not make
2804    undefined weak symbols dynamic, both functions may return false.  */
2805
2806 bfd_boolean
2807 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2808                               struct bfd_link_info *info,
2809                               bfd_boolean local_protected)
2810 {
2811   const struct elf_backend_data *bed;
2812   struct elf_link_hash_table *hash_table;
2813
2814   /* If it's a local sym, of course we resolve locally.  */
2815   if (h == NULL)
2816     return TRUE;
2817
2818   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2819   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2820       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2821     return TRUE;
2822
2823   /* Common symbols that become definitions don't get the DEF_REGULAR
2824      flag set, so test it first, and don't bail out.  */
2825   if (ELF_COMMON_DEF_P (h))
2826     /* Do nothing.  */;
2827   /* If we don't have a definition in a regular file, then we can't
2828      resolve locally.  The sym is either undefined or dynamic.  */
2829   else if (!h->def_regular)
2830     return FALSE;
2831
2832   /* Forced local symbols resolve locally.  */
2833   if (h->forced_local)
2834     return TRUE;
2835
2836   /* As do non-dynamic symbols.  */
2837   if (h->dynindx == -1)
2838     return TRUE;
2839
2840   /* At this point, we know the symbol is defined and dynamic.  In an
2841      executable it must resolve locally, likewise when building symbolic
2842      shared libraries.  */
2843   if (info->executable || SYMBOLIC_BIND (info, h))
2844     return TRUE;
2845
2846   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2847      with default visibility might not resolve locally.  */
2848   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2849     return FALSE;
2850
2851   hash_table = elf_hash_table (info);
2852   if (!is_elf_hash_table (hash_table))
2853     return TRUE;
2854
2855   bed = get_elf_backend_data (hash_table->dynobj);
2856
2857   /* STV_PROTECTED non-function symbols are local.  */
2858   if (!bed->is_function_type (h->type))
2859     return TRUE;
2860
2861   /* Function pointer equality tests may require that STV_PROTECTED
2862      symbols be treated as dynamic symbols.  If the address of a
2863      function not defined in an executable is set to that function's
2864      plt entry in the executable, then the address of the function in
2865      a shared library must also be the plt entry in the executable.  */
2866   return local_protected;
2867 }
2868
2869 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2870    aligned.  Returns the first TLS output section.  */
2871
2872 struct bfd_section *
2873 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2874 {
2875   struct bfd_section *sec, *tls;
2876   unsigned int align = 0;
2877
2878   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2879     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2880       break;
2881   tls = sec;
2882
2883   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2884     if (sec->alignment_power > align)
2885       align = sec->alignment_power;
2886
2887   elf_hash_table (info)->tls_sec = tls;
2888
2889   /* Ensure the alignment of the first section is the largest alignment,
2890      so that the tls segment starts aligned.  */
2891   if (tls != NULL)
2892     tls->alignment_power = align;
2893
2894   return tls;
2895 }
2896
2897 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2898 static bfd_boolean
2899 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2900                                   Elf_Internal_Sym *sym)
2901 {
2902   const struct elf_backend_data *bed;
2903
2904   /* Local symbols do not count, but target specific ones might.  */
2905   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2906       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2907     return FALSE;
2908
2909   bed = get_elf_backend_data (abfd);
2910   /* Function symbols do not count.  */
2911   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
2912     return FALSE;
2913
2914   /* If the section is undefined, then so is the symbol.  */
2915   if (sym->st_shndx == SHN_UNDEF)
2916     return FALSE;
2917
2918   /* If the symbol is defined in the common section, then
2919      it is a common definition and so does not count.  */
2920   if (bed->common_definition (sym))
2921     return FALSE;
2922
2923   /* If the symbol is in a target specific section then we
2924      must rely upon the backend to tell us what it is.  */
2925   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
2926     /* FIXME - this function is not coded yet:
2927
2928        return _bfd_is_global_symbol_definition (abfd, sym);
2929
2930        Instead for now assume that the definition is not global,
2931        Even if this is wrong, at least the linker will behave
2932        in the same way that it used to do.  */
2933     return FALSE;
2934
2935   return TRUE;
2936 }
2937
2938 /* Search the symbol table of the archive element of the archive ABFD
2939    whose archive map contains a mention of SYMDEF, and determine if
2940    the symbol is defined in this element.  */
2941 static bfd_boolean
2942 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
2943 {
2944   Elf_Internal_Shdr * hdr;
2945   bfd_size_type symcount;
2946   bfd_size_type extsymcount;
2947   bfd_size_type extsymoff;
2948   Elf_Internal_Sym *isymbuf;
2949   Elf_Internal_Sym *isym;
2950   Elf_Internal_Sym *isymend;
2951   bfd_boolean result;
2952
2953   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
2954   if (abfd == NULL)
2955     return FALSE;
2956
2957   if (! bfd_check_format (abfd, bfd_object))
2958     return FALSE;
2959
2960   /* If we have already included the element containing this symbol in the
2961      link then we do not need to include it again.  Just claim that any symbol
2962      it contains is not a definition, so that our caller will not decide to
2963      (re)include this element.  */
2964   if (abfd->archive_pass)
2965     return FALSE;
2966
2967   /* Select the appropriate symbol table.  */
2968   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
2969     hdr = &elf_tdata (abfd)->symtab_hdr;
2970   else
2971     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2972
2973   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
2974
2975   /* The sh_info field of the symtab header tells us where the
2976      external symbols start.  We don't care about the local symbols.  */
2977   if (elf_bad_symtab (abfd))
2978     {
2979       extsymcount = symcount;
2980       extsymoff = 0;
2981     }
2982   else
2983     {
2984       extsymcount = symcount - hdr->sh_info;
2985       extsymoff = hdr->sh_info;
2986     }
2987
2988   if (extsymcount == 0)
2989     return FALSE;
2990
2991   /* Read in the symbol table.  */
2992   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
2993                                   NULL, NULL, NULL);
2994   if (isymbuf == NULL)
2995     return FALSE;
2996
2997   /* Scan the symbol table looking for SYMDEF.  */
2998   result = FALSE;
2999   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3000     {
3001       const char *name;
3002
3003       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3004                                               isym->st_name);
3005       if (name == NULL)
3006         break;
3007
3008       if (strcmp (name, symdef->name) == 0)
3009         {
3010           result = is_global_data_symbol_definition (abfd, isym);
3011           break;
3012         }
3013     }
3014
3015   free (isymbuf);
3016
3017   return result;
3018 }
3019 \f
3020 /* Add an entry to the .dynamic table.  */
3021
3022 bfd_boolean
3023 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3024                             bfd_vma tag,
3025                             bfd_vma val)
3026 {
3027   struct elf_link_hash_table *hash_table;
3028   const struct elf_backend_data *bed;
3029   asection *s;
3030   bfd_size_type newsize;
3031   bfd_byte *newcontents;
3032   Elf_Internal_Dyn dyn;
3033
3034   hash_table = elf_hash_table (info);
3035   if (! is_elf_hash_table (hash_table))
3036     return FALSE;
3037
3038   bed = get_elf_backend_data (hash_table->dynobj);
3039   s = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
3040   BFD_ASSERT (s != NULL);
3041
3042   newsize = s->size + bed->s->sizeof_dyn;
3043   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3044   if (newcontents == NULL)
3045     return FALSE;
3046
3047   dyn.d_tag = tag;
3048   dyn.d_un.d_val = val;
3049   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3050
3051   s->size = newsize;
3052   s->contents = newcontents;
3053
3054   return TRUE;
3055 }
3056
3057 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3058    otherwise just check whether one already exists.  Returns -1 on error,
3059    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3060
3061 static int
3062 elf_add_dt_needed_tag (bfd *abfd,
3063                        struct bfd_link_info *info,
3064                        const char *soname,
3065                        bfd_boolean do_it)
3066 {
3067   struct elf_link_hash_table *hash_table;
3068   bfd_size_type oldsize;
3069   bfd_size_type strindex;
3070
3071   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3072     return -1;
3073
3074   hash_table = elf_hash_table (info);
3075   oldsize = _bfd_elf_strtab_size (hash_table->dynstr);
3076   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3077   if (strindex == (bfd_size_type) -1)
3078     return -1;
3079
3080   if (oldsize == _bfd_elf_strtab_size (hash_table->dynstr))
3081     {
3082       asection *sdyn;
3083       const struct elf_backend_data *bed;
3084       bfd_byte *extdyn;
3085
3086       bed = get_elf_backend_data (hash_table->dynobj);
3087       sdyn = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
3088       if (sdyn != NULL)
3089         for (extdyn = sdyn->contents;
3090              extdyn < sdyn->contents + sdyn->size;
3091              extdyn += bed->s->sizeof_dyn)
3092           {
3093             Elf_Internal_Dyn dyn;
3094
3095             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3096             if (dyn.d_tag == DT_NEEDED
3097                 && dyn.d_un.d_val == strindex)
3098               {
3099                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3100                 return 1;
3101               }
3102           }
3103     }
3104
3105   if (do_it)
3106     {
3107       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3108         return -1;
3109
3110       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3111         return -1;
3112     }
3113   else
3114     /* We were just checking for existence of the tag.  */
3115     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3116
3117   return 0;
3118 }
3119
3120 static bfd_boolean
3121 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3122 {
3123   for (; needed != NULL; needed = needed->next)
3124     if (strcmp (soname, needed->name) == 0)
3125       return TRUE;
3126
3127   return FALSE;
3128 }
3129
3130 /* Sort symbol by value and section.  */
3131 static int
3132 elf_sort_symbol (const void *arg1, const void *arg2)
3133 {
3134   const struct elf_link_hash_entry *h1;
3135   const struct elf_link_hash_entry *h2;
3136   bfd_signed_vma vdiff;
3137
3138   h1 = *(const struct elf_link_hash_entry **) arg1;
3139   h2 = *(const struct elf_link_hash_entry **) arg2;
3140   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3141   if (vdiff != 0)
3142     return vdiff > 0 ? 1 : -1;
3143   else
3144     {
3145       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3146       if (sdiff != 0)
3147         return sdiff > 0 ? 1 : -1;
3148     }
3149   return 0;
3150 }
3151
3152 /* This function is used to adjust offsets into .dynstr for
3153    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3154
3155 static bfd_boolean
3156 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3157 {
3158   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3159
3160   if (h->dynindx != -1)
3161     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3162   return TRUE;
3163 }
3164
3165 /* Assign string offsets in .dynstr, update all structures referencing
3166    them.  */
3167
3168 static bfd_boolean
3169 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3170 {
3171   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3172   struct elf_link_local_dynamic_entry *entry;
3173   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3174   bfd *dynobj = hash_table->dynobj;
3175   asection *sdyn;
3176   bfd_size_type size;
3177   const struct elf_backend_data *bed;
3178   bfd_byte *extdyn;
3179
3180   _bfd_elf_strtab_finalize (dynstr);
3181   size = _bfd_elf_strtab_size (dynstr);
3182
3183   bed = get_elf_backend_data (dynobj);
3184   sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
3185   BFD_ASSERT (sdyn != NULL);
3186
3187   /* Update all .dynamic entries referencing .dynstr strings.  */
3188   for (extdyn = sdyn->contents;
3189        extdyn < sdyn->contents + sdyn->size;
3190        extdyn += bed->s->sizeof_dyn)
3191     {
3192       Elf_Internal_Dyn dyn;
3193
3194       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3195       switch (dyn.d_tag)
3196         {
3197         case DT_STRSZ:
3198           dyn.d_un.d_val = size;
3199           break;
3200         case DT_NEEDED:
3201         case DT_SONAME:
3202         case DT_RPATH:
3203         case DT_RUNPATH:
3204         case DT_FILTER:
3205         case DT_AUXILIARY:
3206         case DT_AUDIT:
3207         case DT_DEPAUDIT:
3208           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3209           break;
3210         default:
3211           continue;
3212         }
3213       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3214     }
3215
3216   /* Now update local dynamic symbols.  */
3217   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3218     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3219                                                   entry->isym.st_name);
3220
3221   /* And the rest of dynamic symbols.  */
3222   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3223
3224   /* Adjust version definitions.  */
3225   if (elf_tdata (output_bfd)->cverdefs)
3226     {
3227       asection *s;
3228       bfd_byte *p;
3229       bfd_size_type i;
3230       Elf_Internal_Verdef def;
3231       Elf_Internal_Verdaux defaux;
3232
3233       s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
3234       p = s->contents;
3235       do
3236         {
3237           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3238                                    &def);
3239           p += sizeof (Elf_External_Verdef);
3240           if (def.vd_aux != sizeof (Elf_External_Verdef))
3241             continue;
3242           for (i = 0; i < def.vd_cnt; ++i)
3243             {
3244               _bfd_elf_swap_verdaux_in (output_bfd,
3245                                         (Elf_External_Verdaux *) p, &defaux);
3246               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3247                                                         defaux.vda_name);
3248               _bfd_elf_swap_verdaux_out (output_bfd,
3249                                          &defaux, (Elf_External_Verdaux *) p);
3250               p += sizeof (Elf_External_Verdaux);
3251             }
3252         }
3253       while (def.vd_next);
3254     }
3255
3256   /* Adjust version references.  */
3257   if (elf_tdata (output_bfd)->verref)
3258     {
3259       asection *s;
3260       bfd_byte *p;
3261       bfd_size_type i;
3262       Elf_Internal_Verneed need;
3263       Elf_Internal_Vernaux needaux;
3264
3265       s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
3266       p = s->contents;
3267       do
3268         {
3269           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3270                                     &need);
3271           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3272           _bfd_elf_swap_verneed_out (output_bfd, &need,
3273                                      (Elf_External_Verneed *) p);
3274           p += sizeof (Elf_External_Verneed);
3275           for (i = 0; i < need.vn_cnt; ++i)
3276             {
3277               _bfd_elf_swap_vernaux_in (output_bfd,
3278                                         (Elf_External_Vernaux *) p, &needaux);
3279               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3280                                                          needaux.vna_name);
3281               _bfd_elf_swap_vernaux_out (output_bfd,
3282                                          &needaux,
3283                                          (Elf_External_Vernaux *) p);
3284               p += sizeof (Elf_External_Vernaux);
3285             }
3286         }
3287       while (need.vn_next);
3288     }
3289
3290   return TRUE;
3291 }
3292 \f
3293 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3294    The default is to only match when the INPUT and OUTPUT are exactly
3295    the same target.  */
3296
3297 bfd_boolean
3298 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3299                                     const bfd_target *output)
3300 {
3301   return input == output;
3302 }
3303
3304 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3305    This version is used when different targets for the same architecture
3306    are virtually identical.  */
3307
3308 bfd_boolean
3309 _bfd_elf_relocs_compatible (const bfd_target *input,
3310                             const bfd_target *output)
3311 {
3312   const struct elf_backend_data *obed, *ibed;
3313
3314   if (input == output)
3315     return TRUE;
3316
3317   ibed = xvec_get_elf_backend_data (input);
3318   obed = xvec_get_elf_backend_data (output);
3319
3320   if (ibed->arch != obed->arch)
3321     return FALSE;
3322
3323   /* If both backends are using this function, deem them compatible.  */
3324   return ibed->relocs_compatible == obed->relocs_compatible;
3325 }
3326
3327 /* Add symbols from an ELF object file to the linker hash table.  */
3328
3329 static bfd_boolean
3330 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3331 {
3332   Elf_Internal_Ehdr *ehdr;
3333   Elf_Internal_Shdr *hdr;
3334   bfd_size_type symcount;
3335   bfd_size_type extsymcount;
3336   bfd_size_type extsymoff;
3337   struct elf_link_hash_entry **sym_hash;
3338   bfd_boolean dynamic;
3339   Elf_External_Versym *extversym = NULL;
3340   Elf_External_Versym *ever;
3341   struct elf_link_hash_entry *weaks;
3342   struct elf_link_hash_entry **nondeflt_vers = NULL;
3343   bfd_size_type nondeflt_vers_cnt = 0;
3344   Elf_Internal_Sym *isymbuf = NULL;
3345   Elf_Internal_Sym *isym;
3346   Elf_Internal_Sym *isymend;
3347   const struct elf_backend_data *bed;
3348   bfd_boolean add_needed;
3349   struct elf_link_hash_table *htab;
3350   bfd_size_type amt;
3351   void *alloc_mark = NULL;
3352   struct bfd_hash_entry **old_table = NULL;
3353   unsigned int old_size = 0;
3354   unsigned int old_count = 0;
3355   void *old_tab = NULL;
3356   void *old_hash;
3357   void *old_ent;
3358   struct bfd_link_hash_entry *old_undefs = NULL;
3359   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3360   long old_dynsymcount = 0;
3361   size_t tabsize = 0;
3362   size_t hashsize = 0;
3363
3364   htab = elf_hash_table (info);
3365   bed = get_elf_backend_data (abfd);
3366
3367   if ((abfd->flags & DYNAMIC) == 0)
3368     dynamic = FALSE;
3369   else
3370     {
3371       dynamic = TRUE;
3372
3373       /* You can't use -r against a dynamic object.  Also, there's no
3374          hope of using a dynamic object which does not exactly match
3375          the format of the output file.  */
3376       if (info->relocatable
3377           || !is_elf_hash_table (htab)
3378           || info->output_bfd->xvec != abfd->xvec)
3379         {
3380           if (info->relocatable)
3381             bfd_set_error (bfd_error_invalid_operation);
3382           else
3383             bfd_set_error (bfd_error_wrong_format);
3384           goto error_return;
3385         }
3386     }
3387
3388   ehdr = elf_elfheader (abfd);
3389   if (info->warn_alternate_em
3390       && bed->elf_machine_code != ehdr->e_machine
3391       && ((bed->elf_machine_alt1 != 0
3392            && ehdr->e_machine == bed->elf_machine_alt1)
3393           || (bed->elf_machine_alt2 != 0
3394               && ehdr->e_machine == bed->elf_machine_alt2)))
3395     info->callbacks->einfo
3396       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3397        ehdr->e_machine, abfd, bed->elf_machine_code);
3398
3399   /* As a GNU extension, any input sections which are named
3400      .gnu.warning.SYMBOL are treated as warning symbols for the given
3401      symbol.  This differs from .gnu.warning sections, which generate
3402      warnings when they are included in an output file.  */
3403   /* PR 12761: Also generate this warning when building shared libraries.  */
3404   if (info->executable || info->shared)
3405     {
3406       asection *s;
3407
3408       for (s = abfd->sections; s != NULL; s = s->next)
3409         {
3410           const char *name;
3411
3412           name = bfd_get_section_name (abfd, s);
3413           if (CONST_STRNEQ (name, ".gnu.warning."))
3414             {
3415               char *msg;
3416               bfd_size_type sz;
3417
3418               name += sizeof ".gnu.warning." - 1;
3419
3420               /* If this is a shared object, then look up the symbol
3421                  in the hash table.  If it is there, and it is already
3422                  been defined, then we will not be using the entry
3423                  from this shared object, so we don't need to warn.
3424                  FIXME: If we see the definition in a regular object
3425                  later on, we will warn, but we shouldn't.  The only
3426                  fix is to keep track of what warnings we are supposed
3427                  to emit, and then handle them all at the end of the
3428                  link.  */
3429               if (dynamic)
3430                 {
3431                   struct elf_link_hash_entry *h;
3432
3433                   h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3434
3435                   /* FIXME: What about bfd_link_hash_common?  */
3436                   if (h != NULL
3437                       && (h->root.type == bfd_link_hash_defined
3438                           || h->root.type == bfd_link_hash_defweak))
3439                     {
3440                       /* We don't want to issue this warning.  Clobber
3441                          the section size so that the warning does not
3442                          get copied into the output file.  */
3443                       s->size = 0;
3444                       continue;
3445                     }
3446                 }
3447
3448               sz = s->size;
3449               msg = (char *) bfd_alloc (abfd, sz + 1);
3450               if (msg == NULL)
3451                 goto error_return;
3452
3453               if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3454                 goto error_return;
3455
3456               msg[sz] = '\0';
3457
3458               if (! (_bfd_generic_link_add_one_symbol
3459                      (info, abfd, name, BSF_WARNING, s, 0, msg,
3460                       FALSE, bed->collect, NULL)))
3461                 goto error_return;
3462
3463               if (! info->relocatable)
3464                 {
3465                   /* Clobber the section size so that the warning does
3466                      not get copied into the output file.  */
3467                   s->size = 0;
3468
3469                   /* Also set SEC_EXCLUDE, so that symbols defined in
3470                      the warning section don't get copied to the output.  */
3471                   s->flags |= SEC_EXCLUDE;
3472                 }
3473             }
3474         }
3475     }
3476
3477   add_needed = TRUE;
3478   if (! dynamic)
3479     {
3480       /* If we are creating a shared library, create all the dynamic
3481          sections immediately.  We need to attach them to something,
3482          so we attach them to this BFD, provided it is the right
3483          format.  FIXME: If there are no input BFD's of the same
3484          format as the output, we can't make a shared library.  */
3485       if (info->shared
3486           && is_elf_hash_table (htab)
3487           && info->output_bfd->xvec == abfd->xvec
3488           && !htab->dynamic_sections_created)
3489         {
3490           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3491             goto error_return;
3492         }
3493     }
3494   else if (!is_elf_hash_table (htab))
3495     goto error_return;
3496   else
3497     {
3498       asection *s;
3499       const char *soname = NULL;
3500       char *audit = NULL;
3501       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3502       int ret;
3503
3504       /* ld --just-symbols and dynamic objects don't mix very well.
3505          ld shouldn't allow it.  */
3506       if ((s = abfd->sections) != NULL
3507           && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
3508         abort ();
3509
3510       /* If this dynamic lib was specified on the command line with
3511          --as-needed in effect, then we don't want to add a DT_NEEDED
3512          tag unless the lib is actually used.  Similary for libs brought
3513          in by another lib's DT_NEEDED.  When --no-add-needed is used
3514          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3515          any dynamic library in DT_NEEDED tags in the dynamic lib at
3516          all.  */
3517       add_needed = (elf_dyn_lib_class (abfd)
3518                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3519                        | DYN_NO_NEEDED)) == 0;
3520
3521       s = bfd_get_section_by_name (abfd, ".dynamic");
3522       if (s != NULL)
3523         {
3524           bfd_byte *dynbuf;
3525           bfd_byte *extdyn;
3526           unsigned int elfsec;
3527           unsigned long shlink;
3528
3529           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3530             {
3531 error_free_dyn:
3532               free (dynbuf);
3533               goto error_return;
3534             }
3535
3536           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3537           if (elfsec == SHN_BAD)
3538             goto error_free_dyn;
3539           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3540
3541           for (extdyn = dynbuf;
3542                extdyn < dynbuf + s->size;
3543                extdyn += bed->s->sizeof_dyn)
3544             {
3545               Elf_Internal_Dyn dyn;
3546
3547               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3548               if (dyn.d_tag == DT_SONAME)
3549                 {
3550                   unsigned int tagv = dyn.d_un.d_val;
3551                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3552                   if (soname == NULL)
3553                     goto error_free_dyn;
3554                 }
3555               if (dyn.d_tag == DT_NEEDED)
3556                 {
3557                   struct bfd_link_needed_list *n, **pn;
3558                   char *fnm, *anm;
3559                   unsigned int tagv = dyn.d_un.d_val;
3560
3561                   amt = sizeof (struct bfd_link_needed_list);
3562                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3563                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3564                   if (n == NULL || fnm == NULL)
3565                     goto error_free_dyn;
3566                   amt = strlen (fnm) + 1;
3567                   anm = (char *) bfd_alloc (abfd, amt);
3568                   if (anm == NULL)
3569                     goto error_free_dyn;
3570                   memcpy (anm, fnm, amt);
3571                   n->name = anm;
3572                   n->by = abfd;
3573                   n->next = NULL;
3574                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3575                     ;
3576                   *pn = n;
3577                 }
3578               if (dyn.d_tag == DT_RUNPATH)
3579                 {
3580                   struct bfd_link_needed_list *n, **pn;
3581                   char *fnm, *anm;
3582                   unsigned int tagv = dyn.d_un.d_val;
3583
3584                   amt = sizeof (struct bfd_link_needed_list);
3585                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3586                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3587                   if (n == NULL || fnm == NULL)
3588                     goto error_free_dyn;
3589                   amt = strlen (fnm) + 1;
3590                   anm = (char *) bfd_alloc (abfd, amt);
3591                   if (anm == NULL)
3592                     goto error_free_dyn;
3593                   memcpy (anm, fnm, amt);
3594                   n->name = anm;
3595                   n->by = abfd;
3596                   n->next = NULL;
3597                   for (pn = & runpath;
3598                        *pn != NULL;
3599                        pn = &(*pn)->next)
3600                     ;
3601                   *pn = n;
3602                 }
3603               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3604               if (!runpath && dyn.d_tag == DT_RPATH)
3605                 {
3606                   struct bfd_link_needed_list *n, **pn;
3607                   char *fnm, *anm;
3608                   unsigned int tagv = dyn.d_un.d_val;
3609
3610                   amt = sizeof (struct bfd_link_needed_list);
3611                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3612                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3613                   if (n == NULL || fnm == NULL)
3614                     goto error_free_dyn;
3615                   amt = strlen (fnm) + 1;
3616                   anm = (char *) bfd_alloc (abfd, amt);
3617                   if (anm == NULL)
3618                     goto error_free_dyn;
3619                   memcpy (anm, fnm, amt);
3620                   n->name = anm;
3621                   n->by = abfd;
3622                   n->next = NULL;
3623                   for (pn = & rpath;
3624                        *pn != NULL;
3625                        pn = &(*pn)->next)
3626                     ;
3627                   *pn = n;
3628                 }
3629               if (dyn.d_tag == DT_AUDIT)
3630                 {
3631                   unsigned int tagv = dyn.d_un.d_val;
3632                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3633                 }
3634             }
3635
3636           free (dynbuf);
3637         }
3638
3639       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3640          frees all more recently bfd_alloc'd blocks as well.  */
3641       if (runpath)
3642         rpath = runpath;
3643
3644       if (rpath)
3645         {
3646           struct bfd_link_needed_list **pn;
3647           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3648             ;
3649           *pn = rpath;
3650         }
3651
3652       /* We do not want to include any of the sections in a dynamic
3653          object in the output file.  We hack by simply clobbering the
3654          list of sections in the BFD.  This could be handled more
3655          cleanly by, say, a new section flag; the existing
3656          SEC_NEVER_LOAD flag is not the one we want, because that one
3657          still implies that the section takes up space in the output
3658          file.  */
3659       bfd_section_list_clear (abfd);
3660
3661       /* Find the name to use in a DT_NEEDED entry that refers to this
3662          object.  If the object has a DT_SONAME entry, we use it.
3663          Otherwise, if the generic linker stuck something in
3664          elf_dt_name, we use that.  Otherwise, we just use the file
3665          name.  */
3666       if (soname == NULL || *soname == '\0')
3667         {
3668           soname = elf_dt_name (abfd);
3669           if (soname == NULL || *soname == '\0')
3670             soname = bfd_get_filename (abfd);
3671         }
3672
3673       /* Save the SONAME because sometimes the linker emulation code
3674          will need to know it.  */
3675       elf_dt_name (abfd) = soname;
3676
3677       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3678       if (ret < 0)
3679         goto error_return;
3680
3681       /* If we have already included this dynamic object in the
3682          link, just ignore it.  There is no reason to include a
3683          particular dynamic object more than once.  */
3684       if (ret > 0)
3685         return TRUE;
3686
3687       /* Save the DT_AUDIT entry for the linker emulation code. */
3688       elf_dt_audit (abfd) = audit; 
3689     }
3690
3691   /* If this is a dynamic object, we always link against the .dynsym
3692      symbol table, not the .symtab symbol table.  The dynamic linker
3693      will only see the .dynsym symbol table, so there is no reason to
3694      look at .symtab for a dynamic object.  */
3695
3696   if (! dynamic || elf_dynsymtab (abfd) == 0)
3697     hdr = &elf_tdata (abfd)->symtab_hdr;
3698   else
3699     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3700
3701   symcount = hdr->sh_size / bed->s->sizeof_sym;
3702
3703   /* The sh_info field of the symtab header tells us where the
3704      external symbols start.  We don't care about the local symbols at
3705      this point.  */
3706   if (elf_bad_symtab (abfd))
3707     {
3708       extsymcount = symcount;
3709       extsymoff = 0;
3710     }
3711   else
3712     {
3713       extsymcount = symcount - hdr->sh_info;
3714       extsymoff = hdr->sh_info;
3715     }
3716
3717   sym_hash = NULL;
3718   if (extsymcount != 0)
3719     {
3720       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3721                                       NULL, NULL, NULL);
3722       if (isymbuf == NULL)
3723         goto error_return;
3724
3725       /* We store a pointer to the hash table entry for each external
3726          symbol.  */
3727       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3728       sym_hash = (struct elf_link_hash_entry **) bfd_alloc (abfd, amt);
3729       if (sym_hash == NULL)
3730         goto error_free_sym;
3731       elf_sym_hashes (abfd) = sym_hash;
3732     }
3733
3734   if (dynamic)
3735     {
3736       /* Read in any version definitions.  */
3737       if (!_bfd_elf_slurp_version_tables (abfd,
3738                                           info->default_imported_symver))
3739         goto error_free_sym;
3740
3741       /* Read in the symbol versions, but don't bother to convert them
3742          to internal format.  */
3743       if (elf_dynversym (abfd) != 0)
3744         {
3745           Elf_Internal_Shdr *versymhdr;
3746
3747           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3748           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3749           if (extversym == NULL)
3750             goto error_free_sym;
3751           amt = versymhdr->sh_size;
3752           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3753               || bfd_bread (extversym, amt, abfd) != amt)
3754             goto error_free_vers;
3755         }
3756     }
3757
3758   /* If we are loading an as-needed shared lib, save the symbol table
3759      state before we start adding symbols.  If the lib turns out
3760      to be unneeded, restore the state.  */
3761   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3762     {
3763       unsigned int i;
3764       size_t entsize;
3765
3766       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3767         {
3768           struct bfd_hash_entry *p;
3769           struct elf_link_hash_entry *h;
3770
3771           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3772             {
3773               h = (struct elf_link_hash_entry *) p;
3774               entsize += htab->root.table.entsize;
3775               if (h->root.type == bfd_link_hash_warning)
3776                 entsize += htab->root.table.entsize;
3777             }
3778         }
3779
3780       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3781       hashsize = extsymcount * sizeof (struct elf_link_hash_entry *);
3782       old_tab = bfd_malloc (tabsize + entsize + hashsize);
3783       if (old_tab == NULL)
3784         goto error_free_vers;
3785
3786       /* Remember the current objalloc pointer, so that all mem for
3787          symbols added can later be reclaimed.  */
3788       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3789       if (alloc_mark == NULL)
3790         goto error_free_vers;
3791
3792       /* Make a special call to the linker "notice" function to
3793          tell it that we are about to handle an as-needed lib.  */
3794       if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
3795                                        notice_as_needed, 0, NULL))
3796         goto error_free_vers;
3797
3798       /* Clone the symbol table and sym hashes.  Remember some
3799          pointers into the symbol table, and dynamic symbol count.  */
3800       old_hash = (char *) old_tab + tabsize;
3801       old_ent = (char *) old_hash + hashsize;
3802       memcpy (old_tab, htab->root.table.table, tabsize);
3803       memcpy (old_hash, sym_hash, hashsize);
3804       old_undefs = htab->root.undefs;
3805       old_undefs_tail = htab->root.undefs_tail;
3806       old_table = htab->root.table.table;
3807       old_size = htab->root.table.size;
3808       old_count = htab->root.table.count;
3809       old_dynsymcount = htab->dynsymcount;
3810
3811       for (i = 0; i < htab->root.table.size; i++)
3812         {
3813           struct bfd_hash_entry *p;
3814           struct elf_link_hash_entry *h;
3815
3816           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3817             {
3818               memcpy (old_ent, p, htab->root.table.entsize);
3819               old_ent = (char *) old_ent + htab->root.table.entsize;
3820               h = (struct elf_link_hash_entry *) p;
3821               if (h->root.type == bfd_link_hash_warning)
3822                 {
3823                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3824                   old_ent = (char *) old_ent + htab->root.table.entsize;
3825                 }
3826             }
3827         }
3828     }
3829
3830   weaks = NULL;
3831   ever = extversym != NULL ? extversym + extsymoff : NULL;
3832   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3833        isym < isymend;
3834        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3835     {
3836       int bind;
3837       bfd_vma value;
3838       asection *sec, *new_sec;
3839       flagword flags;
3840       const char *name;
3841       struct elf_link_hash_entry *h;
3842       bfd_boolean definition;
3843       bfd_boolean size_change_ok;
3844       bfd_boolean type_change_ok;
3845       bfd_boolean new_weakdef;
3846       bfd_boolean override;
3847       bfd_boolean common;
3848       unsigned int old_alignment;
3849       bfd *old_bfd;
3850       bfd * undef_bfd = NULL;
3851
3852       override = FALSE;
3853
3854       flags = BSF_NO_FLAGS;
3855       sec = NULL;
3856       value = isym->st_value;
3857       *sym_hash = NULL;
3858       common = bed->common_definition (isym);
3859
3860       bind = ELF_ST_BIND (isym->st_info);
3861       switch (bind)
3862         {
3863         case STB_LOCAL:
3864           /* This should be impossible, since ELF requires that all
3865              global symbols follow all local symbols, and that sh_info
3866              point to the first global symbol.  Unfortunately, Irix 5
3867              screws this up.  */
3868           continue;
3869
3870         case STB_GLOBAL:
3871           if (isym->st_shndx != SHN_UNDEF && !common)
3872             flags = BSF_GLOBAL;
3873           break;
3874
3875         case STB_WEAK:
3876           flags = BSF_WEAK;
3877           break;
3878
3879         case STB_GNU_UNIQUE:
3880           flags = BSF_GNU_UNIQUE;
3881           break;
3882
3883         default:
3884           /* Leave it up to the processor backend.  */
3885           break;
3886         }
3887
3888       if (isym->st_shndx == SHN_UNDEF)
3889         sec = bfd_und_section_ptr;
3890       else if (isym->st_shndx == SHN_ABS)
3891         sec = bfd_abs_section_ptr;
3892       else if (isym->st_shndx == SHN_COMMON)
3893         {
3894           sec = bfd_com_section_ptr;
3895           /* What ELF calls the size we call the value.  What ELF
3896              calls the value we call the alignment.  */
3897           value = isym->st_size;
3898         }
3899       else
3900         {
3901           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3902           if (sec == NULL)
3903             sec = bfd_abs_section_ptr;
3904           else if (discarded_section (sec))
3905             {
3906               /* Symbols from discarded section are undefined.  We keep
3907                  its visibility.  */
3908               sec = bfd_und_section_ptr;
3909               isym->st_shndx = SHN_UNDEF;
3910             }
3911           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3912             value -= sec->vma;
3913         }
3914
3915       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3916                                               isym->st_name);
3917       if (name == NULL)
3918         goto error_free_vers;
3919
3920       if (isym->st_shndx == SHN_COMMON
3921           && (abfd->flags & BFD_PLUGIN) != 0)
3922         {
3923           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
3924
3925           if (xc == NULL)
3926             {
3927               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
3928                                  | SEC_EXCLUDE);
3929               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
3930               if (xc == NULL)
3931                 goto error_free_vers;
3932             }
3933           sec = xc;
3934         }
3935       else if (isym->st_shndx == SHN_COMMON
3936                && ELF_ST_TYPE (isym->st_info) == STT_TLS
3937                && !info->relocatable)
3938         {
3939           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
3940
3941           if (tcomm == NULL)
3942             {
3943               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
3944                                  | SEC_LINKER_CREATED);
3945               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
3946               if (tcomm == NULL)
3947                 goto error_free_vers;
3948             }
3949           sec = tcomm;
3950         }
3951       else if (bed->elf_add_symbol_hook)
3952         {
3953           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
3954                                              &sec, &value))
3955             goto error_free_vers;
3956
3957           /* The hook function sets the name to NULL if this symbol
3958              should be skipped for some reason.  */
3959           if (name == NULL)
3960             continue;
3961         }
3962
3963       /* Sanity check that all possibilities were handled.  */
3964       if (sec == NULL)
3965         {
3966           bfd_set_error (bfd_error_bad_value);
3967           goto error_free_vers;
3968         }
3969
3970       if (bfd_is_und_section (sec)
3971           || bfd_is_com_section (sec))
3972         definition = FALSE;
3973       else
3974         definition = TRUE;
3975
3976       size_change_ok = FALSE;
3977       type_change_ok = bed->type_change_ok;
3978       old_alignment = 0;
3979       old_bfd = NULL;
3980       new_sec = sec;
3981
3982       if (is_elf_hash_table (htab))
3983         {
3984           Elf_Internal_Versym iver;
3985           unsigned int vernum = 0;
3986           bfd_boolean skip;
3987
3988           /* If this is a definition of a symbol which was previously
3989              referenced in a non-weak manner then make a note of the bfd
3990              that contained the reference.  This is used if we need to
3991              refer to the source of the reference later on.  */
3992           if (! bfd_is_und_section (sec))
3993             {
3994               h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
3995
3996               if (h != NULL
3997                   && h->root.type == bfd_link_hash_undefined
3998                   && h->root.u.undef.abfd)
3999                 undef_bfd = h->root.u.undef.abfd;
4000             }
4001           
4002           if (ever == NULL)
4003             {
4004               if (info->default_imported_symver)
4005                 /* Use the default symbol version created earlier.  */
4006                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4007               else
4008                 iver.vs_vers = 0;
4009             }
4010           else
4011             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4012
4013           vernum = iver.vs_vers & VERSYM_VERSION;
4014
4015           /* If this is a hidden symbol, or if it is not version
4016              1, we append the version name to the symbol name.
4017              However, we do not modify a non-hidden absolute symbol
4018              if it is not a function, because it might be the version
4019              symbol itself.  FIXME: What if it isn't?  */
4020           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4021               || (vernum > 1
4022                   && (!bfd_is_abs_section (sec)
4023                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4024             {
4025               const char *verstr;
4026               size_t namelen, verlen, newlen;
4027               char *newname, *p;
4028
4029               if (isym->st_shndx != SHN_UNDEF)
4030                 {
4031                   if (vernum > elf_tdata (abfd)->cverdefs)
4032                     verstr = NULL;
4033                   else if (vernum > 1)
4034                     verstr =
4035                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4036                   else
4037                     verstr = "";
4038
4039                   if (verstr == NULL)
4040                     {
4041                       (*_bfd_error_handler)
4042                         (_("%B: %s: invalid version %u (max %d)"),
4043                          abfd, name, vernum,
4044                          elf_tdata (abfd)->cverdefs);
4045                       bfd_set_error (bfd_error_bad_value);
4046                       goto error_free_vers;
4047                     }
4048                 }
4049               else
4050                 {
4051                   /* We cannot simply test for the number of
4052                      entries in the VERNEED section since the
4053                      numbers for the needed versions do not start
4054                      at 0.  */
4055                   Elf_Internal_Verneed *t;
4056
4057                   verstr = NULL;
4058                   for (t = elf_tdata (abfd)->verref;
4059                        t != NULL;
4060                        t = t->vn_nextref)
4061                     {
4062                       Elf_Internal_Vernaux *a;
4063
4064                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4065                         {
4066                           if (a->vna_other == vernum)
4067                             {
4068                               verstr = a->vna_nodename;
4069                               break;
4070                             }
4071                         }
4072                       if (a != NULL)
4073                         break;
4074                     }
4075                   if (verstr == NULL)
4076                     {
4077                       (*_bfd_error_handler)
4078                         (_("%B: %s: invalid needed version %d"),
4079                          abfd, name, vernum);
4080                       bfd_set_error (bfd_error_bad_value);
4081                       goto error_free_vers;
4082                     }
4083                 }
4084
4085               namelen = strlen (name);
4086               verlen = strlen (verstr);
4087               newlen = namelen + verlen + 2;
4088               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4089                   && isym->st_shndx != SHN_UNDEF)
4090                 ++newlen;
4091
4092               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4093               if (newname == NULL)
4094                 goto error_free_vers;
4095               memcpy (newname, name, namelen);
4096               p = newname + namelen;
4097               *p++ = ELF_VER_CHR;
4098               /* If this is a defined non-hidden version symbol,
4099                  we add another @ to the name.  This indicates the
4100                  default version of the symbol.  */
4101               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4102                   && isym->st_shndx != SHN_UNDEF)
4103                 *p++ = ELF_VER_CHR;
4104               memcpy (p, verstr, verlen + 1);
4105
4106               name = newname;
4107             }
4108
4109           /* If necessary, make a second attempt to locate the bfd
4110              containing an unresolved, non-weak reference to the
4111              current symbol.  */
4112           if (! bfd_is_und_section (sec) && undef_bfd == NULL)
4113             {
4114               h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
4115
4116               if (h != NULL
4117                   && h->root.type == bfd_link_hash_undefined
4118                   && h->root.u.undef.abfd)
4119                 undef_bfd = h->root.u.undef.abfd;
4120             }
4121
4122           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec,
4123                                       &value, &old_alignment,
4124                                       sym_hash, &skip, &override,
4125                                       &type_change_ok, &size_change_ok))
4126             goto error_free_vers;
4127
4128           if (skip)
4129             continue;
4130
4131           if (override)
4132             definition = FALSE;
4133
4134           h = *sym_hash;
4135           while (h->root.type == bfd_link_hash_indirect
4136                  || h->root.type == bfd_link_hash_warning)
4137             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4138
4139           /* Remember the old alignment if this is a common symbol, so
4140              that we don't reduce the alignment later on.  We can't
4141              check later, because _bfd_generic_link_add_one_symbol
4142              will set a default for the alignment which we want to
4143              override. We also remember the old bfd where the existing
4144              definition comes from.  */
4145           switch (h->root.type)
4146             {
4147             default:
4148               break;
4149
4150             case bfd_link_hash_defined:
4151             case bfd_link_hash_defweak:
4152               old_bfd = h->root.u.def.section->owner;
4153               break;
4154
4155             case bfd_link_hash_common:
4156               old_bfd = h->root.u.c.p->section->owner;
4157               old_alignment = h->root.u.c.p->alignment_power;
4158               break;
4159             }
4160
4161           if (elf_tdata (abfd)->verdef != NULL
4162               && ! override
4163               && vernum > 1
4164               && definition)
4165             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4166         }
4167
4168       if (! (_bfd_generic_link_add_one_symbol
4169              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4170               (struct bfd_link_hash_entry **) sym_hash)))
4171         goto error_free_vers;
4172
4173       h = *sym_hash;
4174       while (h->root.type == bfd_link_hash_indirect
4175              || h->root.type == bfd_link_hash_warning)
4176         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4177
4178       *sym_hash = h;
4179       if (is_elf_hash_table (htab))
4180         h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4181
4182       new_weakdef = FALSE;
4183       if (dynamic
4184           && definition
4185           && (flags & BSF_WEAK) != 0
4186           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4187           && is_elf_hash_table (htab)
4188           && h->u.weakdef == NULL)
4189         {
4190           /* Keep a list of all weak defined non function symbols from
4191              a dynamic object, using the weakdef field.  Later in this
4192              function we will set the weakdef field to the correct
4193              value.  We only put non-function symbols from dynamic
4194              objects on this list, because that happens to be the only
4195              time we need to know the normal symbol corresponding to a
4196              weak symbol, and the information is time consuming to
4197              figure out.  If the weakdef field is not already NULL,
4198              then this symbol was already defined by some previous
4199              dynamic object, and we will be using that previous
4200              definition anyhow.  */
4201
4202           h->u.weakdef = weaks;
4203           weaks = h;
4204           new_weakdef = TRUE;
4205         }
4206
4207       /* Set the alignment of a common symbol.  */
4208       if ((common || bfd_is_com_section (sec))
4209           && h->root.type == bfd_link_hash_common)
4210         {
4211           unsigned int align;
4212
4213           if (common)
4214             align = bfd_log2 (isym->st_value);
4215           else
4216             {
4217               /* The new symbol is a common symbol in a shared object.
4218                  We need to get the alignment from the section.  */
4219               align = new_sec->alignment_power;
4220             }
4221           if (align > old_alignment)
4222             h->root.u.c.p->alignment_power = align;
4223           else
4224             h->root.u.c.p->alignment_power = old_alignment;
4225         }
4226
4227       if (is_elf_hash_table (htab))
4228         {
4229           bfd_boolean dynsym;
4230
4231           /* Check the alignment when a common symbol is involved. This
4232              can change when a common symbol is overridden by a normal
4233              definition or a common symbol is ignored due to the old
4234              normal definition. We need to make sure the maximum
4235              alignment is maintained.  */
4236           if ((old_alignment || common)
4237               && h->root.type != bfd_link_hash_common)
4238             {
4239               unsigned int common_align;
4240               unsigned int normal_align;
4241               unsigned int symbol_align;
4242               bfd *normal_bfd;
4243               bfd *common_bfd;
4244
4245               symbol_align = ffs (h->root.u.def.value) - 1;
4246               if (h->root.u.def.section->owner != NULL
4247                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4248                 {
4249                   normal_align = h->root.u.def.section->alignment_power;
4250                   if (normal_align > symbol_align)
4251                     normal_align = symbol_align;
4252                 }
4253               else
4254                 normal_align = symbol_align;
4255
4256               if (old_alignment)
4257                 {
4258                   common_align = old_alignment;
4259                   common_bfd = old_bfd;
4260                   normal_bfd = abfd;
4261                 }
4262               else
4263                 {
4264                   common_align = bfd_log2 (isym->st_value);
4265                   common_bfd = abfd;
4266                   normal_bfd = old_bfd;
4267                 }
4268
4269               if (normal_align < common_align)
4270                 {
4271                   /* PR binutils/2735 */
4272                   if (normal_bfd == NULL)
4273                     (*_bfd_error_handler)
4274                       (_("Warning: alignment %u of common symbol `%s' in %B"
4275                          " is greater than the alignment (%u) of its section %A"),
4276                        common_bfd, h->root.u.def.section,
4277                        1 << common_align, name, 1 << normal_align);
4278                   else
4279                     (*_bfd_error_handler)
4280                       (_("Warning: alignment %u of symbol `%s' in %B"
4281                          " is smaller than %u in %B"),
4282                        normal_bfd, common_bfd,
4283                        1 << normal_align, name, 1 << common_align);
4284                 }
4285             }
4286
4287           /* Remember the symbol size if it isn't undefined.  */
4288           if ((isym->st_size != 0 && isym->st_shndx != SHN_UNDEF)
4289               && (definition || h->size == 0))
4290             {
4291               if (h->size != 0
4292                   && h->size != isym->st_size
4293                   && ! size_change_ok)
4294                 (*_bfd_error_handler)
4295                   (_("Warning: size of symbol `%s' changed"
4296                      " from %lu in %B to %lu in %B"),
4297                    old_bfd, abfd,
4298                    name, (unsigned long) h->size,
4299                    (unsigned long) isym->st_size);
4300
4301               h->size = isym->st_size;
4302             }
4303
4304           /* If this is a common symbol, then we always want H->SIZE
4305              to be the size of the common symbol.  The code just above
4306              won't fix the size if a common symbol becomes larger.  We
4307              don't warn about a size change here, because that is
4308              covered by --warn-common.  Allow changed between different
4309              function types.  */
4310           if (h->root.type == bfd_link_hash_common)
4311             h->size = h->root.u.c.size;
4312
4313           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4314               && (definition || h->type == STT_NOTYPE))
4315             {
4316               unsigned int type = ELF_ST_TYPE (isym->st_info);
4317
4318               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4319                  symbol.  */
4320               if (type == STT_GNU_IFUNC
4321                   && (abfd->flags & DYNAMIC) != 0)
4322                 type = STT_FUNC;
4323
4324               if (h->type != type)
4325                 {
4326                   if (h->type != STT_NOTYPE && ! type_change_ok)
4327                     (*_bfd_error_handler)
4328                       (_("Warning: type of symbol `%s' changed"
4329                          " from %d to %d in %B"),
4330                        abfd, name, h->type, type);
4331
4332                   h->type = type;
4333                 }
4334             }
4335
4336           /* Merge st_other field.  */
4337           elf_merge_st_other (abfd, h, isym, definition, dynamic);
4338
4339           /* Set a flag in the hash table entry indicating the type of
4340              reference or definition we just found.  Keep a count of
4341              the number of dynamic symbols we find.  A dynamic symbol
4342              is one which is referenced or defined by both a regular
4343              object and a shared object.  */
4344           dynsym = FALSE;
4345           if (! dynamic)
4346             {
4347               if (! definition)
4348                 {
4349                   h->ref_regular = 1;
4350                   if (bind != STB_WEAK)
4351                     h->ref_regular_nonweak = 1;
4352                 }
4353               else
4354                 {
4355                   h->def_regular = 1;
4356                   if (h->def_dynamic)
4357                     {
4358                       h->def_dynamic = 0;
4359                       h->ref_dynamic = 1;
4360                     }
4361                 }
4362               if (! info->executable
4363                   || h->def_dynamic
4364                   || h->ref_dynamic)
4365                 dynsym = TRUE;
4366             }
4367           else
4368             {
4369               if (! definition)
4370                 h->ref_dynamic = 1;
4371               else
4372                 {
4373                   h->def_dynamic = 1;
4374                   h->dynamic_def = 1;
4375                 }
4376               if (h->def_regular
4377                   || h->ref_regular
4378                   || (h->u.weakdef != NULL
4379                       && ! new_weakdef
4380                       && h->u.weakdef->dynindx != -1))
4381                 dynsym = TRUE;
4382             }
4383
4384           /* We don't want to make debug symbol dynamic.  */
4385           if (definition && (sec->flags & SEC_DEBUGGING) && !info->relocatable)
4386             dynsym = FALSE;
4387
4388           /* Nor should we make plugin symbols dynamic.  */
4389           if ((abfd->flags & BFD_PLUGIN) != 0)
4390             dynsym = FALSE;
4391
4392           if (definition)
4393             h->target_internal = isym->st_target_internal;
4394
4395           /* Check to see if we need to add an indirect symbol for
4396              the default name.  */
4397           if (definition || h->root.type == bfd_link_hash_common)
4398             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4399                                               &sec, &value, &dynsym,
4400                                               override))
4401               goto error_free_vers;
4402
4403           if (definition && !dynamic)
4404             {
4405               char *p = strchr (name, ELF_VER_CHR);
4406               if (p != NULL && p[1] != ELF_VER_CHR)
4407                 {
4408                   /* Queue non-default versions so that .symver x, x@FOO
4409                      aliases can be checked.  */
4410                   if (!nondeflt_vers)
4411                     {
4412                       amt = ((isymend - isym + 1)
4413                              * sizeof (struct elf_link_hash_entry *));
4414                       nondeflt_vers =
4415                           (struct elf_link_hash_entry **) bfd_malloc (amt);
4416                       if (!nondeflt_vers)
4417                         goto error_free_vers;
4418                     }
4419                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4420                 }
4421             }
4422
4423           if (dynsym && h->dynindx == -1)
4424             {
4425               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4426                 goto error_free_vers;
4427               if (h->u.weakdef != NULL
4428                   && ! new_weakdef
4429                   && h->u.weakdef->dynindx == -1)
4430                 {
4431                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4432                     goto error_free_vers;
4433                 }
4434             }
4435           else if (dynsym && h->dynindx != -1)
4436             /* If the symbol already has a dynamic index, but
4437                visibility says it should not be visible, turn it into
4438                a local symbol.  */
4439             switch (ELF_ST_VISIBILITY (h->other))
4440               {
4441               case STV_INTERNAL:
4442               case STV_HIDDEN:
4443                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4444                 dynsym = FALSE;
4445                 break;
4446               }
4447
4448           if (!add_needed
4449               && definition
4450               && ((dynsym
4451                    && h->ref_regular)
4452                   || (h->ref_dynamic
4453                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4454                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4455             {
4456               int ret;
4457               const char *soname = elf_dt_name (abfd);
4458
4459               /* A symbol from a library loaded via DT_NEEDED of some
4460                  other library is referenced by a regular object.
4461                  Add a DT_NEEDED entry for it.  Issue an error if
4462                  --no-add-needed is used and the reference was not
4463                  a weak one.  */
4464               if (undef_bfd != NULL
4465                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4466                 {
4467                   (*_bfd_error_handler)
4468                     (_("%B: undefined reference to symbol '%s'"),
4469                      undef_bfd, name);
4470                   (*_bfd_error_handler)
4471                     (_("note: '%s' is defined in DSO %B so try adding it to the linker command line"),
4472                      abfd, name);
4473                   bfd_set_error (bfd_error_invalid_operation);
4474                   goto error_free_vers;
4475                 }
4476
4477               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4478                   (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4479
4480               add_needed = TRUE;
4481               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4482               if (ret < 0)
4483                 goto error_free_vers;
4484
4485               BFD_ASSERT (ret == 0);
4486             }
4487         }
4488     }
4489
4490   if (extversym != NULL)
4491     {
4492       free (extversym);
4493       extversym = NULL;
4494     }
4495
4496   if (isymbuf != NULL)
4497     {
4498       free (isymbuf);
4499       isymbuf = NULL;
4500     }
4501
4502   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4503     {
4504       unsigned int i;
4505
4506       /* Restore the symbol table.  */
4507       if (bed->as_needed_cleanup)
4508         (*bed->as_needed_cleanup) (abfd, info);
4509       old_hash = (char *) old_tab + tabsize;
4510       old_ent = (char *) old_hash + hashsize;
4511       sym_hash = elf_sym_hashes (abfd);
4512       htab->root.table.table = old_table;
4513       htab->root.table.size = old_size;
4514       htab->root.table.count = old_count;
4515       memcpy (htab->root.table.table, old_tab, tabsize);
4516       memcpy (sym_hash, old_hash, hashsize);
4517       htab->root.undefs = old_undefs;
4518       htab->root.undefs_tail = old_undefs_tail;
4519       for (i = 0; i < htab->root.table.size; i++)
4520         {
4521           struct bfd_hash_entry *p;
4522           struct elf_link_hash_entry *h;
4523           bfd_size_type size;
4524           unsigned int alignment_power;
4525
4526           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4527             {
4528               h = (struct elf_link_hash_entry *) p;
4529               if (h->root.type == bfd_link_hash_warning)
4530                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4531               if (h->dynindx >= old_dynsymcount)
4532                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4533
4534               /* Preserve the maximum alignment and size for common
4535                  symbols even if this dynamic lib isn't on DT_NEEDED
4536                  since it can still be loaded at the run-time by another
4537                  dynamic lib.  */
4538               if (h->root.type == bfd_link_hash_common)
4539                 {
4540                   size = h->root.u.c.size;
4541                   alignment_power = h->root.u.c.p->alignment_power;
4542                 }
4543               else
4544                 {
4545                   size = 0;
4546                   alignment_power = 0;
4547                 }
4548               memcpy (p, old_ent, htab->root.table.entsize);
4549               old_ent = (char *) old_ent + htab->root.table.entsize;
4550               h = (struct elf_link_hash_entry *) p;
4551               if (h->root.type == bfd_link_hash_warning)
4552                 {
4553                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4554                   old_ent = (char *) old_ent + htab->root.table.entsize;
4555                 }
4556               else if (h->root.type == bfd_link_hash_common)
4557                 {
4558                   if (size > h->root.u.c.size)
4559                     h->root.u.c.size = size;
4560                   if (alignment_power > h->root.u.c.p->alignment_power)
4561                     h->root.u.c.p->alignment_power = alignment_power;
4562                 }
4563             }
4564         }
4565
4566       /* Make a special call to the linker "notice" function to
4567          tell it that symbols added for crefs may need to be removed.  */
4568       if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4569                                        notice_not_needed, 0, NULL))
4570         goto error_free_vers;
4571
4572       free (old_tab);
4573       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4574                            alloc_mark);
4575       if (nondeflt_vers != NULL)
4576         free (nondeflt_vers);
4577       return TRUE;
4578     }
4579
4580   if (old_tab != NULL)
4581     {
4582       if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4583                                        notice_needed, 0, NULL))
4584         goto error_free_vers;
4585       free (old_tab);
4586       old_tab = NULL;
4587     }
4588
4589   /* Now that all the symbols from this input file are created, handle
4590      .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4591   if (nondeflt_vers != NULL)
4592     {
4593       bfd_size_type cnt, symidx;
4594
4595       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4596         {
4597           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4598           char *shortname, *p;
4599
4600           p = strchr (h->root.root.string, ELF_VER_CHR);
4601           if (p == NULL
4602               || (h->root.type != bfd_link_hash_defined
4603                   && h->root.type != bfd_link_hash_defweak))
4604             continue;
4605
4606           amt = p - h->root.root.string;
4607           shortname = (char *) bfd_malloc (amt + 1);
4608           if (!shortname)
4609             goto error_free_vers;
4610           memcpy (shortname, h->root.root.string, amt);
4611           shortname[amt] = '\0';
4612
4613           hi = (struct elf_link_hash_entry *)
4614                bfd_link_hash_lookup (&htab->root, shortname,
4615                                      FALSE, FALSE, FALSE);
4616           if (hi != NULL
4617               && hi->root.type == h->root.type
4618               && hi->root.u.def.value == h->root.u.def.value
4619               && hi->root.u.def.section == h->root.u.def.section)
4620             {
4621               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4622               hi->root.type = bfd_link_hash_indirect;
4623               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4624               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4625               sym_hash = elf_sym_hashes (abfd);
4626               if (sym_hash)
4627                 for (symidx = 0; symidx < extsymcount; ++symidx)
4628                   if (sym_hash[symidx] == hi)
4629                     {
4630                       sym_hash[symidx] = h;
4631                       break;
4632                     }
4633             }
4634           free (shortname);
4635         }
4636       free (nondeflt_vers);
4637       nondeflt_vers = NULL;
4638     }
4639
4640   /* Now set the weakdefs field correctly for all the weak defined
4641      symbols we found.  The only way to do this is to search all the
4642      symbols.  Since we only need the information for non functions in
4643      dynamic objects, that's the only time we actually put anything on
4644      the list WEAKS.  We need this information so that if a regular
4645      object refers to a symbol defined weakly in a dynamic object, the
4646      real symbol in the dynamic object is also put in the dynamic
4647      symbols; we also must arrange for both symbols to point to the
4648      same memory location.  We could handle the general case of symbol
4649      aliasing, but a general symbol alias can only be generated in
4650      assembler code, handling it correctly would be very time
4651      consuming, and other ELF linkers don't handle general aliasing
4652      either.  */
4653   if (weaks != NULL)
4654     {
4655       struct elf_link_hash_entry **hpp;
4656       struct elf_link_hash_entry **hppend;
4657       struct elf_link_hash_entry **sorted_sym_hash;
4658       struct elf_link_hash_entry *h;
4659       size_t sym_count;
4660
4661       /* Since we have to search the whole symbol list for each weak
4662          defined symbol, search time for N weak defined symbols will be
4663          O(N^2). Binary search will cut it down to O(NlogN).  */
4664       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4665       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4666       if (sorted_sym_hash == NULL)
4667         goto error_return;
4668       sym_hash = sorted_sym_hash;
4669       hpp = elf_sym_hashes (abfd);
4670       hppend = hpp + extsymcount;
4671       sym_count = 0;
4672       for (; hpp < hppend; hpp++)
4673         {
4674           h = *hpp;
4675           if (h != NULL
4676               && h->root.type == bfd_link_hash_defined
4677               && !bed->is_function_type (h->type))
4678             {
4679               *sym_hash = h;
4680               sym_hash++;
4681               sym_count++;
4682             }
4683         }
4684
4685       qsort (sorted_sym_hash, sym_count,
4686              sizeof (struct elf_link_hash_entry *),
4687              elf_sort_symbol);
4688
4689       while (weaks != NULL)
4690         {
4691           struct elf_link_hash_entry *hlook;
4692           asection *slook;
4693           bfd_vma vlook;
4694           long ilook;
4695           size_t i, j, idx;
4696
4697           hlook = weaks;
4698           weaks = hlook->u.weakdef;
4699           hlook->u.weakdef = NULL;
4700
4701           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4702                       || hlook->root.type == bfd_link_hash_defweak
4703                       || hlook->root.type == bfd_link_hash_common
4704                       || hlook->root.type == bfd_link_hash_indirect);
4705           slook = hlook->root.u.def.section;
4706           vlook = hlook->root.u.def.value;
4707
4708           ilook = -1;
4709           i = 0;
4710           j = sym_count;
4711           while (i < j)
4712             {
4713               bfd_signed_vma vdiff;
4714               idx = (i + j) / 2;
4715               h = sorted_sym_hash [idx];
4716               vdiff = vlook - h->root.u.def.value;
4717               if (vdiff < 0)
4718                 j = idx;
4719               else if (vdiff > 0)
4720                 i = idx + 1;
4721               else
4722                 {
4723                   long sdiff = slook->id - h->root.u.def.section->id;
4724                   if (sdiff < 0)
4725                     j = idx;
4726                   else if (sdiff > 0)
4727                     i = idx + 1;
4728                   else
4729                     {
4730                       ilook = idx;
4731                       break;
4732                     }
4733                 }
4734             }
4735
4736           /* We didn't find a value/section match.  */
4737           if (ilook == -1)
4738             continue;
4739
4740           for (i = ilook; i < sym_count; i++)
4741             {
4742               h = sorted_sym_hash [i];
4743
4744               /* Stop if value or section doesn't match.  */
4745               if (h->root.u.def.value != vlook
4746                   || h->root.u.def.section != slook)
4747                 break;
4748               else if (h != hlook)
4749                 {
4750                   hlook->u.weakdef = h;
4751
4752                   /* If the weak definition is in the list of dynamic
4753                      symbols, make sure the real definition is put
4754                      there as well.  */
4755                   if (hlook->dynindx != -1 && h->dynindx == -1)
4756                     {
4757                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4758                         {
4759                         err_free_sym_hash:
4760                           free (sorted_sym_hash);
4761                           goto error_return;
4762                         }
4763                     }
4764
4765                   /* If the real definition is in the list of dynamic
4766                      symbols, make sure the weak definition is put
4767                      there as well.  If we don't do this, then the
4768                      dynamic loader might not merge the entries for the
4769                      real definition and the weak definition.  */
4770                   if (h->dynindx != -1 && hlook->dynindx == -1)
4771                     {
4772                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4773                         goto err_free_sym_hash;
4774                     }
4775                   break;
4776                 }
4777             }
4778         }
4779
4780       free (sorted_sym_hash);
4781     }
4782
4783   if (bed->check_directives
4784       && !(*bed->check_directives) (abfd, info))
4785     return FALSE;
4786
4787   /* If this object is the same format as the output object, and it is
4788      not a shared library, then let the backend look through the
4789      relocs.
4790
4791      This is required to build global offset table entries and to
4792      arrange for dynamic relocs.  It is not required for the
4793      particular common case of linking non PIC code, even when linking
4794      against shared libraries, but unfortunately there is no way of
4795      knowing whether an object file has been compiled PIC or not.
4796      Looking through the relocs is not particularly time consuming.
4797      The problem is that we must either (1) keep the relocs in memory,
4798      which causes the linker to require additional runtime memory or
4799      (2) read the relocs twice from the input file, which wastes time.
4800      This would be a good case for using mmap.
4801
4802      I have no idea how to handle linking PIC code into a file of a
4803      different format.  It probably can't be done.  */
4804   if (! dynamic
4805       && is_elf_hash_table (htab)
4806       && bed->check_relocs != NULL
4807       && elf_object_id (abfd) == elf_hash_table_id (htab)
4808       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4809     {
4810       asection *o;
4811
4812       for (o = abfd->sections; o != NULL; o = o->next)
4813         {
4814           Elf_Internal_Rela *internal_relocs;
4815           bfd_boolean ok;
4816
4817           if ((o->flags & SEC_RELOC) == 0
4818               || o->reloc_count == 0
4819               || ((info->strip == strip_all || info->strip == strip_debugger)
4820                   && (o->flags & SEC_DEBUGGING) != 0)
4821               || bfd_is_abs_section (o->output_section))
4822             continue;
4823
4824           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4825                                                        info->keep_memory);
4826           if (internal_relocs == NULL)
4827             goto error_return;
4828
4829           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4830
4831           if (elf_section_data (o)->relocs != internal_relocs)
4832             free (internal_relocs);
4833
4834           if (! ok)
4835             goto error_return;
4836         }
4837     }
4838
4839   /* If this is a non-traditional link, try to optimize the handling
4840      of the .stab/.stabstr sections.  */
4841   if (! dynamic
4842       && ! info->traditional_format
4843       && is_elf_hash_table (htab)
4844       && (info->strip != strip_all && info->strip != strip_debugger))
4845     {
4846       asection *stabstr;
4847
4848       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4849       if (stabstr != NULL)
4850         {
4851           bfd_size_type string_offset = 0;
4852           asection *stab;
4853
4854           for (stab = abfd->sections; stab; stab = stab->next)
4855             if (CONST_STRNEQ (stab->name, ".stab")
4856                 && (!stab->name[5] ||
4857                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4858                 && (stab->flags & SEC_MERGE) == 0
4859                 && !bfd_is_abs_section (stab->output_section))
4860               {
4861                 struct bfd_elf_section_data *secdata;
4862
4863                 secdata = elf_section_data (stab);
4864                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4865                                                stabstr, &secdata->sec_info,
4866                                                &string_offset))
4867                   goto error_return;
4868                 if (secdata->sec_info)
4869                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
4870             }
4871         }
4872     }
4873
4874   if (is_elf_hash_table (htab) && add_needed)
4875     {
4876       /* Add this bfd to the loaded list.  */
4877       struct elf_link_loaded_list *n;
4878
4879       n = (struct elf_link_loaded_list *)
4880           bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4881       if (n == NULL)
4882         goto error_return;
4883       n->abfd = abfd;
4884       n->next = htab->loaded;
4885       htab->loaded = n;
4886     }
4887
4888   return TRUE;
4889
4890  error_free_vers:
4891   if (old_tab != NULL)
4892     free (old_tab);
4893   if (nondeflt_vers != NULL)
4894     free (nondeflt_vers);
4895   if (extversym != NULL)
4896     free (extversym);
4897  error_free_sym:
4898   if (isymbuf != NULL)
4899     free (isymbuf);
4900  error_return:
4901   return FALSE;
4902 }
4903
4904 /* Return the linker hash table entry of a symbol that might be
4905    satisfied by an archive symbol.  Return -1 on error.  */
4906
4907 struct elf_link_hash_entry *
4908 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4909                                 struct bfd_link_info *info,
4910                                 const char *name)
4911 {
4912   struct elf_link_hash_entry *h;
4913   char *p, *copy;
4914   size_t len, first;
4915
4916   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
4917   if (h != NULL)
4918     return h;
4919
4920   /* If this is a default version (the name contains @@), look up the
4921      symbol again with only one `@' as well as without the version.
4922      The effect is that references to the symbol with and without the
4923      version will be matched by the default symbol in the archive.  */
4924
4925   p = strchr (name, ELF_VER_CHR);
4926   if (p == NULL || p[1] != ELF_VER_CHR)
4927     return h;
4928
4929   /* First check with only one `@'.  */
4930   len = strlen (name);
4931   copy = (char *) bfd_alloc (abfd, len);
4932   if (copy == NULL)
4933     return (struct elf_link_hash_entry *) 0 - 1;
4934
4935   first = p - name + 1;
4936   memcpy (copy, name, first);
4937   memcpy (copy + first, name + first + 1, len - first);
4938
4939   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
4940   if (h == NULL)
4941     {
4942       /* We also need to check references to the symbol without the
4943          version.  */
4944       copy[first - 1] = '\0';
4945       h = elf_link_hash_lookup (elf_hash_table (info), copy,
4946                                 FALSE, FALSE, TRUE);
4947     }
4948
4949   bfd_release (abfd, copy);
4950   return h;
4951 }
4952
4953 /* Add symbols from an ELF archive file to the linker hash table.  We
4954    don't use _bfd_generic_link_add_archive_symbols because of a
4955    problem which arises on UnixWare.  The UnixWare libc.so is an
4956    archive which includes an entry libc.so.1 which defines a bunch of
4957    symbols.  The libc.so archive also includes a number of other
4958    object files, which also define symbols, some of which are the same
4959    as those defined in libc.so.1.  Correct linking requires that we
4960    consider each object file in turn, and include it if it defines any
4961    symbols we need.  _bfd_generic_link_add_archive_symbols does not do
4962    this; it looks through the list of undefined symbols, and includes
4963    any object file which defines them.  When this algorithm is used on
4964    UnixWare, it winds up pulling in libc.so.1 early and defining a
4965    bunch of symbols.  This means that some of the other objects in the
4966    archive are not included in the link, which is incorrect since they
4967    precede libc.so.1 in the archive.
4968
4969    Fortunately, ELF archive handling is simpler than that done by
4970    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4971    oddities.  In ELF, if we find a symbol in the archive map, and the
4972    symbol is currently undefined, we know that we must pull in that
4973    object file.
4974
4975    Unfortunately, we do have to make multiple passes over the symbol
4976    table until nothing further is resolved.  */
4977
4978 static bfd_boolean
4979 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4980 {
4981   symindex c;
4982   bfd_boolean *defined = NULL;
4983   bfd_boolean *included = NULL;
4984   carsym *symdefs;
4985   bfd_boolean loop;
4986   bfd_size_type amt;
4987   const struct elf_backend_data *bed;
4988   struct elf_link_hash_entry * (*archive_symbol_lookup)
4989     (bfd *, struct bfd_link_info *, const char *);
4990
4991   if (! bfd_has_map (abfd))
4992     {
4993       /* An empty archive is a special case.  */
4994       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4995         return TRUE;
4996       bfd_set_error (bfd_error_no_armap);
4997       return FALSE;
4998     }
4999
5000   /* Keep track of all symbols we know to be already defined, and all
5001      files we know to be already included.  This is to speed up the
5002      second and subsequent passes.  */
5003   c = bfd_ardata (abfd)->symdef_count;
5004   if (c == 0)
5005     return TRUE;
5006   amt = c;
5007   amt *= sizeof (bfd_boolean);
5008   defined = (bfd_boolean *) bfd_zmalloc (amt);
5009   included = (bfd_boolean *) bfd_zmalloc (amt);
5010   if (defined == NULL || included == NULL)
5011     goto error_return;
5012
5013   symdefs = bfd_ardata (abfd)->symdefs;
5014   bed = get_elf_backend_data (abfd);
5015   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5016
5017   do
5018     {
5019       file_ptr last;
5020       symindex i;
5021       carsym *symdef;
5022       carsym *symdefend;
5023
5024       loop = FALSE;
5025       last = -1;
5026
5027       symdef = symdefs;
5028       symdefend = symdef + c;
5029       for (i = 0; symdef < symdefend; symdef++, i++)
5030         {
5031           struct elf_link_hash_entry *h;
5032           bfd *element;
5033           struct bfd_link_hash_entry *undefs_tail;
5034           symindex mark;
5035
5036           if (defined[i] || included[i])
5037             continue;
5038           if (symdef->file_offset == last)
5039             {
5040               included[i] = TRUE;
5041               continue;
5042             }
5043
5044           h = archive_symbol_lookup (abfd, info, symdef->name);
5045           if (h == (struct elf_link_hash_entry *) 0 - 1)
5046             goto error_return;
5047
5048           if (h == NULL)
5049             continue;
5050
5051           if (h->root.type == bfd_link_hash_common)
5052             {
5053               /* We currently have a common symbol.  The archive map contains
5054                  a reference to this symbol, so we may want to include it.  We
5055                  only want to include it however, if this archive element
5056                  contains a definition of the symbol, not just another common
5057                  declaration of it.
5058
5059                  Unfortunately some archivers (including GNU ar) will put
5060                  declarations of common symbols into their archive maps, as
5061                  well as real definitions, so we cannot just go by the archive
5062                  map alone.  Instead we must read in the element's symbol
5063                  table and check that to see what kind of symbol definition
5064                  this is.  */
5065               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5066                 continue;
5067             }
5068           else if (h->root.type != bfd_link_hash_undefined)
5069             {
5070               if (h->root.type != bfd_link_hash_undefweak)
5071                 defined[i] = TRUE;
5072               continue;
5073             }
5074
5075           /* We need to include this archive member.  */
5076           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5077           if (element == NULL)
5078             goto error_return;
5079
5080           if (! bfd_check_format (element, bfd_object))
5081             goto error_return;
5082
5083           /* Doublecheck that we have not included this object
5084              already--it should be impossible, but there may be
5085              something wrong with the archive.  */
5086           if (element->archive_pass != 0)
5087             {
5088               bfd_set_error (bfd_error_bad_value);
5089               goto error_return;
5090             }
5091           element->archive_pass = 1;
5092
5093           undefs_tail = info->hash->undefs_tail;
5094
5095           if (!(*info->callbacks
5096                 ->add_archive_element) (info, element, symdef->name, &element))
5097             goto error_return;
5098           if (!bfd_link_add_symbols (element, info))
5099             goto error_return;
5100
5101           /* If there are any new undefined symbols, we need to make
5102              another pass through the archive in order to see whether
5103              they can be defined.  FIXME: This isn't perfect, because
5104              common symbols wind up on undefs_tail and because an
5105              undefined symbol which is defined later on in this pass
5106              does not require another pass.  This isn't a bug, but it
5107              does make the code less efficient than it could be.  */
5108           if (undefs_tail != info->hash->undefs_tail)
5109             loop = TRUE;
5110
5111           /* Look backward to mark all symbols from this object file
5112              which we have already seen in this pass.  */
5113           mark = i;
5114           do
5115             {
5116               included[mark] = TRUE;
5117               if (mark == 0)
5118                 break;
5119               --mark;
5120             }
5121           while (symdefs[mark].file_offset == symdef->file_offset);
5122
5123           /* We mark subsequent symbols from this object file as we go
5124              on through the loop.  */
5125           last = symdef->file_offset;
5126         }
5127     }
5128   while (loop);
5129
5130   free (defined);
5131   free (included);
5132
5133   return TRUE;
5134
5135  error_return:
5136   if (defined != NULL)
5137     free (defined);
5138   if (included != NULL)
5139     free (included);
5140   return FALSE;
5141 }
5142
5143 /* Given an ELF BFD, add symbols to the global hash table as
5144    appropriate.  */
5145
5146 bfd_boolean
5147 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5148 {
5149   switch (bfd_get_format (abfd))
5150     {
5151     case bfd_object:
5152       return elf_link_add_object_symbols (abfd, info);
5153     case bfd_archive:
5154       return elf_link_add_archive_symbols (abfd, info);
5155     default:
5156       bfd_set_error (bfd_error_wrong_format);
5157       return FALSE;
5158     }
5159 }
5160 \f
5161 struct hash_codes_info
5162 {
5163   unsigned long *hashcodes;
5164   bfd_boolean error;
5165 };
5166
5167 /* This function will be called though elf_link_hash_traverse to store
5168    all hash value of the exported symbols in an array.  */
5169
5170 static bfd_boolean
5171 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5172 {
5173   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5174   const char *name;
5175   char *p;
5176   unsigned long ha;
5177   char *alc = NULL;
5178
5179   /* Ignore indirect symbols.  These are added by the versioning code.  */
5180   if (h->dynindx == -1)
5181     return TRUE;
5182
5183   name = h->root.root.string;
5184   p = strchr (name, ELF_VER_CHR);
5185   if (p != NULL)
5186     {
5187       alc = (char *) bfd_malloc (p - name + 1);
5188       if (alc == NULL)
5189         {
5190           inf->error = TRUE;
5191           return FALSE;
5192         }
5193       memcpy (alc, name, p - name);
5194       alc[p - name] = '\0';
5195       name = alc;
5196     }
5197
5198   /* Compute the hash value.  */
5199   ha = bfd_elf_hash (name);
5200
5201   /* Store the found hash value in the array given as the argument.  */
5202   *(inf->hashcodes)++ = ha;
5203
5204   /* And store it in the struct so that we can put it in the hash table
5205      later.  */
5206   h->u.elf_hash_value = ha;
5207
5208   if (alc != NULL)
5209     free (alc);
5210
5211   return TRUE;
5212 }
5213
5214 struct collect_gnu_hash_codes
5215 {
5216   bfd *output_bfd;
5217   const struct elf_backend_data *bed;
5218   unsigned long int nsyms;
5219   unsigned long int maskbits;
5220   unsigned long int *hashcodes;
5221   unsigned long int *hashval;
5222   unsigned long int *indx;
5223   unsigned long int *counts;
5224   bfd_vma *bitmask;
5225   bfd_byte *contents;
5226   long int min_dynindx;
5227   unsigned long int bucketcount;
5228   unsigned long int symindx;
5229   long int local_indx;
5230   long int shift1, shift2;
5231   unsigned long int mask;
5232   bfd_boolean error;
5233 };
5234
5235 /* This function will be called though elf_link_hash_traverse to store
5236    all hash value of the exported symbols in an array.  */
5237
5238 static bfd_boolean
5239 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5240 {
5241   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5242   const char *name;
5243   char *p;
5244   unsigned long ha;
5245   char *alc = NULL;
5246
5247   /* Ignore indirect symbols.  These are added by the versioning code.  */
5248   if (h->dynindx == -1)
5249     return TRUE;
5250
5251   /* Ignore also local symbols and undefined symbols.  */
5252   if (! (*s->bed->elf_hash_symbol) (h))
5253     return TRUE;
5254
5255   name = h->root.root.string;
5256   p = strchr (name, ELF_VER_CHR);
5257   if (p != NULL)
5258     {
5259       alc = (char *) bfd_malloc (p - name + 1);
5260       if (alc == NULL)
5261         {
5262           s->error = TRUE;
5263           return FALSE;
5264         }
5265       memcpy (alc, name, p - name);
5266       alc[p - name] = '\0';
5267       name = alc;
5268     }
5269
5270   /* Compute the hash value.  */
5271   ha = bfd_elf_gnu_hash (name);
5272
5273   /* Store the found hash value in the array for compute_bucket_count,
5274      and also for .dynsym reordering purposes.  */
5275   s->hashcodes[s->nsyms] = ha;
5276   s->hashval[h->dynindx] = ha;
5277   ++s->nsyms;
5278   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5279     s->min_dynindx = h->dynindx;
5280
5281   if (alc != NULL)
5282     free (alc);
5283
5284   return TRUE;
5285 }
5286
5287 /* This function will be called though elf_link_hash_traverse to do
5288    final dynaminc symbol renumbering.  */
5289
5290 static bfd_boolean
5291 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5292 {
5293   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5294   unsigned long int bucket;
5295   unsigned long int val;
5296
5297   /* Ignore indirect symbols.  */
5298   if (h->dynindx == -1)
5299     return TRUE;
5300
5301   /* Ignore also local symbols and undefined symbols.  */
5302   if (! (*s->bed->elf_hash_symbol) (h))
5303     {
5304       if (h->dynindx >= s->min_dynindx)
5305         h->dynindx = s->local_indx++;
5306       return TRUE;
5307     }
5308
5309   bucket = s->hashval[h->dynindx] % s->bucketcount;
5310   val = (s->hashval[h->dynindx] >> s->shift1)
5311         & ((s->maskbits >> s->shift1) - 1);
5312   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5313   s->bitmask[val]
5314     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5315   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5316   if (s->counts[bucket] == 1)
5317     /* Last element terminates the chain.  */
5318     val |= 1;
5319   bfd_put_32 (s->output_bfd, val,
5320               s->contents + (s->indx[bucket] - s->symindx) * 4);
5321   --s->counts[bucket];
5322   h->dynindx = s->indx[bucket]++;
5323   return TRUE;
5324 }
5325
5326 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5327
5328 bfd_boolean
5329 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5330 {
5331   return !(h->forced_local
5332            || h->root.type == bfd_link_hash_undefined
5333            || h->root.type == bfd_link_hash_undefweak
5334            || ((h->root.type == bfd_link_hash_defined
5335                 || h->root.type == bfd_link_hash_defweak)
5336                && h->root.u.def.section->output_section == NULL));
5337 }
5338
5339 /* Array used to determine the number of hash table buckets to use
5340    based on the number of symbols there are.  If there are fewer than
5341    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5342    fewer than 37 we use 17 buckets, and so forth.  We never use more
5343    than 32771 buckets.  */
5344
5345 static const size_t elf_buckets[] =
5346 {
5347   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5348   16411, 32771, 0
5349 };
5350
5351 /* Compute bucket count for hashing table.  We do not use a static set
5352    of possible tables sizes anymore.  Instead we determine for all
5353    possible reasonable sizes of the table the outcome (i.e., the
5354    number of collisions etc) and choose the best solution.  The
5355    weighting functions are not too simple to allow the table to grow
5356    without bounds.  Instead one of the weighting factors is the size.
5357    Therefore the result is always a good payoff between few collisions
5358    (= short chain lengths) and table size.  */
5359 static size_t
5360 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5361                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5362                       unsigned long int nsyms,
5363                       int gnu_hash)
5364 {
5365   size_t best_size = 0;
5366   unsigned long int i;
5367
5368   /* We have a problem here.  The following code to optimize the table
5369      size requires an integer type with more the 32 bits.  If
5370      BFD_HOST_U_64_BIT is set we know about such a type.  */
5371 #ifdef BFD_HOST_U_64_BIT
5372   if (info->optimize)
5373     {
5374       size_t minsize;
5375       size_t maxsize;
5376       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5377       bfd *dynobj = elf_hash_table (info)->dynobj;
5378       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5379       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5380       unsigned long int *counts;
5381       bfd_size_type amt;
5382       unsigned int no_improvement_count = 0;
5383
5384       /* Possible optimization parameters: if we have NSYMS symbols we say
5385          that the hashing table must at least have NSYMS/4 and at most
5386          2*NSYMS buckets.  */
5387       minsize = nsyms / 4;
5388       if (minsize == 0)
5389         minsize = 1;
5390       best_size = maxsize = nsyms * 2;
5391       if (gnu_hash)
5392         {
5393           if (minsize < 2)
5394             minsize = 2;
5395           if ((best_size & 31) == 0)
5396             ++best_size;
5397         }
5398
5399       /* Create array where we count the collisions in.  We must use bfd_malloc
5400          since the size could be large.  */
5401       amt = maxsize;
5402       amt *= sizeof (unsigned long int);
5403       counts = (unsigned long int *) bfd_malloc (amt);
5404       if (counts == NULL)
5405         return 0;
5406
5407       /* Compute the "optimal" size for the hash table.  The criteria is a
5408          minimal chain length.  The minor criteria is (of course) the size
5409          of the table.  */
5410       for (i = minsize; i < maxsize; ++i)
5411         {
5412           /* Walk through the array of hashcodes and count the collisions.  */
5413           BFD_HOST_U_64_BIT max;
5414           unsigned long int j;
5415           unsigned long int fact;
5416
5417           if (gnu_hash && (i & 31) == 0)
5418             continue;
5419
5420           memset (counts, '\0', i * sizeof (unsigned long int));
5421
5422           /* Determine how often each hash bucket is used.  */
5423           for (j = 0; j < nsyms; ++j)
5424             ++counts[hashcodes[j] % i];
5425
5426           /* For the weight function we need some information about the
5427              pagesize on the target.  This is information need not be 100%
5428              accurate.  Since this information is not available (so far) we
5429              define it here to a reasonable default value.  If it is crucial
5430              to have a better value some day simply define this value.  */
5431 # ifndef BFD_TARGET_PAGESIZE
5432 #  define BFD_TARGET_PAGESIZE   (4096)
5433 # endif
5434
5435           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5436              and the chains.  */
5437           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5438
5439 # if 1
5440           /* Variant 1: optimize for short chains.  We add the squares
5441              of all the chain lengths (which favors many small chain
5442              over a few long chains).  */
5443           for (j = 0; j < i; ++j)
5444             max += counts[j] * counts[j];
5445
5446           /* This adds penalties for the overall size of the table.  */
5447           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5448           max *= fact * fact;
5449 # else
5450           /* Variant 2: Optimize a lot more for small table.  Here we
5451              also add squares of the size but we also add penalties for
5452              empty slots (the +1 term).  */
5453           for (j = 0; j < i; ++j)
5454             max += (1 + counts[j]) * (1 + counts[j]);
5455
5456           /* The overall size of the table is considered, but not as
5457              strong as in variant 1, where it is squared.  */
5458           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5459           max *= fact;
5460 # endif
5461
5462           /* Compare with current best results.  */
5463           if (max < best_chlen)
5464             {
5465               best_chlen = max;
5466               best_size = i;
5467               no_improvement_count = 0;
5468             }
5469           /* PR 11843: Avoid futile long searches for the best bucket size
5470              when there are a large number of symbols.  */
5471           else if (++no_improvement_count == 100)
5472             break;
5473         }
5474
5475       free (counts);
5476     }
5477   else
5478 #endif /* defined (BFD_HOST_U_64_BIT) */
5479     {
5480       /* This is the fallback solution if no 64bit type is available or if we
5481          are not supposed to spend much time on optimizations.  We select the
5482          bucket count using a fixed set of numbers.  */
5483       for (i = 0; elf_buckets[i] != 0; i++)
5484         {
5485           best_size = elf_buckets[i];
5486           if (nsyms < elf_buckets[i + 1])
5487             break;
5488         }
5489       if (gnu_hash && best_size < 2)
5490         best_size = 2;
5491     }
5492
5493   return best_size;
5494 }
5495
5496 /* Size any SHT_GROUP section for ld -r.  */
5497
5498 bfd_boolean
5499 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5500 {
5501   bfd *ibfd;
5502
5503   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
5504     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5505         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5506       return FALSE;
5507   return TRUE;
5508 }
5509
5510 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5511    called by the ELF linker emulation before_allocation routine.  We
5512    must set the sizes of the sections before the linker sets the
5513    addresses of the various sections.  */
5514
5515 bfd_boolean
5516 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5517                                const char *soname,
5518                                const char *rpath,
5519                                const char *filter_shlib,
5520                                const char *audit,
5521                                const char *depaudit,
5522                                const char * const *auxiliary_filters,
5523                                struct bfd_link_info *info,
5524                                asection **sinterpptr)
5525 {
5526   bfd_size_type soname_indx;
5527   bfd *dynobj;
5528   const struct elf_backend_data *bed;
5529   struct elf_info_failed asvinfo;
5530
5531   *sinterpptr = NULL;
5532
5533   soname_indx = (bfd_size_type) -1;
5534
5535   if (!is_elf_hash_table (info->hash))
5536     return TRUE;
5537
5538   bed = get_elf_backend_data (output_bfd);
5539   if (info->execstack)
5540     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X;
5541   else if (info->noexecstack)
5542     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W;
5543   else
5544     {
5545       bfd *inputobj;
5546       asection *notesec = NULL;
5547       int exec = 0;
5548
5549       for (inputobj = info->input_bfds;
5550            inputobj;
5551            inputobj = inputobj->link_next)
5552         {
5553           asection *s;
5554
5555           if (inputobj->flags
5556               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5557             continue;
5558           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5559           if (s)
5560             {
5561               if (s->flags & SEC_CODE)
5562                 exec = PF_X;
5563               notesec = s;
5564             }
5565           else if (bed->default_execstack)
5566             exec = PF_X;
5567         }
5568       if (notesec)
5569         {
5570           elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | exec;
5571           if (exec && info->relocatable
5572               && notesec->output_section != bfd_abs_section_ptr)
5573             notesec->output_section->flags |= SEC_CODE;
5574         }
5575     }
5576
5577   /* Any syms created from now on start with -1 in
5578      got.refcount/offset and plt.refcount/offset.  */
5579   elf_hash_table (info)->init_got_refcount
5580     = elf_hash_table (info)->init_got_offset;
5581   elf_hash_table (info)->init_plt_refcount
5582     = elf_hash_table (info)->init_plt_offset;
5583
5584   if (info->relocatable
5585       && !_bfd_elf_size_group_sections (info))
5586     return FALSE;
5587
5588   /* The backend may have to create some sections regardless of whether
5589      we're dynamic or not.  */
5590   if (bed->elf_backend_always_size_sections
5591       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5592     return FALSE;
5593
5594   dynobj = elf_hash_table (info)->dynobj;
5595
5596   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5597     {
5598       struct elf_info_failed eif;
5599       struct elf_link_hash_entry *h;
5600       asection *dynstr;
5601       struct bfd_elf_version_tree *t;
5602       struct bfd_elf_version_expr *d;
5603       asection *s;
5604       bfd_boolean all_defined;
5605
5606       *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
5607       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5608
5609       if (soname != NULL)
5610         {
5611           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5612                                              soname, TRUE);
5613           if (soname_indx == (bfd_size_type) -1
5614               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5615             return FALSE;
5616         }
5617
5618       if (info->symbolic)
5619         {
5620           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5621             return FALSE;
5622           info->flags |= DF_SYMBOLIC;
5623         }
5624
5625       if (rpath != NULL)
5626         {
5627           bfd_size_type indx;
5628
5629           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5630                                       TRUE);
5631           if (indx == (bfd_size_type) -1
5632               || !_bfd_elf_add_dynamic_entry (info, DT_RPATH, indx))
5633             return FALSE;
5634
5635           if  (info->new_dtags)
5636             {
5637               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr, indx);
5638               if (!_bfd_elf_add_dynamic_entry (info, DT_RUNPATH, indx))
5639                 return FALSE;
5640             }
5641         }
5642
5643       if (filter_shlib != NULL)
5644         {
5645           bfd_size_type indx;
5646
5647           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5648                                       filter_shlib, TRUE);
5649           if (indx == (bfd_size_type) -1
5650               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5651             return FALSE;
5652         }
5653
5654       if (auxiliary_filters != NULL)
5655         {
5656           const char * const *p;
5657
5658           for (p = auxiliary_filters; *p != NULL; p++)
5659             {
5660               bfd_size_type indx;
5661
5662               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5663                                           *p, TRUE);
5664               if (indx == (bfd_size_type) -1
5665                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5666                 return FALSE;
5667             }
5668         }
5669
5670       if (audit != NULL)
5671         {
5672           bfd_size_type indx;
5673
5674           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5675                                       TRUE);
5676           if (indx == (bfd_size_type) -1
5677               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5678             return FALSE;
5679         }
5680
5681       if (depaudit != NULL)
5682         {
5683           bfd_size_type indx;
5684
5685           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5686                                       TRUE);
5687           if (indx == (bfd_size_type) -1
5688               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5689             return FALSE;
5690         }
5691
5692       eif.info = info;
5693       eif.failed = FALSE;
5694
5695       /* If we are supposed to export all symbols into the dynamic symbol
5696          table (this is not the normal case), then do so.  */
5697       if (info->export_dynamic
5698           || (info->executable && info->dynamic))
5699         {
5700           elf_link_hash_traverse (elf_hash_table (info),
5701                                   _bfd_elf_export_symbol,
5702                                   &eif);
5703           if (eif.failed)
5704             return FALSE;
5705         }
5706
5707       /* Make all global versions with definition.  */
5708       for (t = info->version_info; t != NULL; t = t->next)
5709         for (d = t->globals.list; d != NULL; d = d->next)
5710           if (!d->symver && d->literal)
5711             {
5712               const char *verstr, *name;
5713               size_t namelen, verlen, newlen;
5714               char *newname, *p, leading_char;
5715               struct elf_link_hash_entry *newh;
5716
5717               leading_char = bfd_get_symbol_leading_char (output_bfd);
5718               name = d->pattern;
5719               namelen = strlen (name) + (leading_char != '\0');
5720               verstr = t->name;
5721               verlen = strlen (verstr);
5722               newlen = namelen + verlen + 3;
5723
5724               newname = (char *) bfd_malloc (newlen);
5725               if (newname == NULL)
5726                 return FALSE;
5727               newname[0] = leading_char;
5728               memcpy (newname + (leading_char != '\0'), name, namelen);
5729
5730               /* Check the hidden versioned definition.  */
5731               p = newname + namelen;
5732               *p++ = ELF_VER_CHR;
5733               memcpy (p, verstr, verlen + 1);
5734               newh = elf_link_hash_lookup (elf_hash_table (info),
5735                                            newname, FALSE, FALSE,
5736                                            FALSE);
5737               if (newh == NULL
5738                   || (newh->root.type != bfd_link_hash_defined
5739                       && newh->root.type != bfd_link_hash_defweak))
5740                 {
5741                   /* Check the default versioned definition.  */
5742                   *p++ = ELF_VER_CHR;
5743                   memcpy (p, verstr, verlen + 1);
5744                   newh = elf_link_hash_lookup (elf_hash_table (info),
5745                                                newname, FALSE, FALSE,
5746                                                FALSE);
5747                 }
5748               free (newname);
5749
5750               /* Mark this version if there is a definition and it is
5751                  not defined in a shared object.  */
5752               if (newh != NULL
5753                   && !newh->def_dynamic
5754                   && (newh->root.type == bfd_link_hash_defined
5755                       || newh->root.type == bfd_link_hash_defweak))
5756                 d->symver = 1;
5757             }
5758
5759       /* Attach all the symbols to their version information.  */
5760       asvinfo.info = info;
5761       asvinfo.failed = FALSE;
5762
5763       elf_link_hash_traverse (elf_hash_table (info),
5764                               _bfd_elf_link_assign_sym_version,
5765                               &asvinfo);
5766       if (asvinfo.failed)
5767         return FALSE;
5768
5769       if (!info->allow_undefined_version)
5770         {
5771           /* Check if all global versions have a definition.  */
5772           all_defined = TRUE;
5773           for (t = info->version_info; t != NULL; t = t->next)
5774             for (d = t->globals.list; d != NULL; d = d->next)
5775               if (d->literal && !d->symver && !d->script)
5776                 {
5777                   (*_bfd_error_handler)
5778                     (_("%s: undefined version: %s"),
5779                      d->pattern, t->name);
5780                   all_defined = FALSE;
5781                 }
5782
5783           if (!all_defined)
5784             {
5785               bfd_set_error (bfd_error_bad_value);
5786               return FALSE;
5787             }
5788         }
5789
5790       /* Find all symbols which were defined in a dynamic object and make
5791          the backend pick a reasonable value for them.  */
5792       elf_link_hash_traverse (elf_hash_table (info),
5793                               _bfd_elf_adjust_dynamic_symbol,
5794                               &eif);
5795       if (eif.failed)
5796         return FALSE;
5797
5798       /* Add some entries to the .dynamic section.  We fill in some of the
5799          values later, in bfd_elf_final_link, but we must add the entries
5800          now so that we know the final size of the .dynamic section.  */
5801
5802       /* If there are initialization and/or finalization functions to
5803          call then add the corresponding DT_INIT/DT_FINI entries.  */
5804       h = (info->init_function
5805            ? elf_link_hash_lookup (elf_hash_table (info),
5806                                    info->init_function, FALSE,
5807                                    FALSE, FALSE)
5808            : NULL);
5809       if (h != NULL
5810           && (h->ref_regular
5811               || h->def_regular))
5812         {
5813           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5814             return FALSE;
5815         }
5816       h = (info->fini_function
5817            ? elf_link_hash_lookup (elf_hash_table (info),
5818                                    info->fini_function, FALSE,
5819                                    FALSE, FALSE)
5820            : NULL);
5821       if (h != NULL
5822           && (h->ref_regular
5823               || h->def_regular))
5824         {
5825           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5826             return FALSE;
5827         }
5828
5829       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5830       if (s != NULL && s->linker_has_input)
5831         {
5832           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5833           if (! info->executable)
5834             {
5835               bfd *sub;
5836               asection *o;
5837
5838               for (sub = info->input_bfds; sub != NULL;
5839                    sub = sub->link_next)
5840                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5841                   for (o = sub->sections; o != NULL; o = o->next)
5842                     if (elf_section_data (o)->this_hdr.sh_type
5843                         == SHT_PREINIT_ARRAY)
5844                       {
5845                         (*_bfd_error_handler)
5846                           (_("%B: .preinit_array section is not allowed in DSO"),
5847                            sub);
5848                         break;
5849                       }
5850
5851               bfd_set_error (bfd_error_nonrepresentable_section);
5852               return FALSE;
5853             }
5854
5855           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5856               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5857             return FALSE;
5858         }
5859       s = bfd_get_section_by_name (output_bfd, ".init_array");
5860       if (s != NULL && s->linker_has_input)
5861         {
5862           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5863               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5864             return FALSE;
5865         }
5866       s = bfd_get_section_by_name (output_bfd, ".fini_array");
5867       if (s != NULL && s->linker_has_input)
5868         {
5869           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5870               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5871             return FALSE;
5872         }
5873
5874       dynstr = bfd_get_section_by_name (dynobj, ".dynstr");
5875       /* If .dynstr is excluded from the link, we don't want any of
5876          these tags.  Strictly, we should be checking each section
5877          individually;  This quick check covers for the case where
5878          someone does a /DISCARD/ : { *(*) }.  */
5879       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5880         {
5881           bfd_size_type strsize;
5882
5883           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5884           if ((info->emit_hash
5885                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5886               || (info->emit_gnu_hash
5887                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5888               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5889               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5890               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5891               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5892                                               bed->s->sizeof_sym))
5893             return FALSE;
5894         }
5895     }
5896
5897   /* The backend must work out the sizes of all the other dynamic
5898      sections.  */
5899   if (dynobj != NULL
5900       && bed->elf_backend_size_dynamic_sections != NULL
5901       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5902     return FALSE;
5903
5904   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5905     return FALSE;
5906
5907   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5908     {
5909       unsigned long section_sym_count;
5910       struct bfd_elf_version_tree *verdefs;
5911       asection *s;
5912
5913       /* Set up the version definition section.  */
5914       s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
5915       BFD_ASSERT (s != NULL);
5916
5917       /* We may have created additional version definitions if we are
5918          just linking a regular application.  */
5919       verdefs = info->version_info;
5920
5921       /* Skip anonymous version tag.  */
5922       if (verdefs != NULL && verdefs->vernum == 0)
5923         verdefs = verdefs->next;
5924
5925       if (verdefs == NULL && !info->create_default_symver)
5926         s->flags |= SEC_EXCLUDE;
5927       else
5928         {
5929           unsigned int cdefs;
5930           bfd_size_type size;
5931           struct bfd_elf_version_tree *t;
5932           bfd_byte *p;
5933           Elf_Internal_Verdef def;
5934           Elf_Internal_Verdaux defaux;
5935           struct bfd_link_hash_entry *bh;
5936           struct elf_link_hash_entry *h;
5937           const char *name;
5938
5939           cdefs = 0;
5940           size = 0;
5941
5942           /* Make space for the base version.  */
5943           size += sizeof (Elf_External_Verdef);
5944           size += sizeof (Elf_External_Verdaux);
5945           ++cdefs;
5946
5947           /* Make space for the default version.  */
5948           if (info->create_default_symver)
5949             {
5950               size += sizeof (Elf_External_Verdef);
5951               ++cdefs;
5952             }
5953
5954           for (t = verdefs; t != NULL; t = t->next)
5955             {
5956               struct bfd_elf_version_deps *n;
5957
5958               /* Don't emit base version twice.  */
5959               if (t->vernum == 0)
5960                 continue;
5961
5962               size += sizeof (Elf_External_Verdef);
5963               size += sizeof (Elf_External_Verdaux);
5964               ++cdefs;
5965
5966               for (n = t->deps; n != NULL; n = n->next)
5967                 size += sizeof (Elf_External_Verdaux);
5968             }
5969
5970           s->size = size;
5971           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
5972           if (s->contents == NULL && s->size != 0)
5973             return FALSE;
5974
5975           /* Fill in the version definition section.  */
5976
5977           p = s->contents;
5978
5979           def.vd_version = VER_DEF_CURRENT;
5980           def.vd_flags = VER_FLG_BASE;
5981           def.vd_ndx = 1;
5982           def.vd_cnt = 1;
5983           if (info->create_default_symver)
5984             {
5985               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
5986               def.vd_next = sizeof (Elf_External_Verdef);
5987             }
5988           else
5989             {
5990               def.vd_aux = sizeof (Elf_External_Verdef);
5991               def.vd_next = (sizeof (Elf_External_Verdef)
5992                              + sizeof (Elf_External_Verdaux));
5993             }
5994
5995           if (soname_indx != (bfd_size_type) -1)
5996             {
5997               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5998                                       soname_indx);
5999               def.vd_hash = bfd_elf_hash (soname);
6000               defaux.vda_name = soname_indx;
6001               name = soname;
6002             }
6003           else
6004             {
6005               bfd_size_type indx;
6006
6007               name = lbasename (output_bfd->filename);
6008               def.vd_hash = bfd_elf_hash (name);
6009               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6010                                           name, FALSE);
6011               if (indx == (bfd_size_type) -1)
6012                 return FALSE;
6013               defaux.vda_name = indx;
6014             }
6015           defaux.vda_next = 0;
6016
6017           _bfd_elf_swap_verdef_out (output_bfd, &def,
6018                                     (Elf_External_Verdef *) p);
6019           p += sizeof (Elf_External_Verdef);
6020           if (info->create_default_symver)
6021             {
6022               /* Add a symbol representing this version.  */
6023               bh = NULL;
6024               if (! (_bfd_generic_link_add_one_symbol
6025                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6026                       0, NULL, FALSE,
6027                       get_elf_backend_data (dynobj)->collect, &bh)))
6028                 return FALSE;
6029               h = (struct elf_link_hash_entry *) bh;
6030               h->non_elf = 0;
6031               h->def_regular = 1;
6032               h->type = STT_OBJECT;
6033               h->verinfo.vertree = NULL;
6034
6035               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6036                 return FALSE;
6037
6038               /* Create a duplicate of the base version with the same
6039                  aux block, but different flags.  */
6040               def.vd_flags = 0;
6041               def.vd_ndx = 2;
6042               def.vd_aux = sizeof (Elf_External_Verdef);
6043               if (verdefs)
6044                 def.vd_next = (sizeof (Elf_External_Verdef)
6045                                + sizeof (Elf_External_Verdaux));
6046               else
6047                 def.vd_next = 0;
6048               _bfd_elf_swap_verdef_out (output_bfd, &def,
6049                                         (Elf_External_Verdef *) p);
6050               p += sizeof (Elf_External_Verdef);
6051             }
6052           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6053                                      (Elf_External_Verdaux *) p);
6054           p += sizeof (Elf_External_Verdaux);
6055
6056           for (t = verdefs; t != NULL; t = t->next)
6057             {
6058               unsigned int cdeps;
6059               struct bfd_elf_version_deps *n;
6060
6061               /* Don't emit the base version twice.  */
6062               if (t->vernum == 0)
6063                 continue;
6064
6065               cdeps = 0;
6066               for (n = t->deps; n != NULL; n = n->next)
6067                 ++cdeps;
6068
6069               /* Add a symbol representing this version.  */
6070               bh = NULL;
6071               if (! (_bfd_generic_link_add_one_symbol
6072                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6073                       0, NULL, FALSE,
6074                       get_elf_backend_data (dynobj)->collect, &bh)))
6075                 return FALSE;
6076               h = (struct elf_link_hash_entry *) bh;
6077               h->non_elf = 0;
6078               h->def_regular = 1;
6079               h->type = STT_OBJECT;
6080               h->verinfo.vertree = t;
6081
6082               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6083                 return FALSE;
6084
6085               def.vd_version = VER_DEF_CURRENT;
6086               def.vd_flags = 0;
6087               if (t->globals.list == NULL
6088                   && t->locals.list == NULL
6089                   && ! t->used)
6090                 def.vd_flags |= VER_FLG_WEAK;
6091               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6092               def.vd_cnt = cdeps + 1;
6093               def.vd_hash = bfd_elf_hash (t->name);
6094               def.vd_aux = sizeof (Elf_External_Verdef);
6095               def.vd_next = 0;
6096
6097               /* If a basever node is next, it *must* be the last node in
6098                  the chain, otherwise Verdef construction breaks.  */
6099               if (t->next != NULL && t->next->vernum == 0)
6100                 BFD_ASSERT (t->next->next == NULL);
6101
6102               if (t->next != NULL && t->next->vernum != 0)
6103                 def.vd_next = (sizeof (Elf_External_Verdef)
6104                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6105
6106               _bfd_elf_swap_verdef_out (output_bfd, &def,
6107                                         (Elf_External_Verdef *) p);
6108               p += sizeof (Elf_External_Verdef);
6109
6110               defaux.vda_name = h->dynstr_index;
6111               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6112                                       h->dynstr_index);
6113               defaux.vda_next = 0;
6114               if (t->deps != NULL)
6115                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6116               t->name_indx = defaux.vda_name;
6117
6118               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6119                                          (Elf_External_Verdaux *) p);
6120               p += sizeof (Elf_External_Verdaux);
6121
6122               for (n = t->deps; n != NULL; n = n->next)
6123                 {
6124                   if (n->version_needed == NULL)
6125                     {
6126                       /* This can happen if there was an error in the
6127                          version script.  */
6128                       defaux.vda_name = 0;
6129                     }
6130                   else
6131                     {
6132                       defaux.vda_name = n->version_needed->name_indx;
6133                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6134                                               defaux.vda_name);
6135                     }
6136                   if (n->next == NULL)
6137                     defaux.vda_next = 0;
6138                   else
6139                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6140
6141                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6142                                              (Elf_External_Verdaux *) p);
6143                   p += sizeof (Elf_External_Verdaux);
6144                 }
6145             }
6146
6147           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6148               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6149             return FALSE;
6150
6151           elf_tdata (output_bfd)->cverdefs = cdefs;
6152         }
6153
6154       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6155         {
6156           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6157             return FALSE;
6158         }
6159       else if (info->flags & DF_BIND_NOW)
6160         {
6161           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6162             return FALSE;
6163         }
6164
6165       if (info->flags_1)
6166         {
6167           if (info->executable)
6168             info->flags_1 &= ~ (DF_1_INITFIRST
6169                                 | DF_1_NODELETE
6170                                 | DF_1_NOOPEN);
6171           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6172             return FALSE;
6173         }
6174
6175       /* Work out the size of the version reference section.  */
6176
6177       s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
6178       BFD_ASSERT (s != NULL);
6179       {
6180         struct elf_find_verdep_info sinfo;
6181
6182         sinfo.info = info;
6183         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6184         if (sinfo.vers == 0)
6185           sinfo.vers = 1;
6186         sinfo.failed = FALSE;
6187
6188         elf_link_hash_traverse (elf_hash_table (info),
6189                                 _bfd_elf_link_find_version_dependencies,
6190                                 &sinfo);
6191         if (sinfo.failed)
6192           return FALSE;
6193
6194         if (elf_tdata (output_bfd)->verref == NULL)
6195           s->flags |= SEC_EXCLUDE;
6196         else
6197           {
6198             Elf_Internal_Verneed *t;
6199             unsigned int size;
6200             unsigned int crefs;
6201             bfd_byte *p;
6202
6203             /* Build the version dependency section.  */
6204             size = 0;
6205             crefs = 0;
6206             for (t = elf_tdata (output_bfd)->verref;
6207                  t != NULL;
6208                  t = t->vn_nextref)
6209               {
6210                 Elf_Internal_Vernaux *a;
6211
6212                 size += sizeof (Elf_External_Verneed);
6213                 ++crefs;
6214                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6215                   size += sizeof (Elf_External_Vernaux);
6216               }
6217
6218             s->size = size;
6219             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6220             if (s->contents == NULL)
6221               return FALSE;
6222
6223             p = s->contents;
6224             for (t = elf_tdata (output_bfd)->verref;
6225                  t != NULL;
6226                  t = t->vn_nextref)
6227               {
6228                 unsigned int caux;
6229                 Elf_Internal_Vernaux *a;
6230                 bfd_size_type indx;
6231
6232                 caux = 0;
6233                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6234                   ++caux;
6235
6236                 t->vn_version = VER_NEED_CURRENT;
6237                 t->vn_cnt = caux;
6238                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6239                                             elf_dt_name (t->vn_bfd) != NULL
6240                                             ? elf_dt_name (t->vn_bfd)
6241                                             : lbasename (t->vn_bfd->filename),
6242                                             FALSE);
6243                 if (indx == (bfd_size_type) -1)
6244                   return FALSE;
6245                 t->vn_file = indx;
6246                 t->vn_aux = sizeof (Elf_External_Verneed);
6247                 if (t->vn_nextref == NULL)
6248                   t->vn_next = 0;
6249                 else
6250                   t->vn_next = (sizeof (Elf_External_Verneed)
6251                                 + caux * sizeof (Elf_External_Vernaux));
6252
6253                 _bfd_elf_swap_verneed_out (output_bfd, t,
6254                                            (Elf_External_Verneed *) p);
6255                 p += sizeof (Elf_External_Verneed);
6256
6257                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6258                   {
6259                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6260                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6261                                                 a->vna_nodename, FALSE);
6262                     if (indx == (bfd_size_type) -1)
6263                       return FALSE;
6264                     a->vna_name = indx;
6265                     if (a->vna_nextptr == NULL)
6266                       a->vna_next = 0;
6267                     else
6268                       a->vna_next = sizeof (Elf_External_Vernaux);
6269
6270                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6271                                                (Elf_External_Vernaux *) p);
6272                     p += sizeof (Elf_External_Vernaux);
6273                   }
6274               }
6275
6276             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6277                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6278               return FALSE;
6279
6280             elf_tdata (output_bfd)->cverrefs = crefs;
6281           }
6282       }
6283
6284       if ((elf_tdata (output_bfd)->cverrefs == 0
6285            && elf_tdata (output_bfd)->cverdefs == 0)
6286           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6287                                              &section_sym_count) == 0)
6288         {
6289           s = bfd_get_section_by_name (dynobj, ".gnu.version");
6290           s->flags |= SEC_EXCLUDE;
6291         }
6292     }
6293   return TRUE;
6294 }
6295
6296 /* Find the first non-excluded output section.  We'll use its
6297    section symbol for some emitted relocs.  */
6298 void
6299 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6300 {
6301   asection *s;
6302
6303   for (s = output_bfd->sections; s != NULL; s = s->next)
6304     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6305         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6306       {
6307         elf_hash_table (info)->text_index_section = s;
6308         break;
6309       }
6310 }
6311
6312 /* Find two non-excluded output sections, one for code, one for data.
6313    We'll use their section symbols for some emitted relocs.  */
6314 void
6315 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6316 {
6317   asection *s;
6318
6319   /* Data first, since setting text_index_section changes
6320      _bfd_elf_link_omit_section_dynsym.  */
6321   for (s = output_bfd->sections; s != NULL; s = s->next)
6322     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6323         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6324       {
6325         elf_hash_table (info)->data_index_section = s;
6326         break;
6327       }
6328
6329   for (s = output_bfd->sections; s != NULL; s = s->next)
6330     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6331          == (SEC_ALLOC | SEC_READONLY))
6332         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6333       {
6334         elf_hash_table (info)->text_index_section = s;
6335         break;
6336       }
6337
6338   if (elf_hash_table (info)->text_index_section == NULL)
6339     elf_hash_table (info)->text_index_section
6340       = elf_hash_table (info)->data_index_section;
6341 }
6342
6343 bfd_boolean
6344 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6345 {
6346   const struct elf_backend_data *bed;
6347
6348   if (!is_elf_hash_table (info->hash))
6349     return TRUE;
6350
6351   bed = get_elf_backend_data (output_bfd);
6352   (*bed->elf_backend_init_index_section) (output_bfd, info);
6353
6354   if (elf_hash_table (info)->dynamic_sections_created)
6355     {
6356       bfd *dynobj;
6357       asection *s;
6358       bfd_size_type dynsymcount;
6359       unsigned long section_sym_count;
6360       unsigned int dtagcount;
6361
6362       dynobj = elf_hash_table (info)->dynobj;
6363
6364       /* Assign dynsym indicies.  In a shared library we generate a
6365          section symbol for each output section, which come first.
6366          Next come all of the back-end allocated local dynamic syms,
6367          followed by the rest of the global symbols.  */
6368
6369       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6370                                                     &section_sym_count);
6371
6372       /* Work out the size of the symbol version section.  */
6373       s = bfd_get_section_by_name (dynobj, ".gnu.version");
6374       BFD_ASSERT (s != NULL);
6375       if (dynsymcount != 0
6376           && (s->flags & SEC_EXCLUDE) == 0)
6377         {
6378           s->size = dynsymcount * sizeof (Elf_External_Versym);
6379           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6380           if (s->contents == NULL)
6381             return FALSE;
6382
6383           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6384             return FALSE;
6385         }
6386
6387       /* Set the size of the .dynsym and .hash sections.  We counted
6388          the number of dynamic symbols in elf_link_add_object_symbols.
6389          We will build the contents of .dynsym and .hash when we build
6390          the final symbol table, because until then we do not know the
6391          correct value to give the symbols.  We built the .dynstr
6392          section as we went along in elf_link_add_object_symbols.  */
6393       s = bfd_get_section_by_name (dynobj, ".dynsym");
6394       BFD_ASSERT (s != NULL);
6395       s->size = dynsymcount * bed->s->sizeof_sym;
6396
6397       if (dynsymcount != 0)
6398         {
6399           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6400           if (s->contents == NULL)
6401             return FALSE;
6402
6403           /* The first entry in .dynsym is a dummy symbol.
6404              Clear all the section syms, in case we don't output them all.  */
6405           ++section_sym_count;
6406           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6407         }
6408
6409       elf_hash_table (info)->bucketcount = 0;
6410
6411       /* Compute the size of the hashing table.  As a side effect this
6412          computes the hash values for all the names we export.  */
6413       if (info->emit_hash)
6414         {
6415           unsigned long int *hashcodes;
6416           struct hash_codes_info hashinf;
6417           bfd_size_type amt;
6418           unsigned long int nsyms;
6419           size_t bucketcount;
6420           size_t hash_entry_size;
6421
6422           /* Compute the hash values for all exported symbols.  At the same
6423              time store the values in an array so that we could use them for
6424              optimizations.  */
6425           amt = dynsymcount * sizeof (unsigned long int);
6426           hashcodes = (unsigned long int *) bfd_malloc (amt);
6427           if (hashcodes == NULL)
6428             return FALSE;
6429           hashinf.hashcodes = hashcodes;
6430           hashinf.error = FALSE;
6431
6432           /* Put all hash values in HASHCODES.  */
6433           elf_link_hash_traverse (elf_hash_table (info),
6434                                   elf_collect_hash_codes, &hashinf);
6435           if (hashinf.error)
6436             {
6437               free (hashcodes);
6438               return FALSE;
6439             }
6440
6441           nsyms = hashinf.hashcodes - hashcodes;
6442           bucketcount
6443             = compute_bucket_count (info, hashcodes, nsyms, 0);
6444           free (hashcodes);
6445
6446           if (bucketcount == 0)
6447             return FALSE;
6448
6449           elf_hash_table (info)->bucketcount = bucketcount;
6450
6451           s = bfd_get_section_by_name (dynobj, ".hash");
6452           BFD_ASSERT (s != NULL);
6453           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6454           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6455           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6456           if (s->contents == NULL)
6457             return FALSE;
6458
6459           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6460           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6461                    s->contents + hash_entry_size);
6462         }
6463
6464       if (info->emit_gnu_hash)
6465         {
6466           size_t i, cnt;
6467           unsigned char *contents;
6468           struct collect_gnu_hash_codes cinfo;
6469           bfd_size_type amt;
6470           size_t bucketcount;
6471
6472           memset (&cinfo, 0, sizeof (cinfo));
6473
6474           /* Compute the hash values for all exported symbols.  At the same
6475              time store the values in an array so that we could use them for
6476              optimizations.  */
6477           amt = dynsymcount * 2 * sizeof (unsigned long int);
6478           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6479           if (cinfo.hashcodes == NULL)
6480             return FALSE;
6481
6482           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6483           cinfo.min_dynindx = -1;
6484           cinfo.output_bfd = output_bfd;
6485           cinfo.bed = bed;
6486
6487           /* Put all hash values in HASHCODES.  */
6488           elf_link_hash_traverse (elf_hash_table (info),
6489                                   elf_collect_gnu_hash_codes, &cinfo);
6490           if (cinfo.error)
6491             {
6492               free (cinfo.hashcodes);
6493               return FALSE;
6494             }
6495
6496           bucketcount
6497             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6498
6499           if (bucketcount == 0)
6500             {
6501               free (cinfo.hashcodes);
6502               return FALSE;
6503             }
6504
6505           s = bfd_get_section_by_name (dynobj, ".gnu.hash");
6506           BFD_ASSERT (s != NULL);
6507
6508           if (cinfo.nsyms == 0)
6509             {
6510               /* Empty .gnu.hash section is special.  */
6511               BFD_ASSERT (cinfo.min_dynindx == -1);
6512               free (cinfo.hashcodes);
6513               s->size = 5 * 4 + bed->s->arch_size / 8;
6514               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6515               if (contents == NULL)
6516                 return FALSE;
6517               s->contents = contents;
6518               /* 1 empty bucket.  */
6519               bfd_put_32 (output_bfd, 1, contents);
6520               /* SYMIDX above the special symbol 0.  */
6521               bfd_put_32 (output_bfd, 1, contents + 4);
6522               /* Just one word for bitmask.  */
6523               bfd_put_32 (output_bfd, 1, contents + 8);
6524               /* Only hash fn bloom filter.  */
6525               bfd_put_32 (output_bfd, 0, contents + 12);
6526               /* No hashes are valid - empty bitmask.  */
6527               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6528               /* No hashes in the only bucket.  */
6529               bfd_put_32 (output_bfd, 0,
6530                           contents + 16 + bed->s->arch_size / 8);
6531             }
6532           else
6533             {
6534               unsigned long int maskwords, maskbitslog2, x;
6535               BFD_ASSERT (cinfo.min_dynindx != -1);
6536
6537               x = cinfo.nsyms;
6538               maskbitslog2 = 1;
6539               while ((x >>= 1) != 0)
6540                 ++maskbitslog2;
6541               if (maskbitslog2 < 3)
6542                 maskbitslog2 = 5;
6543               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6544                 maskbitslog2 = maskbitslog2 + 3;
6545               else
6546                 maskbitslog2 = maskbitslog2 + 2;
6547               if (bed->s->arch_size == 64)
6548                 {
6549                   if (maskbitslog2 == 5)
6550                     maskbitslog2 = 6;
6551                   cinfo.shift1 = 6;
6552                 }
6553               else
6554                 cinfo.shift1 = 5;
6555               cinfo.mask = (1 << cinfo.shift1) - 1;
6556               cinfo.shift2 = maskbitslog2;
6557               cinfo.maskbits = 1 << maskbitslog2;
6558               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6559               amt = bucketcount * sizeof (unsigned long int) * 2;
6560               amt += maskwords * sizeof (bfd_vma);
6561               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6562               if (cinfo.bitmask == NULL)
6563                 {
6564                   free (cinfo.hashcodes);
6565                   return FALSE;
6566                 }
6567
6568               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6569               cinfo.indx = cinfo.counts + bucketcount;
6570               cinfo.symindx = dynsymcount - cinfo.nsyms;
6571               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6572
6573               /* Determine how often each hash bucket is used.  */
6574               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6575               for (i = 0; i < cinfo.nsyms; ++i)
6576                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6577
6578               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6579                 if (cinfo.counts[i] != 0)
6580                   {
6581                     cinfo.indx[i] = cnt;
6582                     cnt += cinfo.counts[i];
6583                   }
6584               BFD_ASSERT (cnt == dynsymcount);
6585               cinfo.bucketcount = bucketcount;
6586               cinfo.local_indx = cinfo.min_dynindx;
6587
6588               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6589               s->size += cinfo.maskbits / 8;
6590               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6591               if (contents == NULL)
6592                 {
6593                   free (cinfo.bitmask);
6594                   free (cinfo.hashcodes);
6595                   return FALSE;
6596                 }
6597
6598               s->contents = contents;
6599               bfd_put_32 (output_bfd, bucketcount, contents);
6600               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6601               bfd_put_32 (output_bfd, maskwords, contents + 8);
6602               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6603               contents += 16 + cinfo.maskbits / 8;
6604
6605               for (i = 0; i < bucketcount; ++i)
6606                 {
6607                   if (cinfo.counts[i] == 0)
6608                     bfd_put_32 (output_bfd, 0, contents);
6609                   else
6610                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6611                   contents += 4;
6612                 }
6613
6614               cinfo.contents = contents;
6615
6616               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6617               elf_link_hash_traverse (elf_hash_table (info),
6618                                       elf_renumber_gnu_hash_syms, &cinfo);
6619
6620               contents = s->contents + 16;
6621               for (i = 0; i < maskwords; ++i)
6622                 {
6623                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6624                            contents);
6625                   contents += bed->s->arch_size / 8;
6626                 }
6627
6628               free (cinfo.bitmask);
6629               free (cinfo.hashcodes);
6630             }
6631         }
6632
6633       s = bfd_get_section_by_name (dynobj, ".dynstr");
6634       BFD_ASSERT (s != NULL);
6635
6636       elf_finalize_dynstr (output_bfd, info);
6637
6638       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6639
6640       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6641         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6642           return FALSE;
6643     }
6644
6645   return TRUE;
6646 }
6647 \f
6648 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6649
6650 static void
6651 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6652                             asection *sec)
6653 {
6654   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6655   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6656 }
6657
6658 /* Finish SHF_MERGE section merging.  */
6659
6660 bfd_boolean
6661 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6662 {
6663   bfd *ibfd;
6664   asection *sec;
6665
6666   if (!is_elf_hash_table (info->hash))
6667     return FALSE;
6668
6669   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
6670     if ((ibfd->flags & DYNAMIC) == 0)
6671       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6672         if ((sec->flags & SEC_MERGE) != 0
6673             && !bfd_is_abs_section (sec->output_section))
6674           {
6675             struct bfd_elf_section_data *secdata;
6676
6677             secdata = elf_section_data (sec);
6678             if (! _bfd_add_merge_section (abfd,
6679                                           &elf_hash_table (info)->merge_info,
6680                                           sec, &secdata->sec_info))
6681               return FALSE;
6682             else if (secdata->sec_info)
6683               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6684           }
6685
6686   if (elf_hash_table (info)->merge_info != NULL)
6687     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6688                          merge_sections_remove_hook);
6689   return TRUE;
6690 }
6691
6692 /* Create an entry in an ELF linker hash table.  */
6693
6694 struct bfd_hash_entry *
6695 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6696                             struct bfd_hash_table *table,
6697                             const char *string)
6698 {
6699   /* Allocate the structure if it has not already been allocated by a
6700      subclass.  */
6701   if (entry == NULL)
6702     {
6703       entry = (struct bfd_hash_entry *)
6704           bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6705       if (entry == NULL)
6706         return entry;
6707     }
6708
6709   /* Call the allocation method of the superclass.  */
6710   entry = _bfd_link_hash_newfunc (entry, table, string);
6711   if (entry != NULL)
6712     {
6713       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6714       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6715
6716       /* Set local fields.  */
6717       ret->indx = -1;
6718       ret->dynindx = -1;
6719       ret->got = htab->init_got_refcount;
6720       ret->plt = htab->init_plt_refcount;
6721       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6722                               - offsetof (struct elf_link_hash_entry, size)));
6723       /* Assume that we have been called by a non-ELF symbol reader.
6724          This flag is then reset by the code which reads an ELF input
6725          file.  This ensures that a symbol created by a non-ELF symbol
6726          reader will have the flag set correctly.  */
6727       ret->non_elf = 1;
6728     }
6729
6730   return entry;
6731 }
6732
6733 /* Copy data from an indirect symbol to its direct symbol, hiding the
6734    old indirect symbol.  Also used for copying flags to a weakdef.  */
6735
6736 void
6737 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6738                                   struct elf_link_hash_entry *dir,
6739                                   struct elf_link_hash_entry *ind)
6740 {
6741   struct elf_link_hash_table *htab;
6742
6743   /* Copy down any references that we may have already seen to the
6744      symbol which just became indirect.  */
6745
6746   dir->ref_dynamic |= ind->ref_dynamic;
6747   dir->ref_regular |= ind->ref_regular;
6748   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6749   dir->non_got_ref |= ind->non_got_ref;
6750   dir->needs_plt |= ind->needs_plt;
6751   dir->pointer_equality_needed |= ind->pointer_equality_needed;
6752
6753   if (ind->root.type != bfd_link_hash_indirect)
6754     return;
6755
6756   /* Copy over the global and procedure linkage table refcount entries.
6757      These may have been already set up by a check_relocs routine.  */
6758   htab = elf_hash_table (info);
6759   if (ind->got.refcount > htab->init_got_refcount.refcount)
6760     {
6761       if (dir->got.refcount < 0)
6762         dir->got.refcount = 0;
6763       dir->got.refcount += ind->got.refcount;
6764       ind->got.refcount = htab->init_got_refcount.refcount;
6765     }
6766
6767   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6768     {
6769       if (dir->plt.refcount < 0)
6770         dir->plt.refcount = 0;
6771       dir->plt.refcount += ind->plt.refcount;
6772       ind->plt.refcount = htab->init_plt_refcount.refcount;
6773     }
6774
6775   if (ind->dynindx != -1)
6776     {
6777       if (dir->dynindx != -1)
6778         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6779       dir->dynindx = ind->dynindx;
6780       dir->dynstr_index = ind->dynstr_index;
6781       ind->dynindx = -1;
6782       ind->dynstr_index = 0;
6783     }
6784 }
6785
6786 void
6787 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6788                                 struct elf_link_hash_entry *h,
6789                                 bfd_boolean force_local)
6790 {
6791   /* STT_GNU_IFUNC symbol must go through PLT.  */
6792   if (h->type != STT_GNU_IFUNC)
6793     {
6794       h->plt = elf_hash_table (info)->init_plt_offset;
6795       h->needs_plt = 0;
6796     }
6797   if (force_local)
6798     {
6799       h->forced_local = 1;
6800       if (h->dynindx != -1)
6801         {
6802           h->dynindx = -1;
6803           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6804                                   h->dynstr_index);
6805         }
6806     }
6807 }
6808
6809 /* Initialize an ELF linker hash table.  */
6810
6811 bfd_boolean
6812 _bfd_elf_link_hash_table_init
6813   (struct elf_link_hash_table *table,
6814    bfd *abfd,
6815    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6816                                       struct bfd_hash_table *,
6817                                       const char *),
6818    unsigned int entsize,
6819    enum elf_target_id target_id)
6820 {
6821   bfd_boolean ret;
6822   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6823
6824   memset (table, 0, sizeof * table);
6825   table->init_got_refcount.refcount = can_refcount - 1;
6826   table->init_plt_refcount.refcount = can_refcount - 1;
6827   table->init_got_offset.offset = -(bfd_vma) 1;
6828   table->init_plt_offset.offset = -(bfd_vma) 1;
6829   /* The first dynamic symbol is a dummy.  */
6830   table->dynsymcount = 1;
6831
6832   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6833
6834   table->root.type = bfd_link_elf_hash_table;
6835   table->hash_table_id = target_id;
6836
6837   return ret;
6838 }
6839
6840 /* Create an ELF linker hash table.  */
6841
6842 struct bfd_link_hash_table *
6843 _bfd_elf_link_hash_table_create (bfd *abfd)
6844 {
6845   struct elf_link_hash_table *ret;
6846   bfd_size_type amt = sizeof (struct elf_link_hash_table);
6847
6848   ret = (struct elf_link_hash_table *) bfd_malloc (amt);
6849   if (ret == NULL)
6850     return NULL;
6851
6852   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
6853                                        sizeof (struct elf_link_hash_entry),
6854                                        GENERIC_ELF_DATA))
6855     {
6856       free (ret);
6857       return NULL;
6858     }
6859
6860   return &ret->root;
6861 }
6862
6863 /* This is a hook for the ELF emulation code in the generic linker to
6864    tell the backend linker what file name to use for the DT_NEEDED
6865    entry for a dynamic object.  */
6866
6867 void
6868 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
6869 {
6870   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6871       && bfd_get_format (abfd) == bfd_object)
6872     elf_dt_name (abfd) = name;
6873 }
6874
6875 int
6876 bfd_elf_get_dyn_lib_class (bfd *abfd)
6877 {
6878   int lib_class;
6879   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6880       && bfd_get_format (abfd) == bfd_object)
6881     lib_class = elf_dyn_lib_class (abfd);
6882   else
6883     lib_class = 0;
6884   return lib_class;
6885 }
6886
6887 void
6888 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
6889 {
6890   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6891       && bfd_get_format (abfd) == bfd_object)
6892     elf_dyn_lib_class (abfd) = lib_class;
6893 }
6894
6895 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
6896    the linker ELF emulation code.  */
6897
6898 struct bfd_link_needed_list *
6899 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
6900                          struct bfd_link_info *info)
6901 {
6902   if (! is_elf_hash_table (info->hash))
6903     return NULL;
6904   return elf_hash_table (info)->needed;
6905 }
6906
6907 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
6908    hook for the linker ELF emulation code.  */
6909
6910 struct bfd_link_needed_list *
6911 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
6912                           struct bfd_link_info *info)
6913 {
6914   if (! is_elf_hash_table (info->hash))
6915     return NULL;
6916   return elf_hash_table (info)->runpath;
6917 }
6918
6919 /* Get the name actually used for a dynamic object for a link.  This
6920    is the SONAME entry if there is one.  Otherwise, it is the string
6921    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
6922
6923 const char *
6924 bfd_elf_get_dt_soname (bfd *abfd)
6925 {
6926   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6927       && bfd_get_format (abfd) == bfd_object)
6928     return elf_dt_name (abfd);
6929   return NULL;
6930 }
6931
6932 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
6933    the ELF linker emulation code.  */
6934
6935 bfd_boolean
6936 bfd_elf_get_bfd_needed_list (bfd *abfd,
6937                              struct bfd_link_needed_list **pneeded)
6938 {
6939   asection *s;
6940   bfd_byte *dynbuf = NULL;
6941   unsigned int elfsec;
6942   unsigned long shlink;
6943   bfd_byte *extdyn, *extdynend;
6944   size_t extdynsize;
6945   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
6946
6947   *pneeded = NULL;
6948
6949   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
6950       || bfd_get_format (abfd) != bfd_object)
6951     return TRUE;
6952
6953   s = bfd_get_section_by_name (abfd, ".dynamic");
6954   if (s == NULL || s->size == 0)
6955     return TRUE;
6956
6957   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
6958     goto error_return;
6959
6960   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
6961   if (elfsec == SHN_BAD)
6962     goto error_return;
6963
6964   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
6965
6966   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
6967   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
6968
6969   extdyn = dynbuf;
6970   extdynend = extdyn + s->size;
6971   for (; extdyn < extdynend; extdyn += extdynsize)
6972     {
6973       Elf_Internal_Dyn dyn;
6974
6975       (*swap_dyn_in) (abfd, extdyn, &dyn);
6976
6977       if (dyn.d_tag == DT_NULL)
6978         break;
6979
6980       if (dyn.d_tag == DT_NEEDED)
6981         {
6982           const char *string;
6983           struct bfd_link_needed_list *l;
6984           unsigned int tagv = dyn.d_un.d_val;
6985           bfd_size_type amt;
6986
6987           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
6988           if (string == NULL)
6989             goto error_return;
6990
6991           amt = sizeof *l;
6992           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
6993           if (l == NULL)
6994             goto error_return;
6995
6996           l->by = abfd;
6997           l->name = string;
6998           l->next = *pneeded;
6999           *pneeded = l;
7000         }
7001     }
7002
7003   free (dynbuf);
7004
7005   return TRUE;
7006
7007  error_return:
7008   if (dynbuf != NULL)
7009     free (dynbuf);
7010   return FALSE;
7011 }
7012
7013 struct elf_symbuf_symbol
7014 {
7015   unsigned long st_name;        /* Symbol name, index in string tbl */
7016   unsigned char st_info;        /* Type and binding attributes */
7017   unsigned char st_other;       /* Visibilty, and target specific */
7018 };
7019
7020 struct elf_symbuf_head
7021 {
7022   struct elf_symbuf_symbol *ssym;
7023   bfd_size_type count;
7024   unsigned int st_shndx;
7025 };
7026
7027 struct elf_symbol
7028 {
7029   union
7030     {
7031       Elf_Internal_Sym *isym;
7032       struct elf_symbuf_symbol *ssym;
7033     } u;
7034   const char *name;
7035 };
7036
7037 /* Sort references to symbols by ascending section number.  */
7038
7039 static int
7040 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7041 {
7042   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7043   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7044
7045   return s1->st_shndx - s2->st_shndx;
7046 }
7047
7048 static int
7049 elf_sym_name_compare (const void *arg1, const void *arg2)
7050 {
7051   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7052   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7053   return strcmp (s1->name, s2->name);
7054 }
7055
7056 static struct elf_symbuf_head *
7057 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7058 {
7059   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7060   struct elf_symbuf_symbol *ssym;
7061   struct elf_symbuf_head *ssymbuf, *ssymhead;
7062   bfd_size_type i, shndx_count, total_size;
7063
7064   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7065   if (indbuf == NULL)
7066     return NULL;
7067
7068   for (ind = indbuf, i = 0; i < symcount; i++)
7069     if (isymbuf[i].st_shndx != SHN_UNDEF)
7070       *ind++ = &isymbuf[i];
7071   indbufend = ind;
7072
7073   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7074          elf_sort_elf_symbol);
7075
7076   shndx_count = 0;
7077   if (indbufend > indbuf)
7078     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7079       if (ind[0]->st_shndx != ind[1]->st_shndx)
7080         shndx_count++;
7081
7082   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7083                 + (indbufend - indbuf) * sizeof (*ssym));
7084   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7085   if (ssymbuf == NULL)
7086     {
7087       free (indbuf);
7088       return NULL;
7089     }
7090
7091   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7092   ssymbuf->ssym = NULL;
7093   ssymbuf->count = shndx_count;
7094   ssymbuf->st_shndx = 0;
7095   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7096     {
7097       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7098         {
7099           ssymhead++;
7100           ssymhead->ssym = ssym;
7101           ssymhead->count = 0;
7102           ssymhead->st_shndx = (*ind)->st_shndx;
7103         }
7104       ssym->st_name = (*ind)->st_name;
7105       ssym->st_info = (*ind)->st_info;
7106       ssym->st_other = (*ind)->st_other;
7107       ssymhead->count++;
7108     }
7109   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7110               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7111                   == total_size));
7112
7113   free (indbuf);
7114   return ssymbuf;
7115 }
7116
7117 /* Check if 2 sections define the same set of local and global
7118    symbols.  */
7119
7120 static bfd_boolean
7121 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7122                                    struct bfd_link_info *info)
7123 {
7124   bfd *bfd1, *bfd2;
7125   const struct elf_backend_data *bed1, *bed2;
7126   Elf_Internal_Shdr *hdr1, *hdr2;
7127   bfd_size_type symcount1, symcount2;
7128   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7129   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7130   Elf_Internal_Sym *isym, *isymend;
7131   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7132   bfd_size_type count1, count2, i;
7133   unsigned int shndx1, shndx2;
7134   bfd_boolean result;
7135
7136   bfd1 = sec1->owner;
7137   bfd2 = sec2->owner;
7138
7139   /* Both sections have to be in ELF.  */
7140   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7141       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7142     return FALSE;
7143
7144   if (elf_section_type (sec1) != elf_section_type (sec2))
7145     return FALSE;
7146
7147   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7148   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7149   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7150     return FALSE;
7151
7152   bed1 = get_elf_backend_data (bfd1);
7153   bed2 = get_elf_backend_data (bfd2);
7154   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7155   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7156   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7157   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7158
7159   if (symcount1 == 0 || symcount2 == 0)
7160     return FALSE;
7161
7162   result = FALSE;
7163   isymbuf1 = NULL;
7164   isymbuf2 = NULL;
7165   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7166   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7167
7168   if (ssymbuf1 == NULL)
7169     {
7170       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7171                                        NULL, NULL, NULL);
7172       if (isymbuf1 == NULL)
7173         goto done;
7174
7175       if (!info->reduce_memory_overheads)
7176         elf_tdata (bfd1)->symbuf = ssymbuf1
7177           = elf_create_symbuf (symcount1, isymbuf1);
7178     }
7179
7180   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7181     {
7182       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7183                                        NULL, NULL, NULL);
7184       if (isymbuf2 == NULL)
7185         goto done;
7186
7187       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7188         elf_tdata (bfd2)->symbuf = ssymbuf2
7189           = elf_create_symbuf (symcount2, isymbuf2);
7190     }
7191
7192   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7193     {
7194       /* Optimized faster version.  */
7195       bfd_size_type lo, hi, mid;
7196       struct elf_symbol *symp;
7197       struct elf_symbuf_symbol *ssym, *ssymend;
7198
7199       lo = 0;
7200       hi = ssymbuf1->count;
7201       ssymbuf1++;
7202       count1 = 0;
7203       while (lo < hi)
7204         {
7205           mid = (lo + hi) / 2;
7206           if (shndx1 < ssymbuf1[mid].st_shndx)
7207             hi = mid;
7208           else if (shndx1 > ssymbuf1[mid].st_shndx)
7209             lo = mid + 1;
7210           else
7211             {
7212               count1 = ssymbuf1[mid].count;
7213               ssymbuf1 += mid;
7214               break;
7215             }
7216         }
7217
7218       lo = 0;
7219       hi = ssymbuf2->count;
7220       ssymbuf2++;
7221       count2 = 0;
7222       while (lo < hi)
7223         {
7224           mid = (lo + hi) / 2;
7225           if (shndx2 < ssymbuf2[mid].st_shndx)
7226             hi = mid;
7227           else if (shndx2 > ssymbuf2[mid].st_shndx)
7228             lo = mid + 1;
7229           else
7230             {
7231               count2 = ssymbuf2[mid].count;
7232               ssymbuf2 += mid;
7233               break;
7234             }
7235         }
7236
7237       if (count1 == 0 || count2 == 0 || count1 != count2)
7238         goto done;
7239
7240       symtable1 = (struct elf_symbol *)
7241           bfd_malloc (count1 * sizeof (struct elf_symbol));
7242       symtable2 = (struct elf_symbol *)
7243           bfd_malloc (count2 * sizeof (struct elf_symbol));
7244       if (symtable1 == NULL || symtable2 == NULL)
7245         goto done;
7246
7247       symp = symtable1;
7248       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7249            ssym < ssymend; ssym++, symp++)
7250         {
7251           symp->u.ssym = ssym;
7252           symp->name = bfd_elf_string_from_elf_section (bfd1,
7253                                                         hdr1->sh_link,
7254                                                         ssym->st_name);
7255         }
7256
7257       symp = symtable2;
7258       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7259            ssym < ssymend; ssym++, symp++)
7260         {
7261           symp->u.ssym = ssym;
7262           symp->name = bfd_elf_string_from_elf_section (bfd2,
7263                                                         hdr2->sh_link,
7264                                                         ssym->st_name);
7265         }
7266
7267       /* Sort symbol by name.  */
7268       qsort (symtable1, count1, sizeof (struct elf_symbol),
7269              elf_sym_name_compare);
7270       qsort (symtable2, count1, sizeof (struct elf_symbol),
7271              elf_sym_name_compare);
7272
7273       for (i = 0; i < count1; i++)
7274         /* Two symbols must have the same binding, type and name.  */
7275         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7276             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7277             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7278           goto done;
7279
7280       result = TRUE;
7281       goto done;
7282     }
7283
7284   symtable1 = (struct elf_symbol *)
7285       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7286   symtable2 = (struct elf_symbol *)
7287       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7288   if (symtable1 == NULL || symtable2 == NULL)
7289     goto done;
7290
7291   /* Count definitions in the section.  */
7292   count1 = 0;
7293   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7294     if (isym->st_shndx == shndx1)
7295       symtable1[count1++].u.isym = isym;
7296
7297   count2 = 0;
7298   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7299     if (isym->st_shndx == shndx2)
7300       symtable2[count2++].u.isym = isym;
7301
7302   if (count1 == 0 || count2 == 0 || count1 != count2)
7303     goto done;
7304
7305   for (i = 0; i < count1; i++)
7306     symtable1[i].name
7307       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7308                                          symtable1[i].u.isym->st_name);
7309
7310   for (i = 0; i < count2; i++)
7311     symtable2[i].name
7312       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7313                                          symtable2[i].u.isym->st_name);
7314
7315   /* Sort symbol by name.  */
7316   qsort (symtable1, count1, sizeof (struct elf_symbol),
7317          elf_sym_name_compare);
7318   qsort (symtable2, count1, sizeof (struct elf_symbol),
7319          elf_sym_name_compare);
7320
7321   for (i = 0; i < count1; i++)
7322     /* Two symbols must have the same binding, type and name.  */
7323     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7324         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7325         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7326       goto done;
7327
7328   result = TRUE;
7329
7330 done:
7331   if (symtable1)
7332     free (symtable1);
7333   if (symtable2)
7334     free (symtable2);
7335   if (isymbuf1)
7336     free (isymbuf1);
7337   if (isymbuf2)
7338     free (isymbuf2);
7339
7340   return result;
7341 }
7342
7343 /* Return TRUE if 2 section types are compatible.  */
7344
7345 bfd_boolean
7346 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7347                                  bfd *bbfd, const asection *bsec)
7348 {
7349   if (asec == NULL
7350       || bsec == NULL
7351       || abfd->xvec->flavour != bfd_target_elf_flavour
7352       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7353     return TRUE;
7354
7355   return elf_section_type (asec) == elf_section_type (bsec);
7356 }
7357 \f
7358 /* Final phase of ELF linker.  */
7359
7360 /* A structure we use to avoid passing large numbers of arguments.  */
7361
7362 struct elf_final_link_info
7363 {
7364   /* General link information.  */
7365   struct bfd_link_info *info;
7366   /* Output BFD.  */
7367   bfd *output_bfd;
7368   /* Symbol string table.  */
7369   struct bfd_strtab_hash *symstrtab;
7370   /* .dynsym section.  */
7371   asection *dynsym_sec;
7372   /* .hash section.  */
7373   asection *hash_sec;
7374   /* symbol version section (.gnu.version).  */
7375   asection *symver_sec;
7376   /* Buffer large enough to hold contents of any section.  */
7377   bfd_byte *contents;
7378   /* Buffer large enough to hold external relocs of any section.  */
7379   void *external_relocs;
7380   /* Buffer large enough to hold internal relocs of any section.  */
7381   Elf_Internal_Rela *internal_relocs;
7382   /* Buffer large enough to hold external local symbols of any input
7383      BFD.  */
7384   bfd_byte *external_syms;
7385   /* And a buffer for symbol section indices.  */
7386   Elf_External_Sym_Shndx *locsym_shndx;
7387   /* Buffer large enough to hold internal local symbols of any input
7388      BFD.  */
7389   Elf_Internal_Sym *internal_syms;
7390   /* Array large enough to hold a symbol index for each local symbol
7391      of any input BFD.  */
7392   long *indices;
7393   /* Array large enough to hold a section pointer for each local
7394      symbol of any input BFD.  */
7395   asection **sections;
7396   /* Buffer to hold swapped out symbols.  */
7397   bfd_byte *symbuf;
7398   /* And one for symbol section indices.  */
7399   Elf_External_Sym_Shndx *symshndxbuf;
7400   /* Number of swapped out symbols in buffer.  */
7401   size_t symbuf_count;
7402   /* Number of symbols which fit in symbuf.  */
7403   size_t symbuf_size;
7404   /* And same for symshndxbuf.  */
7405   size_t shndxbuf_size;
7406   /* Number of STT_FILE syms seen.  */
7407   size_t filesym_count;
7408 };
7409
7410 /* This struct is used to pass information to elf_link_output_extsym.  */
7411
7412 struct elf_outext_info
7413 {
7414   bfd_boolean failed;
7415   bfd_boolean localsyms;
7416   bfd_boolean need_second_pass;
7417   bfd_boolean second_pass;
7418   struct elf_final_link_info *flinfo;
7419 };
7420
7421
7422 /* Support for evaluating a complex relocation.
7423
7424    Complex relocations are generalized, self-describing relocations.  The
7425    implementation of them consists of two parts: complex symbols, and the
7426    relocations themselves.
7427
7428    The relocations are use a reserved elf-wide relocation type code (R_RELC
7429    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7430    information (start bit, end bit, word width, etc) into the addend.  This
7431    information is extracted from CGEN-generated operand tables within gas.
7432
7433    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7434    internal) representing prefix-notation expressions, including but not
7435    limited to those sorts of expressions normally encoded as addends in the
7436    addend field.  The symbol mangling format is:
7437
7438    <node> := <literal>
7439           |  <unary-operator> ':' <node>
7440           |  <binary-operator> ':' <node> ':' <node>
7441           ;
7442
7443    <literal> := 's' <digits=N> ':' <N character symbol name>
7444              |  'S' <digits=N> ':' <N character section name>
7445              |  '#' <hexdigits>
7446              ;
7447
7448    <binary-operator> := as in C
7449    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7450
7451 static void
7452 set_symbol_value (bfd *bfd_with_globals,
7453                   Elf_Internal_Sym *isymbuf,
7454                   size_t locsymcount,
7455                   size_t symidx,
7456                   bfd_vma val)
7457 {
7458   struct elf_link_hash_entry **sym_hashes;
7459   struct elf_link_hash_entry *h;
7460   size_t extsymoff = locsymcount;
7461
7462   if (symidx < locsymcount)
7463     {
7464       Elf_Internal_Sym *sym;
7465
7466       sym = isymbuf + symidx;
7467       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7468         {
7469           /* It is a local symbol: move it to the
7470              "absolute" section and give it a value.  */
7471           sym->st_shndx = SHN_ABS;
7472           sym->st_value = val;
7473           return;
7474         }
7475       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7476       extsymoff = 0;
7477     }
7478
7479   /* It is a global symbol: set its link type
7480      to "defined" and give it a value.  */
7481
7482   sym_hashes = elf_sym_hashes (bfd_with_globals);
7483   h = sym_hashes [symidx - extsymoff];
7484   while (h->root.type == bfd_link_hash_indirect
7485          || h->root.type == bfd_link_hash_warning)
7486     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7487   h->root.type = bfd_link_hash_defined;
7488   h->root.u.def.value = val;
7489   h->root.u.def.section = bfd_abs_section_ptr;
7490 }
7491
7492 static bfd_boolean
7493 resolve_symbol (const char *name,
7494                 bfd *input_bfd,
7495                 struct elf_final_link_info *flinfo,
7496                 bfd_vma *result,
7497                 Elf_Internal_Sym *isymbuf,
7498                 size_t locsymcount)
7499 {
7500   Elf_Internal_Sym *sym;
7501   struct bfd_link_hash_entry *global_entry;
7502   const char *candidate = NULL;
7503   Elf_Internal_Shdr *symtab_hdr;
7504   size_t i;
7505
7506   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7507
7508   for (i = 0; i < locsymcount; ++ i)
7509     {
7510       sym = isymbuf + i;
7511
7512       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7513         continue;
7514
7515       candidate = bfd_elf_string_from_elf_section (input_bfd,
7516                                                    symtab_hdr->sh_link,
7517                                                    sym->st_name);
7518 #ifdef DEBUG
7519       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7520               name, candidate, (unsigned long) sym->st_value);
7521 #endif
7522       if (candidate && strcmp (candidate, name) == 0)
7523         {
7524           asection *sec = flinfo->sections [i];
7525
7526           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7527           *result += sec->output_offset + sec->output_section->vma;
7528 #ifdef DEBUG
7529           printf ("Found symbol with value %8.8lx\n",
7530                   (unsigned long) *result);
7531 #endif
7532           return TRUE;
7533         }
7534     }
7535
7536   /* Hmm, haven't found it yet. perhaps it is a global.  */
7537   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7538                                        FALSE, FALSE, TRUE);
7539   if (!global_entry)
7540     return FALSE;
7541
7542   if (global_entry->type == bfd_link_hash_defined
7543       || global_entry->type == bfd_link_hash_defweak)
7544     {
7545       *result = (global_entry->u.def.value
7546                  + global_entry->u.def.section->output_section->vma
7547                  + global_entry->u.def.section->output_offset);
7548 #ifdef DEBUG
7549       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7550               global_entry->root.string, (unsigned long) *result);
7551 #endif
7552       return TRUE;
7553     }
7554
7555   return FALSE;
7556 }
7557
7558 static bfd_boolean
7559 resolve_section (const char *name,
7560                  asection *sections,
7561                  bfd_vma *result)
7562 {
7563   asection *curr;
7564   unsigned int len;
7565
7566   for (curr = sections; curr; curr = curr->next)
7567     if (strcmp (curr->name, name) == 0)
7568       {
7569         *result = curr->vma;
7570         return TRUE;
7571       }
7572
7573   /* Hmm. still haven't found it. try pseudo-section names.  */
7574   for (curr = sections; curr; curr = curr->next)
7575     {
7576       len = strlen (curr->name);
7577       if (len > strlen (name))
7578         continue;
7579
7580       if (strncmp (curr->name, name, len) == 0)
7581         {
7582           if (strncmp (".end", name + len, 4) == 0)
7583             {
7584               *result = curr->vma + curr->size;
7585               return TRUE;
7586             }
7587
7588           /* Insert more pseudo-section names here, if you like.  */
7589         }
7590     }
7591
7592   return FALSE;
7593 }
7594
7595 static void
7596 undefined_reference (const char *reftype, const char *name)
7597 {
7598   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7599                       reftype, name);
7600 }
7601
7602 static bfd_boolean
7603 eval_symbol (bfd_vma *result,
7604              const char **symp,
7605              bfd *input_bfd,
7606              struct elf_final_link_info *flinfo,
7607              bfd_vma dot,
7608              Elf_Internal_Sym *isymbuf,
7609              size_t locsymcount,
7610              int signed_p)
7611 {
7612   size_t len;
7613   size_t symlen;
7614   bfd_vma a;
7615   bfd_vma b;
7616   char symbuf[4096];
7617   const char *sym = *symp;
7618   const char *symend;
7619   bfd_boolean symbol_is_section = FALSE;
7620
7621   len = strlen (sym);
7622   symend = sym + len;
7623
7624   if (len < 1 || len > sizeof (symbuf))
7625     {
7626       bfd_set_error (bfd_error_invalid_operation);
7627       return FALSE;
7628     }
7629
7630   switch (* sym)
7631     {
7632     case '.':
7633       *result = dot;
7634       *symp = sym + 1;
7635       return TRUE;
7636
7637     case '#':
7638       ++sym;
7639       *result = strtoul (sym, (char **) symp, 16);
7640       return TRUE;
7641
7642     case 'S':
7643       symbol_is_section = TRUE;
7644     case 's':
7645       ++sym;
7646       symlen = strtol (sym, (char **) symp, 10);
7647       sym = *symp + 1; /* Skip the trailing ':'.  */
7648
7649       if (symend < sym || symlen + 1 > sizeof (symbuf))
7650         {
7651           bfd_set_error (bfd_error_invalid_operation);
7652           return FALSE;
7653         }
7654
7655       memcpy (symbuf, sym, symlen);
7656       symbuf[symlen] = '\0';
7657       *symp = sym + symlen;
7658
7659       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7660          the symbol as a section, or vice-versa. so we're pretty liberal in our
7661          interpretation here; section means "try section first", not "must be a
7662          section", and likewise with symbol.  */
7663
7664       if (symbol_is_section)
7665         {
7666           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7667               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7668                                   isymbuf, locsymcount))
7669             {
7670               undefined_reference ("section", symbuf);
7671               return FALSE;
7672             }
7673         }
7674       else
7675         {
7676           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7677                                isymbuf, locsymcount)
7678               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7679                                    result))
7680             {
7681               undefined_reference ("symbol", symbuf);
7682               return FALSE;
7683             }
7684         }
7685
7686       return TRUE;
7687
7688       /* All that remains are operators.  */
7689
7690 #define UNARY_OP(op)                                            \
7691   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7692     {                                                           \
7693       sym += strlen (#op);                                      \
7694       if (*sym == ':')                                          \
7695         ++sym;                                                  \
7696       *symp = sym;                                              \
7697       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7698                         isymbuf, locsymcount, signed_p))        \
7699         return FALSE;                                           \
7700       if (signed_p)                                             \
7701         *result = op ((bfd_signed_vma) a);                      \
7702       else                                                      \
7703         *result = op a;                                         \
7704       return TRUE;                                              \
7705     }
7706
7707 #define BINARY_OP(op)                                           \
7708   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7709     {                                                           \
7710       sym += strlen (#op);                                      \
7711       if (*sym == ':')                                          \
7712         ++sym;                                                  \
7713       *symp = sym;                                              \
7714       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7715                         isymbuf, locsymcount, signed_p))        \
7716         return FALSE;                                           \
7717       ++*symp;                                                  \
7718       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7719                         isymbuf, locsymcount, signed_p))        \
7720         return FALSE;                                           \
7721       if (signed_p)                                             \
7722         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7723       else                                                      \
7724         *result = a op b;                                       \
7725       return TRUE;                                              \
7726     }
7727
7728     default:
7729       UNARY_OP  (0-);
7730       BINARY_OP (<<);
7731       BINARY_OP (>>);
7732       BINARY_OP (==);
7733       BINARY_OP (!=);
7734       BINARY_OP (<=);
7735       BINARY_OP (>=);
7736       BINARY_OP (&&);
7737       BINARY_OP (||);
7738       UNARY_OP  (~);
7739       UNARY_OP  (!);
7740       BINARY_OP (*);
7741       BINARY_OP (/);
7742       BINARY_OP (%);
7743       BINARY_OP (^);
7744       BINARY_OP (|);
7745       BINARY_OP (&);
7746       BINARY_OP (+);
7747       BINARY_OP (-);
7748       BINARY_OP (<);
7749       BINARY_OP (>);
7750 #undef UNARY_OP
7751 #undef BINARY_OP
7752       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7753       bfd_set_error (bfd_error_invalid_operation);
7754       return FALSE;
7755     }
7756 }
7757
7758 static void
7759 put_value (bfd_vma size,
7760            unsigned long chunksz,
7761            bfd *input_bfd,
7762            bfd_vma x,
7763            bfd_byte *location)
7764 {
7765   location += (size - chunksz);
7766
7767   for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
7768     {
7769       switch (chunksz)
7770         {
7771         default:
7772         case 0:
7773           abort ();
7774         case 1:
7775           bfd_put_8 (input_bfd, x, location);
7776           break;
7777         case 2:
7778           bfd_put_16 (input_bfd, x, location);
7779           break;
7780         case 4:
7781           bfd_put_32 (input_bfd, x, location);
7782           break;
7783         case 8:
7784 #ifdef BFD64
7785           bfd_put_64 (input_bfd, x, location);
7786 #else
7787           abort ();
7788 #endif
7789           break;
7790         }
7791     }
7792 }
7793
7794 static bfd_vma
7795 get_value (bfd_vma size,
7796            unsigned long chunksz,
7797            bfd *input_bfd,
7798            bfd_byte *location)
7799 {
7800   bfd_vma x = 0;
7801
7802   for (; size; size -= chunksz, location += chunksz)
7803     {
7804       switch (chunksz)
7805         {
7806         default:
7807         case 0:
7808           abort ();
7809         case 1:
7810           x = (x << (8 * chunksz)) | bfd_get_8 (input_bfd, location);
7811           break;
7812         case 2:
7813           x = (x << (8 * chunksz)) | bfd_get_16 (input_bfd, location);
7814           break;
7815         case 4:
7816           x = (x << (8 * chunksz)) | bfd_get_32 (input_bfd, location);
7817           break;
7818         case 8:
7819 #ifdef BFD64
7820           x = (x << (8 * chunksz)) | bfd_get_64 (input_bfd, location);
7821 #else
7822           abort ();
7823 #endif
7824           break;
7825         }
7826     }
7827   return x;
7828 }
7829
7830 static void
7831 decode_complex_addend (unsigned long *start,   /* in bits */
7832                        unsigned long *oplen,   /* in bits */
7833                        unsigned long *len,     /* in bits */
7834                        unsigned long *wordsz,  /* in bytes */
7835                        unsigned long *chunksz, /* in bytes */
7836                        unsigned long *lsb0_p,
7837                        unsigned long *signed_p,
7838                        unsigned long *trunc_p,
7839                        unsigned long encoded)
7840 {
7841   * start     =  encoded        & 0x3F;
7842   * len       = (encoded >>  6) & 0x3F;
7843   * oplen     = (encoded >> 12) & 0x3F;
7844   * wordsz    = (encoded >> 18) & 0xF;
7845   * chunksz   = (encoded >> 22) & 0xF;
7846   * lsb0_p    = (encoded >> 27) & 1;
7847   * signed_p  = (encoded >> 28) & 1;
7848   * trunc_p   = (encoded >> 29) & 1;
7849 }
7850
7851 bfd_reloc_status_type
7852 bfd_elf_perform_complex_relocation (bfd *input_bfd,
7853                                     asection *input_section ATTRIBUTE_UNUSED,
7854                                     bfd_byte *contents,
7855                                     Elf_Internal_Rela *rel,
7856                                     bfd_vma relocation)
7857 {
7858   bfd_vma shift, x, mask;
7859   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
7860   bfd_reloc_status_type r;
7861
7862   /*  Perform this reloc, since it is complex.
7863       (this is not to say that it necessarily refers to a complex
7864       symbol; merely that it is a self-describing CGEN based reloc.
7865       i.e. the addend has the complete reloc information (bit start, end,
7866       word size, etc) encoded within it.).  */
7867
7868   decode_complex_addend (&start, &oplen, &len, &wordsz,
7869                          &chunksz, &lsb0_p, &signed_p,
7870                          &trunc_p, rel->r_addend);
7871
7872   mask = (((1L << (len - 1)) - 1) << 1) | 1;
7873
7874   if (lsb0_p)
7875     shift = (start + 1) - len;
7876   else
7877     shift = (8 * wordsz) - (start + len);
7878
7879   /* FIXME: octets_per_byte.  */
7880   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7881
7882 #ifdef DEBUG
7883   printf ("Doing complex reloc: "
7884           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7885           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7886           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7887           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7888           oplen, (unsigned long) x, (unsigned long) mask,
7889           (unsigned long) relocation);
7890 #endif
7891
7892   r = bfd_reloc_ok;
7893   if (! trunc_p)
7894     /* Now do an overflow check.  */
7895     r = bfd_check_overflow ((signed_p
7896                              ? complain_overflow_signed
7897                              : complain_overflow_unsigned),
7898                             len, 0, (8 * wordsz),
7899                             relocation);
7900
7901   /* Do the deed.  */
7902   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7903
7904 #ifdef DEBUG
7905   printf ("           relocation: %8.8lx\n"
7906           "         shifted mask: %8.8lx\n"
7907           " shifted/masked reloc: %8.8lx\n"
7908           "               result: %8.8lx\n",
7909           (unsigned long) relocation, (unsigned long) (mask << shift),
7910           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
7911 #endif
7912   /* FIXME: octets_per_byte.  */
7913   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7914   return r;
7915 }
7916
7917 /* When performing a relocatable link, the input relocations are
7918    preserved.  But, if they reference global symbols, the indices
7919    referenced must be updated.  Update all the relocations found in
7920    RELDATA.  */
7921
7922 static void
7923 elf_link_adjust_relocs (bfd *abfd,
7924                         struct bfd_elf_section_reloc_data *reldata)
7925 {
7926   unsigned int i;
7927   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7928   bfd_byte *erela;
7929   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7930   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7931   bfd_vma r_type_mask;
7932   int r_sym_shift;
7933   unsigned int count = reldata->count;
7934   struct elf_link_hash_entry **rel_hash = reldata->hashes;
7935
7936   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
7937     {
7938       swap_in = bed->s->swap_reloc_in;
7939       swap_out = bed->s->swap_reloc_out;
7940     }
7941   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
7942     {
7943       swap_in = bed->s->swap_reloca_in;
7944       swap_out = bed->s->swap_reloca_out;
7945     }
7946   else
7947     abort ();
7948
7949   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
7950     abort ();
7951
7952   if (bed->s->arch_size == 32)
7953     {
7954       r_type_mask = 0xff;
7955       r_sym_shift = 8;
7956     }
7957   else
7958     {
7959       r_type_mask = 0xffffffff;
7960       r_sym_shift = 32;
7961     }
7962
7963   erela = reldata->hdr->contents;
7964   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
7965     {
7966       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
7967       unsigned int j;
7968
7969       if (*rel_hash == NULL)
7970         continue;
7971
7972       BFD_ASSERT ((*rel_hash)->indx >= 0);
7973
7974       (*swap_in) (abfd, erela, irela);
7975       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
7976         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
7977                            | (irela[j].r_info & r_type_mask));
7978       (*swap_out) (abfd, irela, erela);
7979     }
7980 }
7981
7982 struct elf_link_sort_rela
7983 {
7984   union {
7985     bfd_vma offset;
7986     bfd_vma sym_mask;
7987   } u;
7988   enum elf_reloc_type_class type;
7989   /* We use this as an array of size int_rels_per_ext_rel.  */
7990   Elf_Internal_Rela rela[1];
7991 };
7992
7993 static int
7994 elf_link_sort_cmp1 (const void *A, const void *B)
7995 {
7996   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
7997   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
7998   int relativea, relativeb;
7999
8000   relativea = a->type == reloc_class_relative;
8001   relativeb = b->type == reloc_class_relative;
8002
8003   if (relativea < relativeb)
8004     return 1;
8005   if (relativea > relativeb)
8006     return -1;
8007   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8008     return -1;
8009   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8010     return 1;
8011   if (a->rela->r_offset < b->rela->r_offset)
8012     return -1;
8013   if (a->rela->r_offset > b->rela->r_offset)
8014     return 1;
8015   return 0;
8016 }
8017
8018 static int
8019 elf_link_sort_cmp2 (const void *A, const void *B)
8020 {
8021   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8022   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8023   int copya, copyb;
8024
8025   if (a->u.offset < b->u.offset)
8026     return -1;
8027   if (a->u.offset > b->u.offset)
8028     return 1;
8029   copya = (a->type == reloc_class_copy) * 2 + (a->type == reloc_class_plt);
8030   copyb = (b->type == reloc_class_copy) * 2 + (b->type == reloc_class_plt);
8031   if (copya < copyb)
8032     return -1;
8033   if (copya > copyb)
8034     return 1;
8035   if (a->rela->r_offset < b->rela->r_offset)
8036     return -1;
8037   if (a->rela->r_offset > b->rela->r_offset)
8038     return 1;
8039   return 0;
8040 }
8041
8042 static size_t
8043 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8044 {
8045   asection *dynamic_relocs;
8046   asection *rela_dyn;
8047   asection *rel_dyn;
8048   bfd_size_type count, size;
8049   size_t i, ret, sort_elt, ext_size;
8050   bfd_byte *sort, *s_non_relative, *p;
8051   struct elf_link_sort_rela *sq;
8052   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8053   int i2e = bed->s->int_rels_per_ext_rel;
8054   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8055   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8056   struct bfd_link_order *lo;
8057   bfd_vma r_sym_mask;
8058   bfd_boolean use_rela;
8059
8060   /* Find a dynamic reloc section.  */
8061   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8062   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8063   if (rela_dyn != NULL && rela_dyn->size > 0
8064       && rel_dyn != NULL && rel_dyn->size > 0)
8065     {
8066       bfd_boolean use_rela_initialised = FALSE;
8067
8068       /* This is just here to stop gcc from complaining.
8069          It's initialization checking code is not perfect.  */
8070       use_rela = TRUE;
8071
8072       /* Both sections are present.  Examine the sizes
8073          of the indirect sections to help us choose.  */
8074       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8075         if (lo->type == bfd_indirect_link_order)
8076           {
8077             asection *o = lo->u.indirect.section;
8078
8079             if ((o->size % bed->s->sizeof_rela) == 0)
8080               {
8081                 if ((o->size % bed->s->sizeof_rel) == 0)
8082                   /* Section size is divisible by both rel and rela sizes.
8083                      It is of no help to us.  */
8084                   ;
8085                 else
8086                   {
8087                     /* Section size is only divisible by rela.  */
8088                     if (use_rela_initialised && (use_rela == FALSE))
8089                       {
8090                         _bfd_error_handler
8091                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8092                         bfd_set_error (bfd_error_invalid_operation);
8093                         return 0;
8094                       }
8095                     else
8096                       {
8097                         use_rela = TRUE;
8098                         use_rela_initialised = TRUE;
8099                       }
8100                   }
8101               }
8102             else if ((o->size % bed->s->sizeof_rel) == 0)
8103               {
8104                 /* Section size is only divisible by rel.  */
8105                 if (use_rela_initialised && (use_rela == TRUE))
8106                   {
8107                     _bfd_error_handler
8108                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8109                     bfd_set_error (bfd_error_invalid_operation);
8110                     return 0;
8111                   }
8112                 else
8113                   {
8114                     use_rela = FALSE;
8115                     use_rela_initialised = TRUE;
8116                   }
8117               }
8118             else
8119               {
8120                 /* The section size is not divisible by either - something is wrong.  */
8121                 _bfd_error_handler
8122                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8123                 bfd_set_error (bfd_error_invalid_operation);
8124                 return 0;
8125               }
8126           }
8127
8128       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8129         if (lo->type == bfd_indirect_link_order)
8130           {
8131             asection *o = lo->u.indirect.section;
8132
8133             if ((o->size % bed->s->sizeof_rela) == 0)
8134               {
8135                 if ((o->size % bed->s->sizeof_rel) == 0)
8136                   /* Section size is divisible by both rel and rela sizes.
8137                      It is of no help to us.  */
8138                   ;
8139                 else
8140                   {
8141                     /* Section size is only divisible by rela.  */
8142                     if (use_rela_initialised && (use_rela == FALSE))
8143                       {
8144                         _bfd_error_handler
8145                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8146                         bfd_set_error (bfd_error_invalid_operation);
8147                         return 0;
8148                       }
8149                     else
8150                       {
8151                         use_rela = TRUE;
8152                         use_rela_initialised = TRUE;
8153                       }
8154                   }
8155               }
8156             else if ((o->size % bed->s->sizeof_rel) == 0)
8157               {
8158                 /* Section size is only divisible by rel.  */
8159                 if (use_rela_initialised && (use_rela == TRUE))
8160                   {
8161                     _bfd_error_handler
8162                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8163                     bfd_set_error (bfd_error_invalid_operation);
8164                     return 0;
8165                   }
8166                 else
8167                   {
8168                     use_rela = FALSE;
8169                     use_rela_initialised = TRUE;
8170                   }
8171               }
8172             else
8173               {
8174                 /* The section size is not divisible by either - something is wrong.  */
8175                 _bfd_error_handler
8176                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8177                 bfd_set_error (bfd_error_invalid_operation);
8178                 return 0;
8179               }
8180           }
8181
8182       if (! use_rela_initialised)
8183         /* Make a guess.  */
8184         use_rela = TRUE;
8185     }
8186   else if (rela_dyn != NULL && rela_dyn->size > 0)
8187     use_rela = TRUE;
8188   else if (rel_dyn != NULL && rel_dyn->size > 0)
8189     use_rela = FALSE;
8190   else
8191     return 0;
8192
8193   if (use_rela)
8194     {
8195       dynamic_relocs = rela_dyn;
8196       ext_size = bed->s->sizeof_rela;
8197       swap_in = bed->s->swap_reloca_in;
8198       swap_out = bed->s->swap_reloca_out;
8199     }
8200   else
8201     {
8202       dynamic_relocs = rel_dyn;
8203       ext_size = bed->s->sizeof_rel;
8204       swap_in = bed->s->swap_reloc_in;
8205       swap_out = bed->s->swap_reloc_out;
8206     }
8207
8208   size = 0;
8209   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8210     if (lo->type == bfd_indirect_link_order)
8211       size += lo->u.indirect.section->size;
8212
8213   if (size != dynamic_relocs->size)
8214     return 0;
8215
8216   sort_elt = (sizeof (struct elf_link_sort_rela)
8217               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8218
8219   count = dynamic_relocs->size / ext_size;
8220   if (count == 0)
8221     return 0;
8222   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8223
8224   if (sort == NULL)
8225     {
8226       (*info->callbacks->warning)
8227         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8228       return 0;
8229     }
8230
8231   if (bed->s->arch_size == 32)
8232     r_sym_mask = ~(bfd_vma) 0xff;
8233   else
8234     r_sym_mask = ~(bfd_vma) 0xffffffff;
8235
8236   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8237     if (lo->type == bfd_indirect_link_order)
8238       {
8239         bfd_byte *erel, *erelend;
8240         asection *o = lo->u.indirect.section;
8241
8242         if (o->contents == NULL && o->size != 0)
8243           {
8244             /* This is a reloc section that is being handled as a normal
8245                section.  See bfd_section_from_shdr.  We can't combine
8246                relocs in this case.  */
8247             free (sort);
8248             return 0;
8249           }
8250         erel = o->contents;
8251         erelend = o->contents + o->size;
8252         /* FIXME: octets_per_byte.  */
8253         p = sort + o->output_offset / ext_size * sort_elt;
8254
8255         while (erel < erelend)
8256           {
8257             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8258
8259             (*swap_in) (abfd, erel, s->rela);
8260             s->type = (*bed->elf_backend_reloc_type_class) (s->rela);
8261             s->u.sym_mask = r_sym_mask;
8262             p += sort_elt;
8263             erel += ext_size;
8264           }
8265       }
8266
8267   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8268
8269   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8270     {
8271       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8272       if (s->type != reloc_class_relative)
8273         break;
8274     }
8275   ret = i;
8276   s_non_relative = p;
8277
8278   sq = (struct elf_link_sort_rela *) s_non_relative;
8279   for (; i < count; i++, p += sort_elt)
8280     {
8281       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8282       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8283         sq = sp;
8284       sp->u.offset = sq->rela->r_offset;
8285     }
8286
8287   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8288
8289   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8290     if (lo->type == bfd_indirect_link_order)
8291       {
8292         bfd_byte *erel, *erelend;
8293         asection *o = lo->u.indirect.section;
8294
8295         erel = o->contents;
8296         erelend = o->contents + o->size;
8297         /* FIXME: octets_per_byte.  */
8298         p = sort + o->output_offset / ext_size * sort_elt;
8299         while (erel < erelend)
8300           {
8301             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8302             (*swap_out) (abfd, s->rela, erel);
8303             p += sort_elt;
8304             erel += ext_size;
8305           }
8306       }
8307
8308   free (sort);
8309   *psec = dynamic_relocs;
8310   return ret;
8311 }
8312
8313 /* Flush the output symbols to the file.  */
8314
8315 static bfd_boolean
8316 elf_link_flush_output_syms (struct elf_final_link_info *flinfo,
8317                             const struct elf_backend_data *bed)
8318 {
8319   if (flinfo->symbuf_count > 0)
8320     {
8321       Elf_Internal_Shdr *hdr;
8322       file_ptr pos;
8323       bfd_size_type amt;
8324
8325       hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8326       pos = hdr->sh_offset + hdr->sh_size;
8327       amt = flinfo->symbuf_count * bed->s->sizeof_sym;
8328       if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) != 0
8329           || bfd_bwrite (flinfo->symbuf, amt, flinfo->output_bfd) != amt)
8330         return FALSE;
8331
8332       hdr->sh_size += amt;
8333       flinfo->symbuf_count = 0;
8334     }
8335
8336   return TRUE;
8337 }
8338
8339 /* Add a symbol to the output symbol table.  */
8340
8341 static int
8342 elf_link_output_sym (struct elf_final_link_info *flinfo,
8343                      const char *name,
8344                      Elf_Internal_Sym *elfsym,
8345                      asection *input_sec,
8346                      struct elf_link_hash_entry *h)
8347 {
8348   bfd_byte *dest;
8349   Elf_External_Sym_Shndx *destshndx;
8350   int (*output_symbol_hook)
8351     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8352      struct elf_link_hash_entry *);
8353   const struct elf_backend_data *bed;
8354
8355   bed = get_elf_backend_data (flinfo->output_bfd);
8356   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8357   if (output_symbol_hook != NULL)
8358     {
8359       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8360       if (ret != 1)
8361         return ret;
8362     }
8363
8364   if (name == NULL || *name == '\0')
8365     elfsym->st_name = 0;
8366   else if (input_sec->flags & SEC_EXCLUDE)
8367     elfsym->st_name = 0;
8368   else
8369     {
8370       elfsym->st_name = (unsigned long) _bfd_stringtab_add (flinfo->symstrtab,
8371                                                             name, TRUE, FALSE);
8372       if (elfsym->st_name == (unsigned long) -1)
8373         return 0;
8374     }
8375
8376   if (flinfo->symbuf_count >= flinfo->symbuf_size)
8377     {
8378       if (! elf_link_flush_output_syms (flinfo, bed))
8379         return 0;
8380     }
8381
8382   dest = flinfo->symbuf + flinfo->symbuf_count * bed->s->sizeof_sym;
8383   destshndx = flinfo->symshndxbuf;
8384   if (destshndx != NULL)
8385     {
8386       if (bfd_get_symcount (flinfo->output_bfd) >= flinfo->shndxbuf_size)
8387         {
8388           bfd_size_type amt;
8389
8390           amt = flinfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
8391           destshndx = (Elf_External_Sym_Shndx *) bfd_realloc (destshndx,
8392                                                               amt * 2);
8393           if (destshndx == NULL)
8394             return 0;
8395           flinfo->symshndxbuf = destshndx;
8396           memset ((char *) destshndx + amt, 0, amt);
8397           flinfo->shndxbuf_size *= 2;
8398         }
8399       destshndx += bfd_get_symcount (flinfo->output_bfd);
8400     }
8401
8402   bed->s->swap_symbol_out (flinfo->output_bfd, elfsym, dest, destshndx);
8403   flinfo->symbuf_count += 1;
8404   bfd_get_symcount (flinfo->output_bfd) += 1;
8405
8406   return 1;
8407 }
8408
8409 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8410
8411 static bfd_boolean
8412 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8413 {
8414   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8415       && sym->st_shndx < SHN_LORESERVE)
8416     {
8417       /* The gABI doesn't support dynamic symbols in output sections
8418          beyond 64k.  */
8419       (*_bfd_error_handler)
8420         (_("%B: Too many sections: %d (>= %d)"),
8421          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8422       bfd_set_error (bfd_error_nonrepresentable_section);
8423       return FALSE;
8424     }
8425   return TRUE;
8426 }
8427
8428 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8429    allowing an unsatisfied unversioned symbol in the DSO to match a
8430    versioned symbol that would normally require an explicit version.
8431    We also handle the case that a DSO references a hidden symbol
8432    which may be satisfied by a versioned symbol in another DSO.  */
8433
8434 static bfd_boolean
8435 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8436                                  const struct elf_backend_data *bed,
8437                                  struct elf_link_hash_entry *h)
8438 {
8439   bfd *abfd;
8440   struct elf_link_loaded_list *loaded;
8441
8442   if (!is_elf_hash_table (info->hash))
8443     return FALSE;
8444
8445   switch (h->root.type)
8446     {
8447     default:
8448       abfd = NULL;
8449       break;
8450
8451     case bfd_link_hash_undefined:
8452     case bfd_link_hash_undefweak:
8453       abfd = h->root.u.undef.abfd;
8454       if ((abfd->flags & DYNAMIC) == 0
8455           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8456         return FALSE;
8457       break;
8458
8459     case bfd_link_hash_defined:
8460     case bfd_link_hash_defweak:
8461       abfd = h->root.u.def.section->owner;
8462       break;
8463
8464     case bfd_link_hash_common:
8465       abfd = h->root.u.c.p->section->owner;
8466       break;
8467     }
8468   BFD_ASSERT (abfd != NULL);
8469
8470   for (loaded = elf_hash_table (info)->loaded;
8471        loaded != NULL;
8472        loaded = loaded->next)
8473     {
8474       bfd *input;
8475       Elf_Internal_Shdr *hdr;
8476       bfd_size_type symcount;
8477       bfd_size_type extsymcount;
8478       bfd_size_type extsymoff;
8479       Elf_Internal_Shdr *versymhdr;
8480       Elf_Internal_Sym *isym;
8481       Elf_Internal_Sym *isymend;
8482       Elf_Internal_Sym *isymbuf;
8483       Elf_External_Versym *ever;
8484       Elf_External_Versym *extversym;
8485
8486       input = loaded->abfd;
8487
8488       /* We check each DSO for a possible hidden versioned definition.  */
8489       if (input == abfd
8490           || (input->flags & DYNAMIC) == 0
8491           || elf_dynversym (input) == 0)
8492         continue;
8493
8494       hdr = &elf_tdata (input)->dynsymtab_hdr;
8495
8496       symcount = hdr->sh_size / bed->s->sizeof_sym;
8497       if (elf_bad_symtab (input))
8498         {
8499           extsymcount = symcount;
8500           extsymoff = 0;
8501         }
8502       else
8503         {
8504           extsymcount = symcount - hdr->sh_info;
8505           extsymoff = hdr->sh_info;
8506         }
8507
8508       if (extsymcount == 0)
8509         continue;
8510
8511       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8512                                       NULL, NULL, NULL);
8513       if (isymbuf == NULL)
8514         return FALSE;
8515
8516       /* Read in any version definitions.  */
8517       versymhdr = &elf_tdata (input)->dynversym_hdr;
8518       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8519       if (extversym == NULL)
8520         goto error_ret;
8521
8522       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8523           || (bfd_bread (extversym, versymhdr->sh_size, input)
8524               != versymhdr->sh_size))
8525         {
8526           free (extversym);
8527         error_ret:
8528           free (isymbuf);
8529           return FALSE;
8530         }
8531
8532       ever = extversym + extsymoff;
8533       isymend = isymbuf + extsymcount;
8534       for (isym = isymbuf; isym < isymend; isym++, ever++)
8535         {
8536           const char *name;
8537           Elf_Internal_Versym iver;
8538           unsigned short version_index;
8539
8540           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8541               || isym->st_shndx == SHN_UNDEF)
8542             continue;
8543
8544           name = bfd_elf_string_from_elf_section (input,
8545                                                   hdr->sh_link,
8546                                                   isym->st_name);
8547           if (strcmp (name, h->root.root.string) != 0)
8548             continue;
8549
8550           _bfd_elf_swap_versym_in (input, ever, &iver);
8551
8552           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8553               && !(h->def_regular
8554                    && h->forced_local))
8555             {
8556               /* If we have a non-hidden versioned sym, then it should
8557                  have provided a definition for the undefined sym unless
8558                  it is defined in a non-shared object and forced local.
8559                */
8560               abort ();
8561             }
8562
8563           version_index = iver.vs_vers & VERSYM_VERSION;
8564           if (version_index == 1 || version_index == 2)
8565             {
8566               /* This is the base or first version.  We can use it.  */
8567               free (extversym);
8568               free (isymbuf);
8569               return TRUE;
8570             }
8571         }
8572
8573       free (extversym);
8574       free (isymbuf);
8575     }
8576
8577   return FALSE;
8578 }
8579
8580 /* Add an external symbol to the symbol table.  This is called from
8581    the hash table traversal routine.  When generating a shared object,
8582    we go through the symbol table twice.  The first time we output
8583    anything that might have been forced to local scope in a version
8584    script.  The second time we output the symbols that are still
8585    global symbols.  */
8586
8587 static bfd_boolean
8588 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8589 {
8590   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8591   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8592   struct elf_final_link_info *flinfo = eoinfo->flinfo;
8593   bfd_boolean strip;
8594   Elf_Internal_Sym sym;
8595   asection *input_sec;
8596   const struct elf_backend_data *bed;
8597   long indx;
8598   int ret;
8599
8600   if (h->root.type == bfd_link_hash_warning)
8601     {
8602       h = (struct elf_link_hash_entry *) h->root.u.i.link;
8603       if (h->root.type == bfd_link_hash_new)
8604         return TRUE;
8605     }
8606
8607   /* Decide whether to output this symbol in this pass.  */
8608   if (eoinfo->localsyms)
8609     {
8610       if (!h->forced_local)
8611         return TRUE;
8612       if (eoinfo->second_pass
8613           && !((h->root.type == bfd_link_hash_defined
8614                 || h->root.type == bfd_link_hash_defweak)
8615                && h->root.u.def.section->output_section != NULL))
8616         return TRUE;
8617     }
8618   else
8619     {
8620       if (h->forced_local)
8621         return TRUE;
8622     }
8623
8624   bed = get_elf_backend_data (flinfo->output_bfd);
8625
8626   if (h->root.type == bfd_link_hash_undefined)
8627     {
8628       /* If we have an undefined symbol reference here then it must have
8629          come from a shared library that is being linked in.  (Undefined
8630          references in regular files have already been handled unless
8631          they are in unreferenced sections which are removed by garbage
8632          collection).  */
8633       bfd_boolean ignore_undef = FALSE;
8634
8635       /* Some symbols may be special in that the fact that they're
8636          undefined can be safely ignored - let backend determine that.  */
8637       if (bed->elf_backend_ignore_undef_symbol)
8638         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
8639
8640       /* If we are reporting errors for this situation then do so now.  */
8641       if (!ignore_undef
8642           && h->ref_dynamic
8643           && (!h->ref_regular || flinfo->info->gc_sections)
8644           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
8645           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
8646         {
8647           if (!(flinfo->info->callbacks->undefined_symbol
8648                 (flinfo->info, h->root.root.string,
8649                  h->ref_regular ? NULL : h->root.u.undef.abfd,
8650                  NULL, 0,
8651                  (flinfo->info->unresolved_syms_in_shared_libs
8652                   == RM_GENERATE_ERROR))))
8653             {
8654               bfd_set_error (bfd_error_bad_value);
8655               eoinfo->failed = TRUE;
8656               return FALSE;
8657             }
8658         }
8659     }
8660
8661   /* We should also warn if a forced local symbol is referenced from
8662      shared libraries.  */
8663   if (!flinfo->info->relocatable
8664       && flinfo->info->executable
8665       && h->forced_local
8666       && h->ref_dynamic
8667       && h->def_regular
8668       && !h->dynamic_def
8669       && !h->dynamic_weak
8670       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
8671     {
8672       bfd *def_bfd;
8673       const char *msg;
8674
8675       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
8676         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
8677       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
8678         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
8679       else
8680         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
8681       def_bfd = flinfo->output_bfd;
8682       if (h->root.u.def.section != bfd_abs_section_ptr)
8683         def_bfd = h->root.u.def.section->owner;
8684       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
8685                              h->root.root.string);
8686       bfd_set_error (bfd_error_bad_value);
8687       eoinfo->failed = TRUE;
8688       return FALSE;
8689     }
8690
8691   /* We don't want to output symbols that have never been mentioned by
8692      a regular file, or that we have been told to strip.  However, if
8693      h->indx is set to -2, the symbol is used by a reloc and we must
8694      output it.  */
8695   if (h->indx == -2)
8696     strip = FALSE;
8697   else if ((h->def_dynamic
8698             || h->ref_dynamic
8699             || h->root.type == bfd_link_hash_new)
8700            && !h->def_regular
8701            && !h->ref_regular)
8702     strip = TRUE;
8703   else if (flinfo->info->strip == strip_all)
8704     strip = TRUE;
8705   else if (flinfo->info->strip == strip_some
8706            && bfd_hash_lookup (flinfo->info->keep_hash,
8707                                h->root.root.string, FALSE, FALSE) == NULL)
8708     strip = TRUE;
8709   else if ((h->root.type == bfd_link_hash_defined
8710             || h->root.type == bfd_link_hash_defweak)
8711            && ((flinfo->info->strip_discarded
8712                 && discarded_section (h->root.u.def.section))
8713                || (h->root.u.def.section->owner != NULL
8714                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
8715     strip = TRUE;
8716   else if ((h->root.type == bfd_link_hash_undefined
8717             || h->root.type == bfd_link_hash_undefweak)
8718            && h->root.u.undef.abfd != NULL
8719            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
8720     strip = TRUE;
8721   else
8722     strip = FALSE;
8723
8724   /* If we're stripping it, and it's not a dynamic symbol, there's
8725      nothing else to do unless it is a forced local symbol or a
8726      STT_GNU_IFUNC symbol.  */
8727   if (strip
8728       && h->dynindx == -1
8729       && h->type != STT_GNU_IFUNC
8730       && !h->forced_local)
8731     return TRUE;
8732
8733   sym.st_value = 0;
8734   sym.st_size = h->size;
8735   sym.st_other = h->other;
8736   if (h->forced_local)
8737     {
8738       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
8739       /* Turn off visibility on local symbol.  */
8740       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
8741     }
8742   else if (h->unique_global)
8743     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
8744   else if (h->root.type == bfd_link_hash_undefweak
8745            || h->root.type == bfd_link_hash_defweak)
8746     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
8747   else
8748     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
8749   sym.st_target_internal = h->target_internal;
8750
8751   switch (h->root.type)
8752     {
8753     default:
8754     case bfd_link_hash_new:
8755     case bfd_link_hash_warning:
8756       abort ();
8757       return FALSE;
8758
8759     case bfd_link_hash_undefined:
8760     case bfd_link_hash_undefweak:
8761       input_sec = bfd_und_section_ptr;
8762       sym.st_shndx = SHN_UNDEF;
8763       break;
8764
8765     case bfd_link_hash_defined:
8766     case bfd_link_hash_defweak:
8767       {
8768         input_sec = h->root.u.def.section;
8769         if (input_sec->output_section != NULL)
8770           {
8771             if (eoinfo->localsyms && flinfo->filesym_count == 1)
8772               {
8773                 bfd_boolean second_pass_sym
8774                   = (input_sec->owner == flinfo->output_bfd
8775                      || input_sec->owner == NULL
8776                      || (input_sec->flags & SEC_LINKER_CREATED) != 0
8777                      || (input_sec->owner->flags & BFD_LINKER_CREATED) != 0);
8778
8779                 eoinfo->need_second_pass |= second_pass_sym;
8780                 if (eoinfo->second_pass != second_pass_sym)
8781                   return TRUE;
8782               }
8783
8784             sym.st_shndx =
8785               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
8786                                                  input_sec->output_section);
8787             if (sym.st_shndx == SHN_BAD)
8788               {
8789                 (*_bfd_error_handler)
8790                   (_("%B: could not find output section %A for input section %A"),
8791                    flinfo->output_bfd, input_sec->output_section, input_sec);
8792                 bfd_set_error (bfd_error_nonrepresentable_section);
8793                 eoinfo->failed = TRUE;
8794                 return FALSE;
8795               }
8796
8797             /* ELF symbols in relocatable files are section relative,
8798                but in nonrelocatable files they are virtual
8799                addresses.  */
8800             sym.st_value = h->root.u.def.value + input_sec->output_offset;
8801             if (!flinfo->info->relocatable)
8802               {
8803                 sym.st_value += input_sec->output_section->vma;
8804                 if (h->type == STT_TLS)
8805                   {
8806                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
8807                     if (tls_sec != NULL)
8808                       sym.st_value -= tls_sec->vma;
8809                     else
8810                       {
8811                         /* The TLS section may have been garbage collected.  */
8812                         BFD_ASSERT (flinfo->info->gc_sections
8813                                     && !input_sec->gc_mark);
8814                       }
8815                   }
8816               }
8817           }
8818         else
8819           {
8820             BFD_ASSERT (input_sec->owner == NULL
8821                         || (input_sec->owner->flags & DYNAMIC) != 0);
8822             sym.st_shndx = SHN_UNDEF;
8823             input_sec = bfd_und_section_ptr;
8824           }
8825       }
8826       break;
8827
8828     case bfd_link_hash_common:
8829       input_sec = h->root.u.c.p->section;
8830       sym.st_shndx = bed->common_section_index (input_sec);
8831       sym.st_value = 1 << h->root.u.c.p->alignment_power;
8832       break;
8833
8834     case bfd_link_hash_indirect:
8835       /* These symbols are created by symbol versioning.  They point
8836          to the decorated version of the name.  For example, if the
8837          symbol foo@@GNU_1.2 is the default, which should be used when
8838          foo is used with no version, then we add an indirect symbol
8839          foo which points to foo@@GNU_1.2.  We ignore these symbols,
8840          since the indirected symbol is already in the hash table.  */
8841       return TRUE;
8842     }
8843
8844   /* Give the processor backend a chance to tweak the symbol value,
8845      and also to finish up anything that needs to be done for this
8846      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
8847      forced local syms when non-shared is due to a historical quirk.
8848      STT_GNU_IFUNC symbol must go through PLT.  */
8849   if ((h->type == STT_GNU_IFUNC
8850        && h->def_regular
8851        && !flinfo->info->relocatable)
8852       || ((h->dynindx != -1
8853            || h->forced_local)
8854           && ((flinfo->info->shared
8855                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
8856                    || h->root.type != bfd_link_hash_undefweak))
8857               || !h->forced_local)
8858           && elf_hash_table (flinfo->info)->dynamic_sections_created))
8859     {
8860       if (! ((*bed->elf_backend_finish_dynamic_symbol)
8861              (flinfo->output_bfd, flinfo->info, h, &sym)))
8862         {
8863           eoinfo->failed = TRUE;
8864           return FALSE;
8865         }
8866     }
8867
8868   /* If we are marking the symbol as undefined, and there are no
8869      non-weak references to this symbol from a regular object, then
8870      mark the symbol as weak undefined; if there are non-weak
8871      references, mark the symbol as strong.  We can't do this earlier,
8872      because it might not be marked as undefined until the
8873      finish_dynamic_symbol routine gets through with it.  */
8874   if (sym.st_shndx == SHN_UNDEF
8875       && h->ref_regular
8876       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
8877           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
8878     {
8879       int bindtype;
8880       unsigned int type = ELF_ST_TYPE (sym.st_info);
8881
8882       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
8883       if (type == STT_GNU_IFUNC)
8884         type = STT_FUNC;
8885
8886       if (h->ref_regular_nonweak)
8887         bindtype = STB_GLOBAL;
8888       else
8889         bindtype = STB_WEAK;
8890       sym.st_info = ELF_ST_INFO (bindtype, type);
8891     }
8892
8893   /* If this is a symbol defined in a dynamic library, don't use the
8894      symbol size from the dynamic library.  Relinking an executable
8895      against a new library may introduce gratuitous changes in the
8896      executable's symbols if we keep the size.  */
8897   if (sym.st_shndx == SHN_UNDEF
8898       && !h->def_regular
8899       && h->def_dynamic)
8900     sym.st_size = 0;
8901
8902   /* If a non-weak symbol with non-default visibility is not defined
8903      locally, it is a fatal error.  */
8904   if (!flinfo->info->relocatable
8905       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
8906       && ELF_ST_BIND (sym.st_info) != STB_WEAK
8907       && h->root.type == bfd_link_hash_undefined
8908       && !h->def_regular)
8909     {
8910       const char *msg;
8911
8912       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
8913         msg = _("%B: protected symbol `%s' isn't defined");
8914       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
8915         msg = _("%B: internal symbol `%s' isn't defined");
8916       else
8917         msg = _("%B: hidden symbol `%s' isn't defined");
8918       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
8919       bfd_set_error (bfd_error_bad_value);
8920       eoinfo->failed = TRUE;
8921       return FALSE;
8922     }
8923
8924   /* If this symbol should be put in the .dynsym section, then put it
8925      there now.  We already know the symbol index.  We also fill in
8926      the entry in the .hash section.  */
8927   if (flinfo->dynsym_sec != NULL
8928       && h->dynindx != -1
8929       && elf_hash_table (flinfo->info)->dynamic_sections_created)
8930     {
8931       bfd_byte *esym;
8932
8933       sym.st_name = h->dynstr_index;
8934       esym = flinfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
8935       if (!check_dynsym (flinfo->output_bfd, &sym))
8936         {
8937           eoinfo->failed = TRUE;
8938           return FALSE;
8939         }
8940       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
8941
8942       if (flinfo->hash_sec != NULL)
8943         {
8944           size_t hash_entry_size;
8945           bfd_byte *bucketpos;
8946           bfd_vma chain;
8947           size_t bucketcount;
8948           size_t bucket;
8949
8950           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
8951           bucket = h->u.elf_hash_value % bucketcount;
8952
8953           hash_entry_size
8954             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
8955           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
8956                        + (bucket + 2) * hash_entry_size);
8957           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
8958           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
8959                    bucketpos);
8960           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
8961                    ((bfd_byte *) flinfo->hash_sec->contents
8962                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
8963         }
8964
8965       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
8966         {
8967           Elf_Internal_Versym iversym;
8968           Elf_External_Versym *eversym;
8969
8970           if (!h->def_regular)
8971             {
8972               if (h->verinfo.verdef == NULL)
8973                 iversym.vs_vers = 0;
8974               else
8975                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
8976             }
8977           else
8978             {
8979               if (h->verinfo.vertree == NULL)
8980                 iversym.vs_vers = 1;
8981               else
8982                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
8983               if (flinfo->info->create_default_symver)
8984                 iversym.vs_vers++;
8985             }
8986
8987           if (h->hidden)
8988             iversym.vs_vers |= VERSYM_HIDDEN;
8989
8990           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
8991           eversym += h->dynindx;
8992           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
8993         }
8994     }
8995
8996   /* If we're stripping it, then it was just a dynamic symbol, and
8997      there's nothing else to do.  */
8998   if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
8999     return TRUE;
9000
9001   indx = bfd_get_symcount (flinfo->output_bfd);
9002   ret = elf_link_output_sym (flinfo, h->root.root.string, &sym, input_sec, h);
9003   if (ret == 0)
9004     {
9005       eoinfo->failed = TRUE;
9006       return FALSE;
9007     }
9008   else if (ret == 1)
9009     h->indx = indx;
9010   else if (h->indx == -2)
9011     abort();
9012
9013   return TRUE;
9014 }
9015
9016 /* Return TRUE if special handling is done for relocs in SEC against
9017    symbols defined in discarded sections.  */
9018
9019 static bfd_boolean
9020 elf_section_ignore_discarded_relocs (asection *sec)
9021 {
9022   const struct elf_backend_data *bed;
9023
9024   switch (sec->sec_info_type)
9025     {
9026     case SEC_INFO_TYPE_STABS:
9027     case SEC_INFO_TYPE_EH_FRAME:
9028       return TRUE;
9029     default:
9030       break;
9031     }
9032
9033   bed = get_elf_backend_data (sec->owner);
9034   if (bed->elf_backend_ignore_discarded_relocs != NULL
9035       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9036     return TRUE;
9037
9038   return FALSE;
9039 }
9040
9041 /* Return a mask saying how ld should treat relocations in SEC against
9042    symbols defined in discarded sections.  If this function returns
9043    COMPLAIN set, ld will issue a warning message.  If this function
9044    returns PRETEND set, and the discarded section was link-once and the
9045    same size as the kept link-once section, ld will pretend that the
9046    symbol was actually defined in the kept section.  Otherwise ld will
9047    zero the reloc (at least that is the intent, but some cooperation by
9048    the target dependent code is needed, particularly for REL targets).  */
9049
9050 unsigned int
9051 _bfd_elf_default_action_discarded (asection *sec)
9052 {
9053   if (sec->flags & SEC_DEBUGGING)
9054     return PRETEND;
9055
9056   if (strcmp (".eh_frame", sec->name) == 0)
9057     return 0;
9058
9059   if (strcmp (".gcc_except_table", sec->name) == 0)
9060     return 0;
9061
9062   return COMPLAIN | PRETEND;
9063 }
9064
9065 /* Find a match between a section and a member of a section group.  */
9066
9067 static asection *
9068 match_group_member (asection *sec, asection *group,
9069                     struct bfd_link_info *info)
9070 {
9071   asection *first = elf_next_in_group (group);
9072   asection *s = first;
9073
9074   while (s != NULL)
9075     {
9076       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9077         return s;
9078
9079       s = elf_next_in_group (s);
9080       if (s == first)
9081         break;
9082     }
9083
9084   return NULL;
9085 }
9086
9087 /* Check if the kept section of a discarded section SEC can be used
9088    to replace it.  Return the replacement if it is OK.  Otherwise return
9089    NULL.  */
9090
9091 asection *
9092 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9093 {
9094   asection *kept;
9095
9096   kept = sec->kept_section;
9097   if (kept != NULL)
9098     {
9099       if ((kept->flags & SEC_GROUP) != 0)
9100         kept = match_group_member (sec, kept, info);
9101       if (kept != NULL
9102           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9103               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9104         kept = NULL;
9105       sec->kept_section = kept;
9106     }
9107   return kept;
9108 }
9109
9110 /* Link an input file into the linker output file.  This function
9111    handles all the sections and relocations of the input file at once.
9112    This is so that we only have to read the local symbols once, and
9113    don't have to keep them in memory.  */
9114
9115 static bfd_boolean
9116 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9117 {
9118   int (*relocate_section)
9119     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9120      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9121   bfd *output_bfd;
9122   Elf_Internal_Shdr *symtab_hdr;
9123   size_t locsymcount;
9124   size_t extsymoff;
9125   Elf_Internal_Sym *isymbuf;
9126   Elf_Internal_Sym *isym;
9127   Elf_Internal_Sym *isymend;
9128   long *pindex;
9129   asection **ppsection;
9130   asection *o;
9131   const struct elf_backend_data *bed;
9132   struct elf_link_hash_entry **sym_hashes;
9133   bfd_size_type address_size;
9134   bfd_vma r_type_mask;
9135   int r_sym_shift;
9136   bfd_boolean have_file_sym = FALSE;
9137
9138   output_bfd = flinfo->output_bfd;
9139   bed = get_elf_backend_data (output_bfd);
9140   relocate_section = bed->elf_backend_relocate_section;
9141
9142   /* If this is a dynamic object, we don't want to do anything here:
9143      we don't want the local symbols, and we don't want the section
9144      contents.  */
9145   if ((input_bfd->flags & DYNAMIC) != 0)
9146     return TRUE;
9147
9148   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9149   if (elf_bad_symtab (input_bfd))
9150     {
9151       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9152       extsymoff = 0;
9153     }
9154   else
9155     {
9156       locsymcount = symtab_hdr->sh_info;
9157       extsymoff = symtab_hdr->sh_info;
9158     }
9159
9160   /* Read the local symbols.  */
9161   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9162   if (isymbuf == NULL && locsymcount != 0)
9163     {
9164       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9165                                       flinfo->internal_syms,
9166                                       flinfo->external_syms,
9167                                       flinfo->locsym_shndx);
9168       if (isymbuf == NULL)
9169         return FALSE;
9170     }
9171
9172   /* Find local symbol sections and adjust values of symbols in
9173      SEC_MERGE sections.  Write out those local symbols we know are
9174      going into the output file.  */
9175   isymend = isymbuf + locsymcount;
9176   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9177        isym < isymend;
9178        isym++, pindex++, ppsection++)
9179     {
9180       asection *isec;
9181       const char *name;
9182       Elf_Internal_Sym osym;
9183       long indx;
9184       int ret;
9185
9186       *pindex = -1;
9187
9188       if (elf_bad_symtab (input_bfd))
9189         {
9190           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9191             {
9192               *ppsection = NULL;
9193               continue;
9194             }
9195         }
9196
9197       if (isym->st_shndx == SHN_UNDEF)
9198         isec = bfd_und_section_ptr;
9199       else if (isym->st_shndx == SHN_ABS)
9200         isec = bfd_abs_section_ptr;
9201       else if (isym->st_shndx == SHN_COMMON)
9202         isec = bfd_com_section_ptr;
9203       else
9204         {
9205           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9206           if (isec == NULL)
9207             {
9208               /* Don't attempt to output symbols with st_shnx in the
9209                  reserved range other than SHN_ABS and SHN_COMMON.  */
9210               *ppsection = NULL;
9211               continue;
9212             }
9213           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9214                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9215             isym->st_value =
9216               _bfd_merged_section_offset (output_bfd, &isec,
9217                                           elf_section_data (isec)->sec_info,
9218                                           isym->st_value);
9219         }
9220
9221       *ppsection = isec;
9222
9223       /* Don't output the first, undefined, symbol.  */
9224       if (ppsection == flinfo->sections)
9225         continue;
9226
9227       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9228         {
9229           /* We never output section symbols.  Instead, we use the
9230              section symbol of the corresponding section in the output
9231              file.  */
9232           continue;
9233         }
9234
9235       /* If we are stripping all symbols, we don't want to output this
9236          one.  */
9237       if (flinfo->info->strip == strip_all)
9238         continue;
9239
9240       /* If we are discarding all local symbols, we don't want to
9241          output this one.  If we are generating a relocatable output
9242          file, then some of the local symbols may be required by
9243          relocs; we output them below as we discover that they are
9244          needed.  */
9245       if (flinfo->info->discard == discard_all)
9246         continue;
9247
9248       /* If this symbol is defined in a section which we are
9249          discarding, we don't need to keep it.  */
9250       if (isym->st_shndx != SHN_UNDEF
9251           && isym->st_shndx < SHN_LORESERVE
9252           && bfd_section_removed_from_list (output_bfd,
9253                                             isec->output_section))
9254         continue;
9255
9256       /* Get the name of the symbol.  */
9257       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9258                                               isym->st_name);
9259       if (name == NULL)
9260         return FALSE;
9261
9262       /* See if we are discarding symbols with this name.  */
9263       if ((flinfo->info->strip == strip_some
9264            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9265                == NULL))
9266           || (((flinfo->info->discard == discard_sec_merge
9267                 && (isec->flags & SEC_MERGE) && !flinfo->info->relocatable)
9268                || flinfo->info->discard == discard_l)
9269               && bfd_is_local_label_name (input_bfd, name)))
9270         continue;
9271
9272       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9273         {
9274           have_file_sym = TRUE;
9275           flinfo->filesym_count += 1;
9276         }
9277       if (!have_file_sym)
9278         {
9279           /* In the absence of debug info, bfd_find_nearest_line uses
9280              FILE symbols to determine the source file for local
9281              function symbols.  Provide a FILE symbol here if input
9282              files lack such, so that their symbols won't be
9283              associated with a previous input file.  It's not the
9284              source file, but the best we can do.  */
9285           have_file_sym = TRUE;
9286           flinfo->filesym_count += 1;
9287           memset (&osym, 0, sizeof (osym));
9288           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9289           osym.st_shndx = SHN_ABS;
9290           if (!elf_link_output_sym (flinfo, input_bfd->filename, &osym,
9291                                     bfd_abs_section_ptr, NULL))
9292             return FALSE;
9293         }
9294
9295       osym = *isym;
9296
9297       /* Adjust the section index for the output file.  */
9298       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9299                                                          isec->output_section);
9300       if (osym.st_shndx == SHN_BAD)
9301         return FALSE;
9302
9303       /* ELF symbols in relocatable files are section relative, but
9304          in executable files they are virtual addresses.  Note that
9305          this code assumes that all ELF sections have an associated
9306          BFD section with a reasonable value for output_offset; below
9307          we assume that they also have a reasonable value for
9308          output_section.  Any special sections must be set up to meet
9309          these requirements.  */
9310       osym.st_value += isec->output_offset;
9311       if (!flinfo->info->relocatable)
9312         {
9313           osym.st_value += isec->output_section->vma;
9314           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9315             {
9316               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9317               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9318               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9319             }
9320         }
9321
9322       indx = bfd_get_symcount (output_bfd);
9323       ret = elf_link_output_sym (flinfo, name, &osym, isec, NULL);
9324       if (ret == 0)
9325         return FALSE;
9326       else if (ret == 1)
9327         *pindex = indx;
9328     }
9329
9330   if (bed->s->arch_size == 32)
9331     {
9332       r_type_mask = 0xff;
9333       r_sym_shift = 8;
9334       address_size = 4;
9335     }
9336   else
9337     {
9338       r_type_mask = 0xffffffff;
9339       r_sym_shift = 32;
9340       address_size = 8;
9341     }
9342
9343   /* Relocate the contents of each section.  */
9344   sym_hashes = elf_sym_hashes (input_bfd);
9345   for (o = input_bfd->sections; o != NULL; o = o->next)
9346     {
9347       bfd_byte *contents;
9348
9349       if (! o->linker_mark)
9350         {
9351           /* This section was omitted from the link.  */
9352           continue;
9353         }
9354
9355       if (flinfo->info->relocatable
9356           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9357         {
9358           /* Deal with the group signature symbol.  */
9359           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9360           unsigned long symndx = sec_data->this_hdr.sh_info;
9361           asection *osec = o->output_section;
9362
9363           if (symndx >= locsymcount
9364               || (elf_bad_symtab (input_bfd)
9365                   && flinfo->sections[symndx] == NULL))
9366             {
9367               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9368               while (h->root.type == bfd_link_hash_indirect
9369                      || h->root.type == bfd_link_hash_warning)
9370                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9371               /* Arrange for symbol to be output.  */
9372               h->indx = -2;
9373               elf_section_data (osec)->this_hdr.sh_info = -2;
9374             }
9375           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9376             {
9377               /* We'll use the output section target_index.  */
9378               asection *sec = flinfo->sections[symndx]->output_section;
9379               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9380             }
9381           else
9382             {
9383               if (flinfo->indices[symndx] == -1)
9384                 {
9385                   /* Otherwise output the local symbol now.  */
9386                   Elf_Internal_Sym sym = isymbuf[symndx];
9387                   asection *sec = flinfo->sections[symndx]->output_section;
9388                   const char *name;
9389                   long indx;
9390                   int ret;
9391
9392                   name = bfd_elf_string_from_elf_section (input_bfd,
9393                                                           symtab_hdr->sh_link,
9394                                                           sym.st_name);
9395                   if (name == NULL)
9396                     return FALSE;
9397
9398                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9399                                                                     sec);
9400                   if (sym.st_shndx == SHN_BAD)
9401                     return FALSE;
9402
9403                   sym.st_value += o->output_offset;
9404
9405                   indx = bfd_get_symcount (output_bfd);
9406                   ret = elf_link_output_sym (flinfo, name, &sym, o, NULL);
9407                   if (ret == 0)
9408                     return FALSE;
9409                   else if (ret == 1)
9410                     flinfo->indices[symndx] = indx;
9411                   else
9412                     abort ();
9413                 }
9414               elf_section_data (osec)->this_hdr.sh_info
9415                 = flinfo->indices[symndx];
9416             }
9417         }
9418
9419       if ((o->flags & SEC_HAS_CONTENTS) == 0
9420           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9421         continue;
9422
9423       if ((o->flags & SEC_LINKER_CREATED) != 0)
9424         {
9425           /* Section was created by _bfd_elf_link_create_dynamic_sections
9426              or somesuch.  */
9427           continue;
9428         }
9429
9430       /* Get the contents of the section.  They have been cached by a
9431          relaxation routine.  Note that o is a section in an input
9432          file, so the contents field will not have been set by any of
9433          the routines which work on output files.  */
9434       if (elf_section_data (o)->this_hdr.contents != NULL)
9435         contents = elf_section_data (o)->this_hdr.contents;
9436       else
9437         {
9438           contents = flinfo->contents;
9439           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9440             return FALSE;
9441         }
9442
9443       if ((o->flags & SEC_RELOC) != 0)
9444         {
9445           Elf_Internal_Rela *internal_relocs;
9446           Elf_Internal_Rela *rel, *relend;
9447           int action_discarded;
9448           int ret;
9449
9450           /* Get the swapped relocs.  */
9451           internal_relocs
9452             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
9453                                          flinfo->internal_relocs, FALSE);
9454           if (internal_relocs == NULL
9455               && o->reloc_count > 0)
9456             return FALSE;
9457
9458           /* We need to reverse-copy input .ctors/.dtors sections if
9459              they are placed in .init_array/.finit_array for output.  */
9460           if (o->size > address_size
9461               && ((strncmp (o->name, ".ctors", 6) == 0
9462                    && strcmp (o->output_section->name,
9463                               ".init_array") == 0)
9464                   || (strncmp (o->name, ".dtors", 6) == 0
9465                       && strcmp (o->output_section->name,
9466                                  ".fini_array") == 0))
9467               && (o->name[6] == 0 || o->name[6] == '.'))
9468             {
9469               if (o->size != o->reloc_count * address_size)
9470                 {
9471                   (*_bfd_error_handler)
9472                     (_("error: %B: size of section %A is not "
9473                        "multiple of address size"),
9474                      input_bfd, o);
9475                   bfd_set_error (bfd_error_on_input);
9476                   return FALSE;
9477                 }
9478               o->flags |= SEC_ELF_REVERSE_COPY;
9479             }
9480
9481           action_discarded = -1;
9482           if (!elf_section_ignore_discarded_relocs (o))
9483             action_discarded = (*bed->action_discarded) (o);
9484
9485           /* Run through the relocs evaluating complex reloc symbols and
9486              looking for relocs against symbols from discarded sections
9487              or section symbols from removed link-once sections.
9488              Complain about relocs against discarded sections.  Zero
9489              relocs against removed link-once sections.  */
9490
9491           rel = internal_relocs;
9492           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9493           for ( ; rel < relend; rel++)
9494             {
9495               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9496               unsigned int s_type;
9497               asection **ps, *sec;
9498               struct elf_link_hash_entry *h = NULL;
9499               const char *sym_name;
9500
9501               if (r_symndx == STN_UNDEF)
9502                 continue;
9503
9504               if (r_symndx >= locsymcount
9505                   || (elf_bad_symtab (input_bfd)
9506                       && flinfo->sections[r_symndx] == NULL))
9507                 {
9508                   h = sym_hashes[r_symndx - extsymoff];
9509
9510                   /* Badly formatted input files can contain relocs that
9511                      reference non-existant symbols.  Check here so that
9512                      we do not seg fault.  */
9513                   if (h == NULL)
9514                     {
9515                       char buffer [32];
9516
9517                       sprintf_vma (buffer, rel->r_info);
9518                       (*_bfd_error_handler)
9519                         (_("error: %B contains a reloc (0x%s) for section %A "
9520                            "that references a non-existent global symbol"),
9521                          input_bfd, o, buffer);
9522                       bfd_set_error (bfd_error_bad_value);
9523                       return FALSE;
9524                     }
9525
9526                   while (h->root.type == bfd_link_hash_indirect
9527                          || h->root.type == bfd_link_hash_warning)
9528                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9529
9530                   s_type = h->type;
9531
9532                   ps = NULL;
9533                   if (h->root.type == bfd_link_hash_defined
9534                       || h->root.type == bfd_link_hash_defweak)
9535                     ps = &h->root.u.def.section;
9536
9537                   sym_name = h->root.root.string;
9538                 }
9539               else
9540                 {
9541                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
9542
9543                   s_type = ELF_ST_TYPE (sym->st_info);
9544                   ps = &flinfo->sections[r_symndx];
9545                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9546                                                sym, *ps);
9547                 }
9548
9549               if ((s_type == STT_RELC || s_type == STT_SRELC)
9550                   && !flinfo->info->relocatable)
9551                 {
9552                   bfd_vma val;
9553                   bfd_vma dot = (rel->r_offset
9554                                  + o->output_offset + o->output_section->vma);
9555 #ifdef DEBUG
9556                   printf ("Encountered a complex symbol!");
9557                   printf (" (input_bfd %s, section %s, reloc %ld\n",
9558                           input_bfd->filename, o->name,
9559                           (long) (rel - internal_relocs));
9560                   printf (" symbol: idx  %8.8lx, name %s\n",
9561                           r_symndx, sym_name);
9562                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
9563                           (unsigned long) rel->r_info,
9564                           (unsigned long) rel->r_offset);
9565 #endif
9566                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
9567                                     isymbuf, locsymcount, s_type == STT_SRELC))
9568                     return FALSE;
9569
9570                   /* Symbol evaluated OK.  Update to absolute value.  */
9571                   set_symbol_value (input_bfd, isymbuf, locsymcount,
9572                                     r_symndx, val);
9573                   continue;
9574                 }
9575
9576               if (action_discarded != -1 && ps != NULL)
9577                 {
9578                   /* Complain if the definition comes from a
9579                      discarded section.  */
9580                   if ((sec = *ps) != NULL && discarded_section (sec))
9581                     {
9582                       BFD_ASSERT (r_symndx != STN_UNDEF);
9583                       if (action_discarded & COMPLAIN)
9584                         (*flinfo->info->callbacks->einfo)
9585                           (_("%X`%s' referenced in section `%A' of %B: "
9586                              "defined in discarded section `%A' of %B\n"),
9587                            sym_name, o, input_bfd, sec, sec->owner);
9588
9589                       /* Try to do the best we can to support buggy old
9590                          versions of gcc.  Pretend that the symbol is
9591                          really defined in the kept linkonce section.
9592                          FIXME: This is quite broken.  Modifying the
9593                          symbol here means we will be changing all later
9594                          uses of the symbol, not just in this section.  */
9595                       if (action_discarded & PRETEND)
9596                         {
9597                           asection *kept;
9598
9599                           kept = _bfd_elf_check_kept_section (sec,
9600                                                               flinfo->info);
9601                           if (kept != NULL)
9602                             {
9603                               *ps = kept;
9604                               continue;
9605                             }
9606                         }
9607                     }
9608                 }
9609             }
9610
9611           /* Relocate the section by invoking a back end routine.
9612
9613              The back end routine is responsible for adjusting the
9614              section contents as necessary, and (if using Rela relocs
9615              and generating a relocatable output file) adjusting the
9616              reloc addend as necessary.
9617
9618              The back end routine does not have to worry about setting
9619              the reloc address or the reloc symbol index.
9620
9621              The back end routine is given a pointer to the swapped in
9622              internal symbols, and can access the hash table entries
9623              for the external symbols via elf_sym_hashes (input_bfd).
9624
9625              When generating relocatable output, the back end routine
9626              must handle STB_LOCAL/STT_SECTION symbols specially.  The
9627              output symbol is going to be a section symbol
9628              corresponding to the output section, which will require
9629              the addend to be adjusted.  */
9630
9631           ret = (*relocate_section) (output_bfd, flinfo->info,
9632                                      input_bfd, o, contents,
9633                                      internal_relocs,
9634                                      isymbuf,
9635                                      flinfo->sections);
9636           if (!ret)
9637             return FALSE;
9638
9639           if (ret == 2
9640               || flinfo->info->relocatable
9641               || flinfo->info->emitrelocations)
9642             {
9643               Elf_Internal_Rela *irela;
9644               Elf_Internal_Rela *irelaend, *irelamid;
9645               bfd_vma last_offset;
9646               struct elf_link_hash_entry **rel_hash;
9647               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
9648               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
9649               unsigned int next_erel;
9650               bfd_boolean rela_normal;
9651               struct bfd_elf_section_data *esdi, *esdo;
9652
9653               esdi = elf_section_data (o);
9654               esdo = elf_section_data (o->output_section);
9655               rela_normal = FALSE;
9656
9657               /* Adjust the reloc addresses and symbol indices.  */
9658
9659               irela = internal_relocs;
9660               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
9661               rel_hash = esdo->rel.hashes + esdo->rel.count;
9662               /* We start processing the REL relocs, if any.  When we reach
9663                  IRELAMID in the loop, we switch to the RELA relocs.  */
9664               irelamid = irela;
9665               if (esdi->rel.hdr != NULL)
9666                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
9667                              * bed->s->int_rels_per_ext_rel);
9668               rel_hash_list = rel_hash;
9669               rela_hash_list = NULL;
9670               last_offset = o->output_offset;
9671               if (!flinfo->info->relocatable)
9672                 last_offset += o->output_section->vma;
9673               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
9674                 {
9675                   unsigned long r_symndx;
9676                   asection *sec;
9677                   Elf_Internal_Sym sym;
9678
9679                   if (next_erel == bed->s->int_rels_per_ext_rel)
9680                     {
9681                       rel_hash++;
9682                       next_erel = 0;
9683                     }
9684
9685                   if (irela == irelamid)
9686                     {
9687                       rel_hash = esdo->rela.hashes + esdo->rela.count;
9688                       rela_hash_list = rel_hash;
9689                       rela_normal = bed->rela_normal;
9690                     }
9691
9692                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
9693                                                              flinfo->info, o,
9694                                                              irela->r_offset);
9695                   if (irela->r_offset >= (bfd_vma) -2)
9696                     {
9697                       /* This is a reloc for a deleted entry or somesuch.
9698                          Turn it into an R_*_NONE reloc, at the same
9699                          offset as the last reloc.  elf_eh_frame.c and
9700                          bfd_elf_discard_info rely on reloc offsets
9701                          being ordered.  */
9702                       irela->r_offset = last_offset;
9703                       irela->r_info = 0;
9704                       irela->r_addend = 0;
9705                       continue;
9706                     }
9707
9708                   irela->r_offset += o->output_offset;
9709
9710                   /* Relocs in an executable have to be virtual addresses.  */
9711                   if (!flinfo->info->relocatable)
9712                     irela->r_offset += o->output_section->vma;
9713
9714                   last_offset = irela->r_offset;
9715
9716                   r_symndx = irela->r_info >> r_sym_shift;
9717                   if (r_symndx == STN_UNDEF)
9718                     continue;
9719
9720                   if (r_symndx >= locsymcount
9721                       || (elf_bad_symtab (input_bfd)
9722                           && flinfo->sections[r_symndx] == NULL))
9723                     {
9724                       struct elf_link_hash_entry *rh;
9725                       unsigned long indx;
9726
9727                       /* This is a reloc against a global symbol.  We
9728                          have not yet output all the local symbols, so
9729                          we do not know the symbol index of any global
9730                          symbol.  We set the rel_hash entry for this
9731                          reloc to point to the global hash table entry
9732                          for this symbol.  The symbol index is then
9733                          set at the end of bfd_elf_final_link.  */
9734                       indx = r_symndx - extsymoff;
9735                       rh = elf_sym_hashes (input_bfd)[indx];
9736                       while (rh->root.type == bfd_link_hash_indirect
9737                              || rh->root.type == bfd_link_hash_warning)
9738                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
9739
9740                       /* Setting the index to -2 tells
9741                          elf_link_output_extsym that this symbol is
9742                          used by a reloc.  */
9743                       BFD_ASSERT (rh->indx < 0);
9744                       rh->indx = -2;
9745
9746                       *rel_hash = rh;
9747
9748                       continue;
9749                     }
9750
9751                   /* This is a reloc against a local symbol.  */
9752
9753                   *rel_hash = NULL;
9754                   sym = isymbuf[r_symndx];
9755                   sec = flinfo->sections[r_symndx];
9756                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
9757                     {
9758                       /* I suppose the backend ought to fill in the
9759                          section of any STT_SECTION symbol against a
9760                          processor specific section.  */
9761                       r_symndx = STN_UNDEF;
9762                       if (bfd_is_abs_section (sec))
9763                         ;
9764                       else if (sec == NULL || sec->owner == NULL)
9765                         {
9766                           bfd_set_error (bfd_error_bad_value);
9767                           return FALSE;
9768                         }
9769                       else
9770                         {
9771                           asection *osec = sec->output_section;
9772
9773                           /* If we have discarded a section, the output
9774                              section will be the absolute section.  In
9775                              case of discarded SEC_MERGE sections, use
9776                              the kept section.  relocate_section should
9777                              have already handled discarded linkonce
9778                              sections.  */
9779                           if (bfd_is_abs_section (osec)
9780                               && sec->kept_section != NULL
9781                               && sec->kept_section->output_section != NULL)
9782                             {
9783                               osec = sec->kept_section->output_section;
9784                               irela->r_addend -= osec->vma;
9785                             }
9786
9787                           if (!bfd_is_abs_section (osec))
9788                             {
9789                               r_symndx = osec->target_index;
9790                               if (r_symndx == STN_UNDEF)
9791                                 {
9792                                   irela->r_addend += osec->vma;
9793                                   osec = _bfd_nearby_section (output_bfd, osec,
9794                                                               osec->vma);
9795                                   irela->r_addend -= osec->vma;
9796                                   r_symndx = osec->target_index;
9797                                 }
9798                             }
9799                         }
9800
9801                       /* Adjust the addend according to where the
9802                          section winds up in the output section.  */
9803                       if (rela_normal)
9804                         irela->r_addend += sec->output_offset;
9805                     }
9806                   else
9807                     {
9808                       if (flinfo->indices[r_symndx] == -1)
9809                         {
9810                           unsigned long shlink;
9811                           const char *name;
9812                           asection *osec;
9813                           long indx;
9814
9815                           if (flinfo->info->strip == strip_all)
9816                             {
9817                               /* You can't do ld -r -s.  */
9818                               bfd_set_error (bfd_error_invalid_operation);
9819                               return FALSE;
9820                             }
9821
9822                           /* This symbol was skipped earlier, but
9823                              since it is needed by a reloc, we
9824                              must output it now.  */
9825                           shlink = symtab_hdr->sh_link;
9826                           name = (bfd_elf_string_from_elf_section
9827                                   (input_bfd, shlink, sym.st_name));
9828                           if (name == NULL)
9829                             return FALSE;
9830
9831                           osec = sec->output_section;
9832                           sym.st_shndx =
9833                             _bfd_elf_section_from_bfd_section (output_bfd,
9834                                                                osec);
9835                           if (sym.st_shndx == SHN_BAD)
9836                             return FALSE;
9837
9838                           sym.st_value += sec->output_offset;
9839                           if (!flinfo->info->relocatable)
9840                             {
9841                               sym.st_value += osec->vma;
9842                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
9843                                 {
9844                                   /* STT_TLS symbols are relative to PT_TLS
9845                                      segment base.  */
9846                                   BFD_ASSERT (elf_hash_table (flinfo->info)
9847                                               ->tls_sec != NULL);
9848                                   sym.st_value -= (elf_hash_table (flinfo->info)
9849                                                    ->tls_sec->vma);
9850                                 }
9851                             }
9852
9853                           indx = bfd_get_symcount (output_bfd);
9854                           ret = elf_link_output_sym (flinfo, name, &sym, sec,
9855                                                      NULL);
9856                           if (ret == 0)
9857                             return FALSE;
9858                           else if (ret == 1)
9859                             flinfo->indices[r_symndx] = indx;
9860                           else
9861                             abort ();
9862                         }
9863
9864                       r_symndx = flinfo->indices[r_symndx];
9865                     }
9866
9867                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
9868                                    | (irela->r_info & r_type_mask));
9869                 }
9870
9871               /* Swap out the relocs.  */
9872               input_rel_hdr = esdi->rel.hdr;
9873               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
9874                 {
9875                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
9876                                                      input_rel_hdr,
9877                                                      internal_relocs,
9878                                                      rel_hash_list))
9879                     return FALSE;
9880                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
9881                                       * bed->s->int_rels_per_ext_rel);
9882                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
9883                 }
9884
9885               input_rela_hdr = esdi->rela.hdr;
9886               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
9887                 {
9888                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
9889                                                      input_rela_hdr,
9890                                                      internal_relocs,
9891                                                      rela_hash_list))
9892                     return FALSE;
9893                 }
9894             }
9895         }
9896
9897       /* Write out the modified section contents.  */
9898       if (bed->elf_backend_write_section
9899           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
9900                                                 contents))
9901         {
9902           /* Section written out.  */
9903         }
9904       else switch (o->sec_info_type)
9905         {
9906         case SEC_INFO_TYPE_STABS:
9907           if (! (_bfd_write_section_stabs
9908                  (output_bfd,
9909                   &elf_hash_table (flinfo->info)->stab_info,
9910                   o, &elf_section_data (o)->sec_info, contents)))
9911             return FALSE;
9912           break;
9913         case SEC_INFO_TYPE_MERGE:
9914           if (! _bfd_write_merged_section (output_bfd, o,
9915                                            elf_section_data (o)->sec_info))
9916             return FALSE;
9917           break;
9918         case SEC_INFO_TYPE_EH_FRAME:
9919           {
9920             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
9921                                                    o, contents))
9922               return FALSE;
9923           }
9924           break;
9925         default:
9926           {
9927             /* FIXME: octets_per_byte.  */
9928             if (! (o->flags & SEC_EXCLUDE))
9929               {
9930                 file_ptr offset = (file_ptr) o->output_offset;
9931                 bfd_size_type todo = o->size;
9932                 if ((o->flags & SEC_ELF_REVERSE_COPY))
9933                   {
9934                     /* Reverse-copy input section to output.  */
9935                     do
9936                       {
9937                         todo -= address_size;
9938                         if (! bfd_set_section_contents (output_bfd,
9939                                                         o->output_section,
9940                                                         contents + todo,
9941                                                         offset,
9942                                                         address_size))
9943                           return FALSE;
9944                         if (todo == 0)
9945                           break;
9946                         offset += address_size;
9947                       }
9948                     while (1);
9949                   }
9950                 else if (! bfd_set_section_contents (output_bfd,
9951                                                      o->output_section,
9952                                                      contents,
9953                                                      offset, todo))
9954                   return FALSE;
9955               }
9956           }
9957           break;
9958         }
9959     }
9960
9961   return TRUE;
9962 }
9963
9964 /* Generate a reloc when linking an ELF file.  This is a reloc
9965    requested by the linker, and does not come from any input file.  This
9966    is used to build constructor and destructor tables when linking
9967    with -Ur.  */
9968
9969 static bfd_boolean
9970 elf_reloc_link_order (bfd *output_bfd,
9971                       struct bfd_link_info *info,
9972                       asection *output_section,
9973                       struct bfd_link_order *link_order)
9974 {
9975   reloc_howto_type *howto;
9976   long indx;
9977   bfd_vma offset;
9978   bfd_vma addend;
9979   struct bfd_elf_section_reloc_data *reldata;
9980   struct elf_link_hash_entry **rel_hash_ptr;
9981   Elf_Internal_Shdr *rel_hdr;
9982   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9983   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
9984   bfd_byte *erel;
9985   unsigned int i;
9986   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
9987
9988   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
9989   if (howto == NULL)
9990     {
9991       bfd_set_error (bfd_error_bad_value);
9992       return FALSE;
9993     }
9994
9995   addend = link_order->u.reloc.p->addend;
9996
9997   if (esdo->rel.hdr)
9998     reldata = &esdo->rel;
9999   else if (esdo->rela.hdr)
10000     reldata = &esdo->rela;
10001   else
10002     {
10003       reldata = NULL;
10004       BFD_ASSERT (0);
10005     }
10006
10007   /* Figure out the symbol index.  */
10008   rel_hash_ptr = reldata->hashes + reldata->count;
10009   if (link_order->type == bfd_section_reloc_link_order)
10010     {
10011       indx = link_order->u.reloc.p->u.section->target_index;
10012       BFD_ASSERT (indx != 0);
10013       *rel_hash_ptr = NULL;
10014     }
10015   else
10016     {
10017       struct elf_link_hash_entry *h;
10018
10019       /* Treat a reloc against a defined symbol as though it were
10020          actually against the section.  */
10021       h = ((struct elf_link_hash_entry *)
10022            bfd_wrapped_link_hash_lookup (output_bfd, info,
10023                                          link_order->u.reloc.p->u.name,
10024                                          FALSE, FALSE, TRUE));
10025       if (h != NULL
10026           && (h->root.type == bfd_link_hash_defined
10027               || h->root.type == bfd_link_hash_defweak))
10028         {
10029           asection *section;
10030
10031           section = h->root.u.def.section;
10032           indx = section->output_section->target_index;
10033           *rel_hash_ptr = NULL;
10034           /* It seems that we ought to add the symbol value to the
10035              addend here, but in practice it has already been added
10036              because it was passed to constructor_callback.  */
10037           addend += section->output_section->vma + section->output_offset;
10038         }
10039       else if (h != NULL)
10040         {
10041           /* Setting the index to -2 tells elf_link_output_extsym that
10042              this symbol is used by a reloc.  */
10043           h->indx = -2;
10044           *rel_hash_ptr = h;
10045           indx = 0;
10046         }
10047       else
10048         {
10049           if (! ((*info->callbacks->unattached_reloc)
10050                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10051             return FALSE;
10052           indx = 0;
10053         }
10054     }
10055
10056   /* If this is an inplace reloc, we must write the addend into the
10057      object file.  */
10058   if (howto->partial_inplace && addend != 0)
10059     {
10060       bfd_size_type size;
10061       bfd_reloc_status_type rstat;
10062       bfd_byte *buf;
10063       bfd_boolean ok;
10064       const char *sym_name;
10065
10066       size = (bfd_size_type) bfd_get_reloc_size (howto);
10067       buf = (bfd_byte *) bfd_zmalloc (size);
10068       if (buf == NULL)
10069         return FALSE;
10070       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10071       switch (rstat)
10072         {
10073         case bfd_reloc_ok:
10074           break;
10075
10076         default:
10077         case bfd_reloc_outofrange:
10078           abort ();
10079
10080         case bfd_reloc_overflow:
10081           if (link_order->type == bfd_section_reloc_link_order)
10082             sym_name = bfd_section_name (output_bfd,
10083                                          link_order->u.reloc.p->u.section);
10084           else
10085             sym_name = link_order->u.reloc.p->u.name;
10086           if (! ((*info->callbacks->reloc_overflow)
10087                  (info, NULL, sym_name, howto->name, addend, NULL,
10088                   NULL, (bfd_vma) 0)))
10089             {
10090               free (buf);
10091               return FALSE;
10092             }
10093           break;
10094         }
10095       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10096                                      link_order->offset, size);
10097       free (buf);
10098       if (! ok)
10099         return FALSE;
10100     }
10101
10102   /* The address of a reloc is relative to the section in a
10103      relocatable file, and is a virtual address in an executable
10104      file.  */
10105   offset = link_order->offset;
10106   if (! info->relocatable)
10107     offset += output_section->vma;
10108
10109   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10110     {
10111       irel[i].r_offset = offset;
10112       irel[i].r_info = 0;
10113       irel[i].r_addend = 0;
10114     }
10115   if (bed->s->arch_size == 32)
10116     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10117   else
10118     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10119
10120   rel_hdr = reldata->hdr;
10121   erel = rel_hdr->contents;
10122   if (rel_hdr->sh_type == SHT_REL)
10123     {
10124       erel += reldata->count * bed->s->sizeof_rel;
10125       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10126     }
10127   else
10128     {
10129       irel[0].r_addend = addend;
10130       erel += reldata->count * bed->s->sizeof_rela;
10131       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10132     }
10133
10134   ++reldata->count;
10135
10136   return TRUE;
10137 }
10138
10139
10140 /* Get the output vma of the section pointed to by the sh_link field.  */
10141
10142 static bfd_vma
10143 elf_get_linked_section_vma (struct bfd_link_order *p)
10144 {
10145   Elf_Internal_Shdr **elf_shdrp;
10146   asection *s;
10147   int elfsec;
10148
10149   s = p->u.indirect.section;
10150   elf_shdrp = elf_elfsections (s->owner);
10151   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10152   elfsec = elf_shdrp[elfsec]->sh_link;
10153   /* PR 290:
10154      The Intel C compiler generates SHT_IA_64_UNWIND with
10155      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10156      sh_info fields.  Hence we could get the situation
10157      where elfsec is 0.  */
10158   if (elfsec == 0)
10159     {
10160       const struct elf_backend_data *bed
10161         = get_elf_backend_data (s->owner);
10162       if (bed->link_order_error_handler)
10163         bed->link_order_error_handler
10164           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10165       return 0;
10166     }
10167   else
10168     {
10169       s = elf_shdrp[elfsec]->bfd_section;
10170       return s->output_section->vma + s->output_offset;
10171     }
10172 }
10173
10174
10175 /* Compare two sections based on the locations of the sections they are
10176    linked to.  Used by elf_fixup_link_order.  */
10177
10178 static int
10179 compare_link_order (const void * a, const void * b)
10180 {
10181   bfd_vma apos;
10182   bfd_vma bpos;
10183
10184   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10185   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10186   if (apos < bpos)
10187     return -1;
10188   return apos > bpos;
10189 }
10190
10191
10192 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10193    order as their linked sections.  Returns false if this could not be done
10194    because an output section includes both ordered and unordered
10195    sections.  Ideally we'd do this in the linker proper.  */
10196
10197 static bfd_boolean
10198 elf_fixup_link_order (bfd *abfd, asection *o)
10199 {
10200   int seen_linkorder;
10201   int seen_other;
10202   int n;
10203   struct bfd_link_order *p;
10204   bfd *sub;
10205   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10206   unsigned elfsec;
10207   struct bfd_link_order **sections;
10208   asection *s, *other_sec, *linkorder_sec;
10209   bfd_vma offset;
10210
10211   other_sec = NULL;
10212   linkorder_sec = NULL;
10213   seen_other = 0;
10214   seen_linkorder = 0;
10215   for (p = o->map_head.link_order; p != NULL; p = p->next)
10216     {
10217       if (p->type == bfd_indirect_link_order)
10218         {
10219           s = p->u.indirect.section;
10220           sub = s->owner;
10221           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10222               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10223               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10224               && elfsec < elf_numsections (sub)
10225               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10226               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10227             {
10228               seen_linkorder++;
10229               linkorder_sec = s;
10230             }
10231           else
10232             {
10233               seen_other++;
10234               other_sec = s;
10235             }
10236         }
10237       else
10238         seen_other++;
10239
10240       if (seen_other && seen_linkorder)
10241         {
10242           if (other_sec && linkorder_sec)
10243             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10244                                    o, linkorder_sec,
10245                                    linkorder_sec->owner, other_sec,
10246                                    other_sec->owner);
10247           else
10248             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10249                                    o);
10250           bfd_set_error (bfd_error_bad_value);
10251           return FALSE;
10252         }
10253     }
10254
10255   if (!seen_linkorder)
10256     return TRUE;
10257
10258   sections = (struct bfd_link_order **)
10259     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10260   if (sections == NULL)
10261     return FALSE;
10262   seen_linkorder = 0;
10263
10264   for (p = o->map_head.link_order; p != NULL; p = p->next)
10265     {
10266       sections[seen_linkorder++] = p;
10267     }
10268   /* Sort the input sections in the order of their linked section.  */
10269   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10270          compare_link_order);
10271
10272   /* Change the offsets of the sections.  */
10273   offset = 0;
10274   for (n = 0; n < seen_linkorder; n++)
10275     {
10276       s = sections[n]->u.indirect.section;
10277       offset &= ~(bfd_vma) 0 << s->alignment_power;
10278       s->output_offset = offset;
10279       sections[n]->offset = offset;
10280       /* FIXME: octets_per_byte.  */
10281       offset += sections[n]->size;
10282     }
10283
10284   free (sections);
10285   return TRUE;
10286 }
10287
10288
10289 /* Do the final step of an ELF link.  */
10290
10291 bfd_boolean
10292 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10293 {
10294   bfd_boolean dynamic;
10295   bfd_boolean emit_relocs;
10296   bfd *dynobj;
10297   struct elf_final_link_info flinfo;
10298   asection *o;
10299   struct bfd_link_order *p;
10300   bfd *sub;
10301   bfd_size_type max_contents_size;
10302   bfd_size_type max_external_reloc_size;
10303   bfd_size_type max_internal_reloc_count;
10304   bfd_size_type max_sym_count;
10305   bfd_size_type max_sym_shndx_count;
10306   file_ptr off;
10307   Elf_Internal_Sym elfsym;
10308   unsigned int i;
10309   Elf_Internal_Shdr *symtab_hdr;
10310   Elf_Internal_Shdr *symtab_shndx_hdr;
10311   Elf_Internal_Shdr *symstrtab_hdr;
10312   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10313   struct elf_outext_info eoinfo;
10314   bfd_boolean merged;
10315   size_t relativecount = 0;
10316   asection *reldyn = 0;
10317   bfd_size_type amt;
10318   asection *attr_section = NULL;
10319   bfd_vma attr_size = 0;
10320   const char *std_attrs_section;
10321
10322   if (! is_elf_hash_table (info->hash))
10323     return FALSE;
10324
10325   if (info->shared)
10326     abfd->flags |= DYNAMIC;
10327
10328   dynamic = elf_hash_table (info)->dynamic_sections_created;
10329   dynobj = elf_hash_table (info)->dynobj;
10330
10331   emit_relocs = (info->relocatable
10332                  || info->emitrelocations);
10333
10334   flinfo.info = info;
10335   flinfo.output_bfd = abfd;
10336   flinfo.symstrtab = _bfd_elf_stringtab_init ();
10337   if (flinfo.symstrtab == NULL)
10338     return FALSE;
10339
10340   if (! dynamic)
10341     {
10342       flinfo.dynsym_sec = NULL;
10343       flinfo.hash_sec = NULL;
10344       flinfo.symver_sec = NULL;
10345     }
10346   else
10347     {
10348       flinfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
10349       flinfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
10350       /* Note that dynsym_sec can be NULL (on VMS).  */
10351       flinfo.symver_sec = bfd_get_section_by_name (dynobj, ".gnu.version");
10352       /* Note that it is OK if symver_sec is NULL.  */
10353     }
10354
10355   flinfo.contents = NULL;
10356   flinfo.external_relocs = NULL;
10357   flinfo.internal_relocs = NULL;
10358   flinfo.external_syms = NULL;
10359   flinfo.locsym_shndx = NULL;
10360   flinfo.internal_syms = NULL;
10361   flinfo.indices = NULL;
10362   flinfo.sections = NULL;
10363   flinfo.symbuf = NULL;
10364   flinfo.symshndxbuf = NULL;
10365   flinfo.symbuf_count = 0;
10366   flinfo.shndxbuf_size = 0;
10367   flinfo.filesym_count = 0;
10368
10369   /* The object attributes have been merged.  Remove the input
10370      sections from the link, and set the contents of the output
10371      secton.  */
10372   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10373   for (o = abfd->sections; o != NULL; o = o->next)
10374     {
10375       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10376           || strcmp (o->name, ".gnu.attributes") == 0)
10377         {
10378           for (p = o->map_head.link_order; p != NULL; p = p->next)
10379             {
10380               asection *input_section;
10381
10382               if (p->type != bfd_indirect_link_order)
10383                 continue;
10384               input_section = p->u.indirect.section;
10385               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10386                  elf_link_input_bfd ignores this section.  */
10387               input_section->flags &= ~SEC_HAS_CONTENTS;
10388             }
10389
10390           attr_size = bfd_elf_obj_attr_size (abfd);
10391           if (attr_size)
10392             {
10393               bfd_set_section_size (abfd, o, attr_size);
10394               attr_section = o;
10395               /* Skip this section later on.  */
10396               o->map_head.link_order = NULL;
10397             }
10398           else
10399             o->flags |= SEC_EXCLUDE;
10400         }
10401     }
10402
10403   /* Count up the number of relocations we will output for each output
10404      section, so that we know the sizes of the reloc sections.  We
10405      also figure out some maximum sizes.  */
10406   max_contents_size = 0;
10407   max_external_reloc_size = 0;
10408   max_internal_reloc_count = 0;
10409   max_sym_count = 0;
10410   max_sym_shndx_count = 0;
10411   merged = FALSE;
10412   for (o = abfd->sections; o != NULL; o = o->next)
10413     {
10414       struct bfd_elf_section_data *esdo = elf_section_data (o);
10415       o->reloc_count = 0;
10416
10417       for (p = o->map_head.link_order; p != NULL; p = p->next)
10418         {
10419           unsigned int reloc_count = 0;
10420           struct bfd_elf_section_data *esdi = NULL;
10421
10422           if (p->type == bfd_section_reloc_link_order
10423               || p->type == bfd_symbol_reloc_link_order)
10424             reloc_count = 1;
10425           else if (p->type == bfd_indirect_link_order)
10426             {
10427               asection *sec;
10428
10429               sec = p->u.indirect.section;
10430               esdi = elf_section_data (sec);
10431
10432               /* Mark all sections which are to be included in the
10433                  link.  This will normally be every section.  We need
10434                  to do this so that we can identify any sections which
10435                  the linker has decided to not include.  */
10436               sec->linker_mark = TRUE;
10437
10438               if (sec->flags & SEC_MERGE)
10439                 merged = TRUE;
10440
10441               if (esdo->this_hdr.sh_type == SHT_REL
10442                   || esdo->this_hdr.sh_type == SHT_RELA)
10443                 /* Some backends use reloc_count in relocation sections
10444                    to count particular types of relocs.  Of course,
10445                    reloc sections themselves can't have relocations.  */
10446                 reloc_count = 0;
10447               else if (info->relocatable || info->emitrelocations)
10448                 reloc_count = sec->reloc_count;
10449               else if (bed->elf_backend_count_relocs)
10450                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10451
10452               if (sec->rawsize > max_contents_size)
10453                 max_contents_size = sec->rawsize;
10454               if (sec->size > max_contents_size)
10455                 max_contents_size = sec->size;
10456
10457               /* We are interested in just local symbols, not all
10458                  symbols.  */
10459               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10460                   && (sec->owner->flags & DYNAMIC) == 0)
10461                 {
10462                   size_t sym_count;
10463
10464                   if (elf_bad_symtab (sec->owner))
10465                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10466                                  / bed->s->sizeof_sym);
10467                   else
10468                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10469
10470                   if (sym_count > max_sym_count)
10471                     max_sym_count = sym_count;
10472
10473                   if (sym_count > max_sym_shndx_count
10474                       && elf_symtab_shndx (sec->owner) != 0)
10475                     max_sym_shndx_count = sym_count;
10476
10477                   if ((sec->flags & SEC_RELOC) != 0)
10478                     {
10479                       size_t ext_size = 0;
10480
10481                       if (esdi->rel.hdr != NULL)
10482                         ext_size = esdi->rel.hdr->sh_size;
10483                       if (esdi->rela.hdr != NULL)
10484                         ext_size += esdi->rela.hdr->sh_size;
10485
10486                       if (ext_size > max_external_reloc_size)
10487                         max_external_reloc_size = ext_size;
10488                       if (sec->reloc_count > max_internal_reloc_count)
10489                         max_internal_reloc_count = sec->reloc_count;
10490                     }
10491                 }
10492             }
10493
10494           if (reloc_count == 0)
10495             continue;
10496
10497           o->reloc_count += reloc_count;
10498
10499           if (p->type == bfd_indirect_link_order
10500               && (info->relocatable || info->emitrelocations))
10501             {
10502               if (esdi->rel.hdr)
10503                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
10504               if (esdi->rela.hdr)
10505                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
10506             }
10507           else
10508             {
10509               if (o->use_rela_p)
10510                 esdo->rela.count += reloc_count;
10511               else
10512                 esdo->rel.count += reloc_count;
10513             }
10514         }
10515
10516       if (o->reloc_count > 0)
10517         o->flags |= SEC_RELOC;
10518       else
10519         {
10520           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
10521              set it (this is probably a bug) and if it is set
10522              assign_section_numbers will create a reloc section.  */
10523           o->flags &=~ SEC_RELOC;
10524         }
10525
10526       /* If the SEC_ALLOC flag is not set, force the section VMA to
10527          zero.  This is done in elf_fake_sections as well, but forcing
10528          the VMA to 0 here will ensure that relocs against these
10529          sections are handled correctly.  */
10530       if ((o->flags & SEC_ALLOC) == 0
10531           && ! o->user_set_vma)
10532         o->vma = 0;
10533     }
10534
10535   if (! info->relocatable && merged)
10536     elf_link_hash_traverse (elf_hash_table (info),
10537                             _bfd_elf_link_sec_merge_syms, abfd);
10538
10539   /* Figure out the file positions for everything but the symbol table
10540      and the relocs.  We set symcount to force assign_section_numbers
10541      to create a symbol table.  */
10542   bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
10543   BFD_ASSERT (! abfd->output_has_begun);
10544   if (! _bfd_elf_compute_section_file_positions (abfd, info))
10545     goto error_return;
10546
10547   /* Set sizes, and assign file positions for reloc sections.  */
10548   for (o = abfd->sections; o != NULL; o = o->next)
10549     {
10550       struct bfd_elf_section_data *esdo = elf_section_data (o);
10551       if ((o->flags & SEC_RELOC) != 0)
10552         {
10553           if (esdo->rel.hdr
10554               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
10555             goto error_return;
10556
10557           if (esdo->rela.hdr
10558               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
10559             goto error_return;
10560         }
10561
10562       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
10563          to count upwards while actually outputting the relocations.  */
10564       esdo->rel.count = 0;
10565       esdo->rela.count = 0;
10566     }
10567
10568   _bfd_elf_assign_file_positions_for_relocs (abfd);
10569
10570   /* We have now assigned file positions for all the sections except
10571      .symtab and .strtab.  We start the .symtab section at the current
10572      file position, and write directly to it.  We build the .strtab
10573      section in memory.  */
10574   bfd_get_symcount (abfd) = 0;
10575   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10576   /* sh_name is set in prep_headers.  */
10577   symtab_hdr->sh_type = SHT_SYMTAB;
10578   /* sh_flags, sh_addr and sh_size all start off zero.  */
10579   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
10580   /* sh_link is set in assign_section_numbers.  */
10581   /* sh_info is set below.  */
10582   /* sh_offset is set just below.  */
10583   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
10584
10585   off = elf_tdata (abfd)->next_file_pos;
10586   off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
10587
10588   /* Note that at this point elf_tdata (abfd)->next_file_pos is
10589      incorrect.  We do not yet know the size of the .symtab section.
10590      We correct next_file_pos below, after we do know the size.  */
10591
10592   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
10593      continuously seeking to the right position in the file.  */
10594   if (! info->keep_memory || max_sym_count < 20)
10595     flinfo.symbuf_size = 20;
10596   else
10597     flinfo.symbuf_size = max_sym_count;
10598   amt = flinfo.symbuf_size;
10599   amt *= bed->s->sizeof_sym;
10600   flinfo.symbuf = (bfd_byte *) bfd_malloc (amt);
10601   if (flinfo.symbuf == NULL)
10602     goto error_return;
10603   if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
10604     {
10605       /* Wild guess at number of output symbols.  realloc'd as needed.  */
10606       amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
10607       flinfo.shndxbuf_size = amt;
10608       amt *= sizeof (Elf_External_Sym_Shndx);
10609       flinfo.symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
10610       if (flinfo.symshndxbuf == NULL)
10611         goto error_return;
10612     }
10613
10614   /* Start writing out the symbol table.  The first symbol is always a
10615      dummy symbol.  */
10616   if (info->strip != strip_all
10617       || emit_relocs)
10618     {
10619       elfsym.st_value = 0;
10620       elfsym.st_size = 0;
10621       elfsym.st_info = 0;
10622       elfsym.st_other = 0;
10623       elfsym.st_shndx = SHN_UNDEF;
10624       elfsym.st_target_internal = 0;
10625       if (elf_link_output_sym (&flinfo, NULL, &elfsym, bfd_und_section_ptr,
10626                                NULL) != 1)
10627         goto error_return;
10628     }
10629
10630   /* Output a symbol for each section.  We output these even if we are
10631      discarding local symbols, since they are used for relocs.  These
10632      symbols have no names.  We store the index of each one in the
10633      index field of the section, so that we can find it again when
10634      outputting relocs.  */
10635   if (info->strip != strip_all
10636       || emit_relocs)
10637     {
10638       elfsym.st_size = 0;
10639       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10640       elfsym.st_other = 0;
10641       elfsym.st_value = 0;
10642       elfsym.st_target_internal = 0;
10643       for (i = 1; i < elf_numsections (abfd); i++)
10644         {
10645           o = bfd_section_from_elf_index (abfd, i);
10646           if (o != NULL)
10647             {
10648               o->target_index = bfd_get_symcount (abfd);
10649               elfsym.st_shndx = i;
10650               if (!info->relocatable)
10651                 elfsym.st_value = o->vma;
10652               if (elf_link_output_sym (&flinfo, NULL, &elfsym, o, NULL) != 1)
10653                 goto error_return;
10654             }
10655         }
10656     }
10657
10658   /* Allocate some memory to hold information read in from the input
10659      files.  */
10660   if (max_contents_size != 0)
10661     {
10662       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
10663       if (flinfo.contents == NULL)
10664         goto error_return;
10665     }
10666
10667   if (max_external_reloc_size != 0)
10668     {
10669       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
10670       if (flinfo.external_relocs == NULL)
10671         goto error_return;
10672     }
10673
10674   if (max_internal_reloc_count != 0)
10675     {
10676       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
10677       amt *= sizeof (Elf_Internal_Rela);
10678       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
10679       if (flinfo.internal_relocs == NULL)
10680         goto error_return;
10681     }
10682
10683   if (max_sym_count != 0)
10684     {
10685       amt = max_sym_count * bed->s->sizeof_sym;
10686       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
10687       if (flinfo.external_syms == NULL)
10688         goto error_return;
10689
10690       amt = max_sym_count * sizeof (Elf_Internal_Sym);
10691       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
10692       if (flinfo.internal_syms == NULL)
10693         goto error_return;
10694
10695       amt = max_sym_count * sizeof (long);
10696       flinfo.indices = (long int *) bfd_malloc (amt);
10697       if (flinfo.indices == NULL)
10698         goto error_return;
10699
10700       amt = max_sym_count * sizeof (asection *);
10701       flinfo.sections = (asection **) bfd_malloc (amt);
10702       if (flinfo.sections == NULL)
10703         goto error_return;
10704     }
10705
10706   if (max_sym_shndx_count != 0)
10707     {
10708       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
10709       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
10710       if (flinfo.locsym_shndx == NULL)
10711         goto error_return;
10712     }
10713
10714   if (elf_hash_table (info)->tls_sec)
10715     {
10716       bfd_vma base, end = 0;
10717       asection *sec;
10718
10719       for (sec = elf_hash_table (info)->tls_sec;
10720            sec && (sec->flags & SEC_THREAD_LOCAL);
10721            sec = sec->next)
10722         {
10723           bfd_size_type size = sec->size;
10724
10725           if (size == 0
10726               && (sec->flags & SEC_HAS_CONTENTS) == 0)
10727             {
10728               struct bfd_link_order *ord = sec->map_tail.link_order;
10729
10730               if (ord != NULL)
10731                 size = ord->offset + ord->size;
10732             }
10733           end = sec->vma + size;
10734         }
10735       base = elf_hash_table (info)->tls_sec->vma;
10736       /* Only align end of TLS section if static TLS doesn't have special
10737          alignment requirements.  */
10738       if (bed->static_tls_alignment == 1)
10739         end = align_power (end,
10740                            elf_hash_table (info)->tls_sec->alignment_power);
10741       elf_hash_table (info)->tls_size = end - base;
10742     }
10743
10744   /* Reorder SHF_LINK_ORDER sections.  */
10745   for (o = abfd->sections; o != NULL; o = o->next)
10746     {
10747       if (!elf_fixup_link_order (abfd, o))
10748         return FALSE;
10749     }
10750
10751   /* Since ELF permits relocations to be against local symbols, we
10752      must have the local symbols available when we do the relocations.
10753      Since we would rather only read the local symbols once, and we
10754      would rather not keep them in memory, we handle all the
10755      relocations for a single input file at the same time.
10756
10757      Unfortunately, there is no way to know the total number of local
10758      symbols until we have seen all of them, and the local symbol
10759      indices precede the global symbol indices.  This means that when
10760      we are generating relocatable output, and we see a reloc against
10761      a global symbol, we can not know the symbol index until we have
10762      finished examining all the local symbols to see which ones we are
10763      going to output.  To deal with this, we keep the relocations in
10764      memory, and don't output them until the end of the link.  This is
10765      an unfortunate waste of memory, but I don't see a good way around
10766      it.  Fortunately, it only happens when performing a relocatable
10767      link, which is not the common case.  FIXME: If keep_memory is set
10768      we could write the relocs out and then read them again; I don't
10769      know how bad the memory loss will be.  */
10770
10771   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10772     sub->output_has_begun = FALSE;
10773   for (o = abfd->sections; o != NULL; o = o->next)
10774     {
10775       for (p = o->map_head.link_order; p != NULL; p = p->next)
10776         {
10777           if (p->type == bfd_indirect_link_order
10778               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
10779                   == bfd_target_elf_flavour)
10780               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
10781             {
10782               if (! sub->output_has_begun)
10783                 {
10784                   if (! elf_link_input_bfd (&flinfo, sub))
10785                     goto error_return;
10786                   sub->output_has_begun = TRUE;
10787                 }
10788             }
10789           else if (p->type == bfd_section_reloc_link_order
10790                    || p->type == bfd_symbol_reloc_link_order)
10791             {
10792               if (! elf_reloc_link_order (abfd, info, o, p))
10793                 goto error_return;
10794             }
10795           else
10796             {
10797               if (! _bfd_default_link_order (abfd, info, o, p))
10798                 {
10799                   if (p->type == bfd_indirect_link_order
10800                       && (bfd_get_flavour (sub)
10801                           == bfd_target_elf_flavour)
10802                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
10803                           != bed->s->elfclass))
10804                     {
10805                       const char *iclass, *oclass;
10806
10807                       if (bed->s->elfclass == ELFCLASS64)
10808                         {
10809                           iclass = "ELFCLASS32";
10810                           oclass = "ELFCLASS64";
10811                         }
10812                       else
10813                         {
10814                           iclass = "ELFCLASS64";
10815                           oclass = "ELFCLASS32";
10816                         }
10817
10818                       bfd_set_error (bfd_error_wrong_format);
10819                       (*_bfd_error_handler)
10820                         (_("%B: file class %s incompatible with %s"),
10821                          sub, iclass, oclass);
10822                     }
10823
10824                   goto error_return;
10825                 }
10826             }
10827         }
10828     }
10829
10830   /* Free symbol buffer if needed.  */
10831   if (!info->reduce_memory_overheads)
10832     {
10833       for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10834         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10835             && elf_tdata (sub)->symbuf)
10836           {
10837             free (elf_tdata (sub)->symbuf);
10838             elf_tdata (sub)->symbuf = NULL;
10839           }
10840     }
10841
10842   /* Output a FILE symbol so that following locals are not associated
10843      with the wrong input file.  */
10844   memset (&elfsym, 0, sizeof (elfsym));
10845   elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10846   elfsym.st_shndx = SHN_ABS;
10847
10848   if (flinfo.filesym_count > 1
10849       && !elf_link_output_sym (&flinfo, NULL, &elfsym,
10850                                bfd_und_section_ptr, NULL))
10851     return FALSE;
10852
10853   /* Output any global symbols that got converted to local in a
10854      version script or due to symbol visibility.  We do this in a
10855      separate step since ELF requires all local symbols to appear
10856      prior to any global symbols.  FIXME: We should only do this if
10857      some global symbols were, in fact, converted to become local.
10858      FIXME: Will this work correctly with the Irix 5 linker?  */
10859   eoinfo.failed = FALSE;
10860   eoinfo.flinfo = &flinfo;
10861   eoinfo.localsyms = TRUE;
10862   eoinfo.need_second_pass = FALSE;
10863   eoinfo.second_pass = FALSE;
10864   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
10865   if (eoinfo.failed)
10866     return FALSE;
10867
10868   if (flinfo.filesym_count == 1
10869       && !elf_link_output_sym (&flinfo, NULL, &elfsym,
10870                                bfd_und_section_ptr, NULL))
10871     return FALSE;
10872
10873   if (eoinfo.need_second_pass)
10874     {
10875       eoinfo.second_pass = TRUE;
10876       bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
10877       if (eoinfo.failed)
10878         return FALSE;
10879     }
10880
10881   /* If backend needs to output some local symbols not present in the hash
10882      table, do it now.  */
10883   if (bed->elf_backend_output_arch_local_syms)
10884     {
10885       typedef int (*out_sym_func)
10886         (void *, const char *, Elf_Internal_Sym *, asection *,
10887          struct elf_link_hash_entry *);
10888
10889       if (! ((*bed->elf_backend_output_arch_local_syms)
10890              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
10891         return FALSE;
10892     }
10893
10894   /* That wrote out all the local symbols.  Finish up the symbol table
10895      with the global symbols. Even if we want to strip everything we
10896      can, we still need to deal with those global symbols that got
10897      converted to local in a version script.  */
10898
10899   /* The sh_info field records the index of the first non local symbol.  */
10900   symtab_hdr->sh_info = bfd_get_symcount (abfd);
10901
10902   if (dynamic
10903       && flinfo.dynsym_sec != NULL
10904       && flinfo.dynsym_sec->output_section != bfd_abs_section_ptr)
10905     {
10906       Elf_Internal_Sym sym;
10907       bfd_byte *dynsym = flinfo.dynsym_sec->contents;
10908       long last_local = 0;
10909
10910       /* Write out the section symbols for the output sections.  */
10911       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
10912         {
10913           asection *s;
10914
10915           sym.st_size = 0;
10916           sym.st_name = 0;
10917           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10918           sym.st_other = 0;
10919           sym.st_target_internal = 0;
10920
10921           for (s = abfd->sections; s != NULL; s = s->next)
10922             {
10923               int indx;
10924               bfd_byte *dest;
10925               long dynindx;
10926
10927               dynindx = elf_section_data (s)->dynindx;
10928               if (dynindx <= 0)
10929                 continue;
10930               indx = elf_section_data (s)->this_idx;
10931               BFD_ASSERT (indx > 0);
10932               sym.st_shndx = indx;
10933               if (! check_dynsym (abfd, &sym))
10934                 return FALSE;
10935               sym.st_value = s->vma;
10936               dest = dynsym + dynindx * bed->s->sizeof_sym;
10937               if (last_local < dynindx)
10938                 last_local = dynindx;
10939               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
10940             }
10941         }
10942
10943       /* Write out the local dynsyms.  */
10944       if (elf_hash_table (info)->dynlocal)
10945         {
10946           struct elf_link_local_dynamic_entry *e;
10947           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
10948             {
10949               asection *s;
10950               bfd_byte *dest;
10951
10952               /* Copy the internal symbol and turn off visibility.
10953                  Note that we saved a word of storage and overwrote
10954                  the original st_name with the dynstr_index.  */
10955               sym = e->isym;
10956               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
10957
10958               s = bfd_section_from_elf_index (e->input_bfd,
10959                                               e->isym.st_shndx);
10960               if (s != NULL)
10961                 {
10962                   sym.st_shndx =
10963                     elf_section_data (s->output_section)->this_idx;
10964                   if (! check_dynsym (abfd, &sym))
10965                     return FALSE;
10966                   sym.st_value = (s->output_section->vma
10967                                   + s->output_offset
10968                                   + e->isym.st_value);
10969                 }
10970
10971               if (last_local < e->dynindx)
10972                 last_local = e->dynindx;
10973
10974               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
10975               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
10976             }
10977         }
10978
10979       elf_section_data (flinfo.dynsym_sec->output_section)->this_hdr.sh_info =
10980         last_local + 1;
10981     }
10982
10983   /* We get the global symbols from the hash table.  */
10984   eoinfo.failed = FALSE;
10985   eoinfo.localsyms = FALSE;
10986   eoinfo.flinfo = &flinfo;
10987   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
10988   if (eoinfo.failed)
10989     return FALSE;
10990
10991   /* If backend needs to output some symbols not present in the hash
10992      table, do it now.  */
10993   if (bed->elf_backend_output_arch_syms)
10994     {
10995       typedef int (*out_sym_func)
10996         (void *, const char *, Elf_Internal_Sym *, asection *,
10997          struct elf_link_hash_entry *);
10998
10999       if (! ((*bed->elf_backend_output_arch_syms)
11000              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
11001         return FALSE;
11002     }
11003
11004   /* Flush all symbols to the file.  */
11005   if (! elf_link_flush_output_syms (&flinfo, bed))
11006     return FALSE;
11007
11008   /* Now we know the size of the symtab section.  */
11009   off += symtab_hdr->sh_size;
11010
11011   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
11012   if (symtab_shndx_hdr->sh_name != 0)
11013     {
11014       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11015       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11016       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11017       amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11018       symtab_shndx_hdr->sh_size = amt;
11019
11020       off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11021                                                        off, TRUE);
11022
11023       if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11024           || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11025         return FALSE;
11026     }
11027
11028
11029   /* Finish up and write out the symbol string table (.strtab)
11030      section.  */
11031   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11032   /* sh_name was set in prep_headers.  */
11033   symstrtab_hdr->sh_type = SHT_STRTAB;
11034   symstrtab_hdr->sh_flags = 0;
11035   symstrtab_hdr->sh_addr = 0;
11036   symstrtab_hdr->sh_size = _bfd_stringtab_size (flinfo.symstrtab);
11037   symstrtab_hdr->sh_entsize = 0;
11038   symstrtab_hdr->sh_link = 0;
11039   symstrtab_hdr->sh_info = 0;
11040   /* sh_offset is set just below.  */
11041   symstrtab_hdr->sh_addralign = 1;
11042
11043   off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr, off, TRUE);
11044   elf_tdata (abfd)->next_file_pos = off;
11045
11046   if (bfd_get_symcount (abfd) > 0)
11047     {
11048       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11049           || ! _bfd_stringtab_emit (abfd, flinfo.symstrtab))
11050         return FALSE;
11051     }
11052
11053   /* Adjust the relocs to have the correct symbol indices.  */
11054   for (o = abfd->sections; o != NULL; o = o->next)
11055     {
11056       struct bfd_elf_section_data *esdo = elf_section_data (o);
11057       if ((o->flags & SEC_RELOC) == 0)
11058         continue;
11059
11060       if (esdo->rel.hdr != NULL)
11061         elf_link_adjust_relocs (abfd, &esdo->rel);
11062       if (esdo->rela.hdr != NULL)
11063         elf_link_adjust_relocs (abfd, &esdo->rela);
11064
11065       /* Set the reloc_count field to 0 to prevent write_relocs from
11066          trying to swap the relocs out itself.  */
11067       o->reloc_count = 0;
11068     }
11069
11070   if (dynamic && info->combreloc && dynobj != NULL)
11071     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11072
11073   /* If we are linking against a dynamic object, or generating a
11074      shared library, finish up the dynamic linking information.  */
11075   if (dynamic)
11076     {
11077       bfd_byte *dyncon, *dynconend;
11078
11079       /* Fix up .dynamic entries.  */
11080       o = bfd_get_section_by_name (dynobj, ".dynamic");
11081       BFD_ASSERT (o != NULL);
11082
11083       dyncon = o->contents;
11084       dynconend = o->contents + o->size;
11085       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11086         {
11087           Elf_Internal_Dyn dyn;
11088           const char *name;
11089           unsigned int type;
11090
11091           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11092
11093           switch (dyn.d_tag)
11094             {
11095             default:
11096               continue;
11097             case DT_NULL:
11098               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11099                 {
11100                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11101                     {
11102                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11103                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11104                     default: continue;
11105                     }
11106                   dyn.d_un.d_val = relativecount;
11107                   relativecount = 0;
11108                   break;
11109                 }
11110               continue;
11111
11112             case DT_INIT:
11113               name = info->init_function;
11114               goto get_sym;
11115             case DT_FINI:
11116               name = info->fini_function;
11117             get_sym:
11118               {
11119                 struct elf_link_hash_entry *h;
11120
11121                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11122                                           FALSE, FALSE, TRUE);
11123                 if (h != NULL
11124                     && (h->root.type == bfd_link_hash_defined
11125                         || h->root.type == bfd_link_hash_defweak))
11126                   {
11127                     dyn.d_un.d_ptr = h->root.u.def.value;
11128                     o = h->root.u.def.section;
11129                     if (o->output_section != NULL)
11130                       dyn.d_un.d_ptr += (o->output_section->vma
11131                                          + o->output_offset);
11132                     else
11133                       {
11134                         /* The symbol is imported from another shared
11135                            library and does not apply to this one.  */
11136                         dyn.d_un.d_ptr = 0;
11137                       }
11138                     break;
11139                   }
11140               }
11141               continue;
11142
11143             case DT_PREINIT_ARRAYSZ:
11144               name = ".preinit_array";
11145               goto get_size;
11146             case DT_INIT_ARRAYSZ:
11147               name = ".init_array";
11148               goto get_size;
11149             case DT_FINI_ARRAYSZ:
11150               name = ".fini_array";
11151             get_size:
11152               o = bfd_get_section_by_name (abfd, name);
11153               if (o == NULL)
11154                 {
11155                   (*_bfd_error_handler)
11156                     (_("%B: could not find output section %s"), abfd, name);
11157                   goto error_return;
11158                 }
11159               if (o->size == 0)
11160                 (*_bfd_error_handler)
11161                   (_("warning: %s section has zero size"), name);
11162               dyn.d_un.d_val = o->size;
11163               break;
11164
11165             case DT_PREINIT_ARRAY:
11166               name = ".preinit_array";
11167               goto get_vma;
11168             case DT_INIT_ARRAY:
11169               name = ".init_array";
11170               goto get_vma;
11171             case DT_FINI_ARRAY:
11172               name = ".fini_array";
11173               goto get_vma;
11174
11175             case DT_HASH:
11176               name = ".hash";
11177               goto get_vma;
11178             case DT_GNU_HASH:
11179               name = ".gnu.hash";
11180               goto get_vma;
11181             case DT_STRTAB:
11182               name = ".dynstr";
11183               goto get_vma;
11184             case DT_SYMTAB:
11185               name = ".dynsym";
11186               goto get_vma;
11187             case DT_VERDEF:
11188               name = ".gnu.version_d";
11189               goto get_vma;
11190             case DT_VERNEED:
11191               name = ".gnu.version_r";
11192               goto get_vma;
11193             case DT_VERSYM:
11194               name = ".gnu.version";
11195             get_vma:
11196               o = bfd_get_section_by_name (abfd, name);
11197               if (o == NULL)
11198                 {
11199                   (*_bfd_error_handler)
11200                     (_("%B: could not find output section %s"), abfd, name);
11201                   goto error_return;
11202                 }
11203               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11204                 {
11205                   (*_bfd_error_handler)
11206                     (_("warning: section '%s' is being made into a note"), name);
11207                   bfd_set_error (bfd_error_nonrepresentable_section);
11208                   goto error_return;
11209                 }
11210               dyn.d_un.d_ptr = o->vma;
11211               break;
11212
11213             case DT_REL:
11214             case DT_RELA:
11215             case DT_RELSZ:
11216             case DT_RELASZ:
11217               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11218                 type = SHT_REL;
11219               else
11220                 type = SHT_RELA;
11221               dyn.d_un.d_val = 0;
11222               dyn.d_un.d_ptr = 0;
11223               for (i = 1; i < elf_numsections (abfd); i++)
11224                 {
11225                   Elf_Internal_Shdr *hdr;
11226
11227                   hdr = elf_elfsections (abfd)[i];
11228                   if (hdr->sh_type == type
11229                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11230                     {
11231                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11232                         dyn.d_un.d_val += hdr->sh_size;
11233                       else
11234                         {
11235                           if (dyn.d_un.d_ptr == 0
11236                               || hdr->sh_addr < dyn.d_un.d_ptr)
11237                             dyn.d_un.d_ptr = hdr->sh_addr;
11238                         }
11239                     }
11240                 }
11241               break;
11242             }
11243           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11244         }
11245     }
11246
11247   /* If we have created any dynamic sections, then output them.  */
11248   if (dynobj != NULL)
11249     {
11250       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11251         goto error_return;
11252
11253       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11254       if (((info->warn_shared_textrel && info->shared)
11255            || info->error_textrel)
11256           && (o = bfd_get_section_by_name (dynobj, ".dynamic")) != NULL)
11257         {
11258           bfd_byte *dyncon, *dynconend;
11259
11260           dyncon = o->contents;
11261           dynconend = o->contents + o->size;
11262           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11263             {
11264               Elf_Internal_Dyn dyn;
11265
11266               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11267
11268               if (dyn.d_tag == DT_TEXTREL)
11269                 {
11270                   if (info->error_textrel)
11271                     info->callbacks->einfo
11272                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11273                   else
11274                     info->callbacks->einfo
11275                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11276                   break;
11277                 }
11278             }
11279         }
11280
11281       for (o = dynobj->sections; o != NULL; o = o->next)
11282         {
11283           if ((o->flags & SEC_HAS_CONTENTS) == 0
11284               || o->size == 0
11285               || o->output_section == bfd_abs_section_ptr)
11286             continue;
11287           if ((o->flags & SEC_LINKER_CREATED) == 0)
11288             {
11289               /* At this point, we are only interested in sections
11290                  created by _bfd_elf_link_create_dynamic_sections.  */
11291               continue;
11292             }
11293           if (elf_hash_table (info)->stab_info.stabstr == o)
11294             continue;
11295           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11296             continue;
11297           if ((elf_section_data (o->output_section)->this_hdr.sh_type
11298                != SHT_STRTAB)
11299               && (strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0))
11300             {
11301               /* FIXME: octets_per_byte.  */
11302               if (! bfd_set_section_contents (abfd, o->output_section,
11303                                               o->contents,
11304                                               (file_ptr) o->output_offset,
11305                                               o->size))
11306                 goto error_return;
11307             }
11308           else
11309             {
11310               /* The contents of the .dynstr section are actually in a
11311                  stringtab.  */
11312               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11313               if (bfd_seek (abfd, off, SEEK_SET) != 0
11314                   || ! _bfd_elf_strtab_emit (abfd,
11315                                              elf_hash_table (info)->dynstr))
11316                 goto error_return;
11317             }
11318         }
11319     }
11320
11321   if (info->relocatable)
11322     {
11323       bfd_boolean failed = FALSE;
11324
11325       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11326       if (failed)
11327         goto error_return;
11328     }
11329
11330   /* If we have optimized stabs strings, output them.  */
11331   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11332     {
11333       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11334         goto error_return;
11335     }
11336
11337   if (info->eh_frame_hdr)
11338     {
11339       if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11340         goto error_return;
11341     }
11342
11343   if (flinfo.symstrtab != NULL)
11344     _bfd_stringtab_free (flinfo.symstrtab);
11345   if (flinfo.contents != NULL)
11346     free (flinfo.contents);
11347   if (flinfo.external_relocs != NULL)
11348     free (flinfo.external_relocs);
11349   if (flinfo.internal_relocs != NULL)
11350     free (flinfo.internal_relocs);
11351   if (flinfo.external_syms != NULL)
11352     free (flinfo.external_syms);
11353   if (flinfo.locsym_shndx != NULL)
11354     free (flinfo.locsym_shndx);
11355   if (flinfo.internal_syms != NULL)
11356     free (flinfo.internal_syms);
11357   if (flinfo.indices != NULL)
11358     free (flinfo.indices);
11359   if (flinfo.sections != NULL)
11360     free (flinfo.sections);
11361   if (flinfo.symbuf != NULL)
11362     free (flinfo.symbuf);
11363   if (flinfo.symshndxbuf != NULL)
11364     free (flinfo.symshndxbuf);
11365   for (o = abfd->sections; o != NULL; o = o->next)
11366     {
11367       struct bfd_elf_section_data *esdo = elf_section_data (o);
11368       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11369         free (esdo->rel.hashes);
11370       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11371         free (esdo->rela.hashes);
11372     }
11373
11374   elf_tdata (abfd)->linker = TRUE;
11375
11376   if (attr_section)
11377     {
11378       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11379       if (contents == NULL)
11380         return FALSE;   /* Bail out and fail.  */
11381       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11382       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11383       free (contents);
11384     }
11385
11386   return TRUE;
11387
11388  error_return:
11389   if (flinfo.symstrtab != NULL)
11390     _bfd_stringtab_free (flinfo.symstrtab);
11391   if (flinfo.contents != NULL)
11392     free (flinfo.contents);
11393   if (flinfo.external_relocs != NULL)
11394     free (flinfo.external_relocs);
11395   if (flinfo.internal_relocs != NULL)
11396     free (flinfo.internal_relocs);
11397   if (flinfo.external_syms != NULL)
11398     free (flinfo.external_syms);
11399   if (flinfo.locsym_shndx != NULL)
11400     free (flinfo.locsym_shndx);
11401   if (flinfo.internal_syms != NULL)
11402     free (flinfo.internal_syms);
11403   if (flinfo.indices != NULL)
11404     free (flinfo.indices);
11405   if (flinfo.sections != NULL)
11406     free (flinfo.sections);
11407   if (flinfo.symbuf != NULL)
11408     free (flinfo.symbuf);
11409   if (flinfo.symshndxbuf != NULL)
11410     free (flinfo.symshndxbuf);
11411   for (o = abfd->sections; o != NULL; o = o->next)
11412     {
11413       struct bfd_elf_section_data *esdo = elf_section_data (o);
11414       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11415         free (esdo->rel.hashes);
11416       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11417         free (esdo->rela.hashes);
11418     }
11419
11420   return FALSE;
11421 }
11422 \f
11423 /* Initialize COOKIE for input bfd ABFD.  */
11424
11425 static bfd_boolean
11426 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11427                    struct bfd_link_info *info, bfd *abfd)
11428 {
11429   Elf_Internal_Shdr *symtab_hdr;
11430   const struct elf_backend_data *bed;
11431
11432   bed = get_elf_backend_data (abfd);
11433   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11434
11435   cookie->abfd = abfd;
11436   cookie->sym_hashes = elf_sym_hashes (abfd);
11437   cookie->bad_symtab = elf_bad_symtab (abfd);
11438   if (cookie->bad_symtab)
11439     {
11440       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11441       cookie->extsymoff = 0;
11442     }
11443   else
11444     {
11445       cookie->locsymcount = symtab_hdr->sh_info;
11446       cookie->extsymoff = symtab_hdr->sh_info;
11447     }
11448
11449   if (bed->s->arch_size == 32)
11450     cookie->r_sym_shift = 8;
11451   else
11452     cookie->r_sym_shift = 32;
11453
11454   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11455   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11456     {
11457       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11458                                               cookie->locsymcount, 0,
11459                                               NULL, NULL, NULL);
11460       if (cookie->locsyms == NULL)
11461         {
11462           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11463           return FALSE;
11464         }
11465       if (info->keep_memory)
11466         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11467     }
11468   return TRUE;
11469 }
11470
11471 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11472
11473 static void
11474 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11475 {
11476   Elf_Internal_Shdr *symtab_hdr;
11477
11478   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11479   if (cookie->locsyms != NULL
11480       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11481     free (cookie->locsyms);
11482 }
11483
11484 /* Initialize the relocation information in COOKIE for input section SEC
11485    of input bfd ABFD.  */
11486
11487 static bfd_boolean
11488 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11489                         struct bfd_link_info *info, bfd *abfd,
11490                         asection *sec)
11491 {
11492   const struct elf_backend_data *bed;
11493
11494   if (sec->reloc_count == 0)
11495     {
11496       cookie->rels = NULL;
11497       cookie->relend = NULL;
11498     }
11499   else
11500     {
11501       bed = get_elf_backend_data (abfd);
11502
11503       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11504                                                 info->keep_memory);
11505       if (cookie->rels == NULL)
11506         return FALSE;
11507       cookie->rel = cookie->rels;
11508       cookie->relend = (cookie->rels
11509                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11510     }
11511   cookie->rel = cookie->rels;
11512   return TRUE;
11513 }
11514
11515 /* Free the memory allocated by init_reloc_cookie_rels,
11516    if appropriate.  */
11517
11518 static void
11519 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11520                         asection *sec)
11521 {
11522   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11523     free (cookie->rels);
11524 }
11525
11526 /* Initialize the whole of COOKIE for input section SEC.  */
11527
11528 static bfd_boolean
11529 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11530                                struct bfd_link_info *info,
11531                                asection *sec)
11532 {
11533   if (!init_reloc_cookie (cookie, info, sec->owner))
11534     goto error1;
11535   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11536     goto error2;
11537   return TRUE;
11538
11539  error2:
11540   fini_reloc_cookie (cookie, sec->owner);
11541  error1:
11542   return FALSE;
11543 }
11544
11545 /* Free the memory allocated by init_reloc_cookie_for_section,
11546    if appropriate.  */
11547
11548 static void
11549 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11550                                asection *sec)
11551 {
11552   fini_reloc_cookie_rels (cookie, sec);
11553   fini_reloc_cookie (cookie, sec->owner);
11554 }
11555 \f
11556 /* Garbage collect unused sections.  */
11557
11558 /* Default gc_mark_hook.  */
11559
11560 asection *
11561 _bfd_elf_gc_mark_hook (asection *sec,
11562                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
11563                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
11564                        struct elf_link_hash_entry *h,
11565                        Elf_Internal_Sym *sym)
11566 {
11567   const char *sec_name;
11568
11569   if (h != NULL)
11570     {
11571       switch (h->root.type)
11572         {
11573         case bfd_link_hash_defined:
11574         case bfd_link_hash_defweak:
11575           return h->root.u.def.section;
11576
11577         case bfd_link_hash_common:
11578           return h->root.u.c.p->section;
11579
11580         case bfd_link_hash_undefined:
11581         case bfd_link_hash_undefweak:
11582           /* To work around a glibc bug, keep all XXX input sections
11583              when there is an as yet undefined reference to __start_XXX
11584              or __stop_XXX symbols.  The linker will later define such
11585              symbols for orphan input sections that have a name
11586              representable as a C identifier.  */
11587           if (strncmp (h->root.root.string, "__start_", 8) == 0)
11588             sec_name = h->root.root.string + 8;
11589           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
11590             sec_name = h->root.root.string + 7;
11591           else
11592             sec_name = NULL;
11593
11594           if (sec_name && *sec_name != '\0')
11595             {
11596               bfd *i;
11597               
11598               for (i = info->input_bfds; i; i = i->link_next)
11599                 {
11600                   sec = bfd_get_section_by_name (i, sec_name);
11601                   if (sec)
11602                     sec->flags |= SEC_KEEP;
11603                 }
11604             }
11605           break;
11606
11607         default:
11608           break;
11609         }
11610     }
11611   else
11612     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
11613
11614   return NULL;
11615 }
11616
11617 /* COOKIE->rel describes a relocation against section SEC, which is
11618    a section we've decided to keep.  Return the section that contains
11619    the relocation symbol, or NULL if no section contains it.  */
11620
11621 asection *
11622 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
11623                        elf_gc_mark_hook_fn gc_mark_hook,
11624                        struct elf_reloc_cookie *cookie)
11625 {
11626   unsigned long r_symndx;
11627   struct elf_link_hash_entry *h;
11628
11629   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
11630   if (r_symndx == STN_UNDEF)
11631     return NULL;
11632
11633   if (r_symndx >= cookie->locsymcount
11634       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11635     {
11636       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
11637       while (h->root.type == bfd_link_hash_indirect
11638              || h->root.type == bfd_link_hash_warning)
11639         h = (struct elf_link_hash_entry *) h->root.u.i.link;
11640       h->mark = 1;
11641       /* If this symbol is weak and there is a non-weak definition, we
11642          keep the non-weak definition because many backends put
11643          dynamic reloc info on the non-weak definition for code
11644          handling copy relocs.  */
11645       if (h->u.weakdef != NULL)
11646         h->u.weakdef->mark = 1;
11647       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
11648     }
11649
11650   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
11651                           &cookie->locsyms[r_symndx]);
11652 }
11653
11654 /* COOKIE->rel describes a relocation against section SEC, which is
11655    a section we've decided to keep.  Mark the section that contains
11656    the relocation symbol.  */
11657
11658 bfd_boolean
11659 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
11660                         asection *sec,
11661                         elf_gc_mark_hook_fn gc_mark_hook,
11662                         struct elf_reloc_cookie *cookie)
11663 {
11664   asection *rsec;
11665
11666   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
11667   if (rsec && !rsec->gc_mark)
11668     {
11669       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
11670           || (rsec->owner->flags & DYNAMIC) != 0)
11671         rsec->gc_mark = 1;
11672       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
11673         return FALSE;
11674     }
11675   return TRUE;
11676 }
11677
11678 /* The mark phase of garbage collection.  For a given section, mark
11679    it and any sections in this section's group, and all the sections
11680    which define symbols to which it refers.  */
11681
11682 bfd_boolean
11683 _bfd_elf_gc_mark (struct bfd_link_info *info,
11684                   asection *sec,
11685                   elf_gc_mark_hook_fn gc_mark_hook)
11686 {
11687   bfd_boolean ret;
11688   asection *group_sec, *eh_frame;
11689
11690   sec->gc_mark = 1;
11691
11692   /* Mark all the sections in the group.  */
11693   group_sec = elf_section_data (sec)->next_in_group;
11694   if (group_sec && !group_sec->gc_mark)
11695     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
11696       return FALSE;
11697
11698   /* Look through the section relocs.  */
11699   ret = TRUE;
11700   eh_frame = elf_eh_frame_section (sec->owner);
11701   if ((sec->flags & SEC_RELOC) != 0
11702       && sec->reloc_count > 0
11703       && sec != eh_frame)
11704     {
11705       struct elf_reloc_cookie cookie;
11706
11707       if (!init_reloc_cookie_for_section (&cookie, info, sec))
11708         ret = FALSE;
11709       else
11710         {
11711           for (; cookie.rel < cookie.relend; cookie.rel++)
11712             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
11713               {
11714                 ret = FALSE;
11715                 break;
11716               }
11717           fini_reloc_cookie_for_section (&cookie, sec);
11718         }
11719     }
11720
11721   if (ret && eh_frame && elf_fde_list (sec))
11722     {
11723       struct elf_reloc_cookie cookie;
11724
11725       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
11726         ret = FALSE;
11727       else
11728         {
11729           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
11730                                       gc_mark_hook, &cookie))
11731             ret = FALSE;
11732           fini_reloc_cookie_for_section (&cookie, eh_frame);
11733         }
11734     }
11735
11736   return ret;
11737 }
11738
11739 /* Keep debug and special sections.  */
11740
11741 bfd_boolean
11742 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
11743                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
11744 {
11745   bfd *ibfd;
11746
11747   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
11748     {
11749       asection *isec;
11750       bfd_boolean some_kept;
11751
11752       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
11753         continue;
11754
11755       /* Ensure all linker created sections are kept, and see whether
11756          any other section is already marked.  */
11757       some_kept = FALSE;
11758       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11759         {
11760           if ((isec->flags & SEC_LINKER_CREATED) != 0)
11761             isec->gc_mark = 1;
11762           else if (isec->gc_mark)
11763             some_kept = TRUE;
11764         }
11765
11766       /* If no section in this file will be kept, then we can
11767          toss out debug sections.  */
11768       if (!some_kept)
11769         continue;
11770
11771       /* Keep debug and special sections like .comment when they are
11772          not part of a group, or when we have single-member groups.  */
11773       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11774         if ((elf_next_in_group (isec) == NULL
11775              || elf_next_in_group (isec) == isec)
11776             && ((isec->flags & SEC_DEBUGGING) != 0
11777                 || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0))
11778           isec->gc_mark = 1;
11779     }
11780   return TRUE;
11781 }
11782
11783 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
11784
11785 struct elf_gc_sweep_symbol_info
11786 {
11787   struct bfd_link_info *info;
11788   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
11789                        bfd_boolean);
11790 };
11791
11792 static bfd_boolean
11793 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
11794 {
11795   if (!h->mark
11796       && (((h->root.type == bfd_link_hash_defined
11797             || h->root.type == bfd_link_hash_defweak)
11798            && !(h->def_regular
11799                 && h->root.u.def.section->gc_mark))
11800           || h->root.type == bfd_link_hash_undefined
11801           || h->root.type == bfd_link_hash_undefweak))
11802     {
11803       struct elf_gc_sweep_symbol_info *inf;
11804
11805       inf = (struct elf_gc_sweep_symbol_info *) data;
11806       (*inf->hide_symbol) (inf->info, h, TRUE);
11807       h->def_regular = 0;
11808       h->ref_regular = 0;
11809       h->ref_regular_nonweak = 0;
11810     }
11811
11812   return TRUE;
11813 }
11814
11815 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
11816
11817 typedef bfd_boolean (*gc_sweep_hook_fn)
11818   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
11819
11820 static bfd_boolean
11821 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
11822 {
11823   bfd *sub;
11824   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11825   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
11826   unsigned long section_sym_count;
11827   struct elf_gc_sweep_symbol_info sweep_info;
11828
11829   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
11830     {
11831       asection *o;
11832
11833       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
11834         continue;
11835
11836       for (o = sub->sections; o != NULL; o = o->next)
11837         {
11838           /* When any section in a section group is kept, we keep all
11839              sections in the section group.  If the first member of
11840              the section group is excluded, we will also exclude the
11841              group section.  */
11842           if (o->flags & SEC_GROUP)
11843             {
11844               asection *first = elf_next_in_group (o);
11845               o->gc_mark = first->gc_mark;
11846             }
11847
11848           if (o->gc_mark)
11849             continue;
11850
11851           /* Skip sweeping sections already excluded.  */
11852           if (o->flags & SEC_EXCLUDE)
11853             continue;
11854
11855           /* Since this is early in the link process, it is simple
11856              to remove a section from the output.  */
11857           o->flags |= SEC_EXCLUDE;
11858
11859           if (info->print_gc_sections && o->size != 0)
11860             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
11861
11862           /* But we also have to update some of the relocation
11863              info we collected before.  */
11864           if (gc_sweep_hook
11865               && (o->flags & SEC_RELOC) != 0
11866               && o->reloc_count > 0
11867               && !bfd_is_abs_section (o->output_section))
11868             {
11869               Elf_Internal_Rela *internal_relocs;
11870               bfd_boolean r;
11871
11872               internal_relocs
11873                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
11874                                              info->keep_memory);
11875               if (internal_relocs == NULL)
11876                 return FALSE;
11877
11878               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
11879
11880               if (elf_section_data (o)->relocs != internal_relocs)
11881                 free (internal_relocs);
11882
11883               if (!r)
11884                 return FALSE;
11885             }
11886         }
11887     }
11888
11889   /* Remove the symbols that were in the swept sections from the dynamic
11890      symbol table.  GCFIXME: Anyone know how to get them out of the
11891      static symbol table as well?  */
11892   sweep_info.info = info;
11893   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
11894   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
11895                           &sweep_info);
11896
11897   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
11898   return TRUE;
11899 }
11900
11901 /* Propagate collected vtable information.  This is called through
11902    elf_link_hash_traverse.  */
11903
11904 static bfd_boolean
11905 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
11906 {
11907   /* Those that are not vtables.  */
11908   if (h->vtable == NULL || h->vtable->parent == NULL)
11909     return TRUE;
11910
11911   /* Those vtables that do not have parents, we cannot merge.  */
11912   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
11913     return TRUE;
11914
11915   /* If we've already been done, exit.  */
11916   if (h->vtable->used && h->vtable->used[-1])
11917     return TRUE;
11918
11919   /* Make sure the parent's table is up to date.  */
11920   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
11921
11922   if (h->vtable->used == NULL)
11923     {
11924       /* None of this table's entries were referenced.  Re-use the
11925          parent's table.  */
11926       h->vtable->used = h->vtable->parent->vtable->used;
11927       h->vtable->size = h->vtable->parent->vtable->size;
11928     }
11929   else
11930     {
11931       size_t n;
11932       bfd_boolean *cu, *pu;
11933
11934       /* Or the parent's entries into ours.  */
11935       cu = h->vtable->used;
11936       cu[-1] = TRUE;
11937       pu = h->vtable->parent->vtable->used;
11938       if (pu != NULL)
11939         {
11940           const struct elf_backend_data *bed;
11941           unsigned int log_file_align;
11942
11943           bed = get_elf_backend_data (h->root.u.def.section->owner);
11944           log_file_align = bed->s->log_file_align;
11945           n = h->vtable->parent->vtable->size >> log_file_align;
11946           while (n--)
11947             {
11948               if (*pu)
11949                 *cu = TRUE;
11950               pu++;
11951               cu++;
11952             }
11953         }
11954     }
11955
11956   return TRUE;
11957 }
11958
11959 static bfd_boolean
11960 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
11961 {
11962   asection *sec;
11963   bfd_vma hstart, hend;
11964   Elf_Internal_Rela *relstart, *relend, *rel;
11965   const struct elf_backend_data *bed;
11966   unsigned int log_file_align;
11967
11968   /* Take care of both those symbols that do not describe vtables as
11969      well as those that are not loaded.  */
11970   if (h->vtable == NULL || h->vtable->parent == NULL)
11971     return TRUE;
11972
11973   BFD_ASSERT (h->root.type == bfd_link_hash_defined
11974               || h->root.type == bfd_link_hash_defweak);
11975
11976   sec = h->root.u.def.section;
11977   hstart = h->root.u.def.value;
11978   hend = hstart + h->size;
11979
11980   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
11981   if (!relstart)
11982     return *(bfd_boolean *) okp = FALSE;
11983   bed = get_elf_backend_data (sec->owner);
11984   log_file_align = bed->s->log_file_align;
11985
11986   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
11987
11988   for (rel = relstart; rel < relend; ++rel)
11989     if (rel->r_offset >= hstart && rel->r_offset < hend)
11990       {
11991         /* If the entry is in use, do nothing.  */
11992         if (h->vtable->used
11993             && (rel->r_offset - hstart) < h->vtable->size)
11994           {
11995             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
11996             if (h->vtable->used[entry])
11997               continue;
11998           }
11999         /* Otherwise, kill it.  */
12000         rel->r_offset = rel->r_info = rel->r_addend = 0;
12001       }
12002
12003   return TRUE;
12004 }
12005
12006 /* Mark sections containing dynamically referenced symbols.  When
12007    building shared libraries, we must assume that any visible symbol is
12008    referenced.  */
12009
12010 bfd_boolean
12011 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12012 {
12013   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12014
12015   if ((h->root.type == bfd_link_hash_defined
12016        || h->root.type == bfd_link_hash_defweak)
12017       && (h->ref_dynamic
12018           || ((!info->executable || info->export_dynamic)
12019               && h->def_regular
12020               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12021               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12022               && (strchr (h->root.root.string, ELF_VER_CHR) != NULL
12023                   || !bfd_hide_sym_by_version (info->version_info,
12024                                                h->root.root.string)))))
12025     h->root.u.def.section->flags |= SEC_KEEP;
12026
12027   return TRUE;
12028 }
12029
12030 /* Keep all sections containing symbols undefined on the command-line,
12031    and the section containing the entry symbol.  */
12032
12033 void
12034 _bfd_elf_gc_keep (struct bfd_link_info *info)
12035 {
12036   struct bfd_sym_chain *sym;
12037
12038   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12039     {
12040       struct elf_link_hash_entry *h;
12041
12042       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12043                                 FALSE, FALSE, FALSE);
12044
12045       if (h != NULL
12046           && (h->root.type == bfd_link_hash_defined
12047               || h->root.type == bfd_link_hash_defweak)
12048           && !bfd_is_abs_section (h->root.u.def.section))
12049         h->root.u.def.section->flags |= SEC_KEEP;
12050     }
12051 }
12052
12053 /* Do mark and sweep of unused sections.  */
12054
12055 bfd_boolean
12056 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12057 {
12058   bfd_boolean ok = TRUE;
12059   bfd *sub;
12060   elf_gc_mark_hook_fn gc_mark_hook;
12061   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12062
12063   if (!bed->can_gc_sections
12064       || !is_elf_hash_table (info->hash))
12065     {
12066       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12067       return TRUE;
12068     }
12069
12070   bed->gc_keep (info);
12071
12072   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12073      at the .eh_frame section if we can mark the FDEs individually.  */
12074   _bfd_elf_begin_eh_frame_parsing (info);
12075   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
12076     {
12077       asection *sec;
12078       struct elf_reloc_cookie cookie;
12079
12080       sec = bfd_get_section_by_name (sub, ".eh_frame");
12081       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12082         {
12083           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12084           if (elf_section_data (sec)->sec_info
12085               && (sec->flags & SEC_LINKER_CREATED) == 0)
12086             elf_eh_frame_section (sub) = sec;
12087           fini_reloc_cookie_for_section (&cookie, sec);
12088           sec = bfd_get_next_section_by_name (sec);
12089         }
12090     }
12091   _bfd_elf_end_eh_frame_parsing (info);
12092
12093   /* Apply transitive closure to the vtable entry usage info.  */
12094   elf_link_hash_traverse (elf_hash_table (info),
12095                           elf_gc_propagate_vtable_entries_used,
12096                           &ok);
12097   if (!ok)
12098     return FALSE;
12099
12100   /* Kill the vtable relocations that were not used.  */
12101   elf_link_hash_traverse (elf_hash_table (info),
12102                           elf_gc_smash_unused_vtentry_relocs,
12103                           &ok);
12104   if (!ok)
12105     return FALSE;
12106
12107   /* Mark dynamically referenced symbols.  */
12108   if (elf_hash_table (info)->dynamic_sections_created)
12109     elf_link_hash_traverse (elf_hash_table (info),
12110                             bed->gc_mark_dynamic_ref,
12111                             info);
12112
12113   /* Grovel through relocs to find out who stays ...  */
12114   gc_mark_hook = bed->gc_mark_hook;
12115   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
12116     {
12117       asection *o;
12118
12119       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12120         continue;
12121
12122       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12123          Also treat note sections as a root, if the section is not part
12124          of a group.  */
12125       for (o = sub->sections; o != NULL; o = o->next)
12126         if (!o->gc_mark
12127             && (o->flags & SEC_EXCLUDE) == 0
12128             && ((o->flags & SEC_KEEP) != 0
12129                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12130                     && elf_next_in_group (o) == NULL )))
12131           {
12132             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12133               return FALSE;
12134           }
12135     }
12136
12137   /* Allow the backend to mark additional target specific sections.  */
12138   bed->gc_mark_extra_sections (info, gc_mark_hook);
12139
12140   /* ... and mark SEC_EXCLUDE for those that go.  */
12141   return elf_gc_sweep (abfd, info);
12142 }
12143 \f
12144 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12145
12146 bfd_boolean
12147 bfd_elf_gc_record_vtinherit (bfd *abfd,
12148                              asection *sec,
12149                              struct elf_link_hash_entry *h,
12150                              bfd_vma offset)
12151 {
12152   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12153   struct elf_link_hash_entry **search, *child;
12154   bfd_size_type extsymcount;
12155   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12156
12157   /* The sh_info field of the symtab header tells us where the
12158      external symbols start.  We don't care about the local symbols at
12159      this point.  */
12160   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12161   if (!elf_bad_symtab (abfd))
12162     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12163
12164   sym_hashes = elf_sym_hashes (abfd);
12165   sym_hashes_end = sym_hashes + extsymcount;
12166
12167   /* Hunt down the child symbol, which is in this section at the same
12168      offset as the relocation.  */
12169   for (search = sym_hashes; search != sym_hashes_end; ++search)
12170     {
12171       if ((child = *search) != NULL
12172           && (child->root.type == bfd_link_hash_defined
12173               || child->root.type == bfd_link_hash_defweak)
12174           && child->root.u.def.section == sec
12175           && child->root.u.def.value == offset)
12176         goto win;
12177     }
12178
12179   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12180                          abfd, sec, (unsigned long) offset);
12181   bfd_set_error (bfd_error_invalid_operation);
12182   return FALSE;
12183
12184  win:
12185   if (!child->vtable)
12186     {
12187       child->vtable = (struct elf_link_virtual_table_entry *)
12188           bfd_zalloc (abfd, sizeof (*child->vtable));
12189       if (!child->vtable)
12190         return FALSE;
12191     }
12192   if (!h)
12193     {
12194       /* This *should* only be the absolute section.  It could potentially
12195          be that someone has defined a non-global vtable though, which
12196          would be bad.  It isn't worth paging in the local symbols to be
12197          sure though; that case should simply be handled by the assembler.  */
12198
12199       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12200     }
12201   else
12202     child->vtable->parent = h;
12203
12204   return TRUE;
12205 }
12206
12207 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12208
12209 bfd_boolean
12210 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12211                            asection *sec ATTRIBUTE_UNUSED,
12212                            struct elf_link_hash_entry *h,
12213                            bfd_vma addend)
12214 {
12215   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12216   unsigned int log_file_align = bed->s->log_file_align;
12217
12218   if (!h->vtable)
12219     {
12220       h->vtable = (struct elf_link_virtual_table_entry *)
12221           bfd_zalloc (abfd, sizeof (*h->vtable));
12222       if (!h->vtable)
12223         return FALSE;
12224     }
12225
12226   if (addend >= h->vtable->size)
12227     {
12228       size_t size, bytes, file_align;
12229       bfd_boolean *ptr = h->vtable->used;
12230
12231       /* While the symbol is undefined, we have to be prepared to handle
12232          a zero size.  */
12233       file_align = 1 << log_file_align;
12234       if (h->root.type == bfd_link_hash_undefined)
12235         size = addend + file_align;
12236       else
12237         {
12238           size = h->size;
12239           if (addend >= size)
12240             {
12241               /* Oops!  We've got a reference past the defined end of
12242                  the table.  This is probably a bug -- shall we warn?  */
12243               size = addend + file_align;
12244             }
12245         }
12246       size = (size + file_align - 1) & -file_align;
12247
12248       /* Allocate one extra entry for use as a "done" flag for the
12249          consolidation pass.  */
12250       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12251
12252       if (ptr)
12253         {
12254           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12255
12256           if (ptr != NULL)
12257             {
12258               size_t oldbytes;
12259
12260               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12261                           * sizeof (bfd_boolean));
12262               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12263             }
12264         }
12265       else
12266         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12267
12268       if (ptr == NULL)
12269         return FALSE;
12270
12271       /* And arrange for that done flag to be at index -1.  */
12272       h->vtable->used = ptr + 1;
12273       h->vtable->size = size;
12274     }
12275
12276   h->vtable->used[addend >> log_file_align] = TRUE;
12277
12278   return TRUE;
12279 }
12280
12281 /* Map an ELF section header flag to its corresponding string.  */
12282 typedef struct
12283 {
12284   char *flag_name;
12285   flagword flag_value;
12286 } elf_flags_to_name_table;
12287
12288 static elf_flags_to_name_table elf_flags_to_names [] =
12289 {
12290   { "SHF_WRITE", SHF_WRITE },
12291   { "SHF_ALLOC", SHF_ALLOC },
12292   { "SHF_EXECINSTR", SHF_EXECINSTR },
12293   { "SHF_MERGE", SHF_MERGE },
12294   { "SHF_STRINGS", SHF_STRINGS },
12295   { "SHF_INFO_LINK", SHF_INFO_LINK},
12296   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12297   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12298   { "SHF_GROUP", SHF_GROUP },
12299   { "SHF_TLS", SHF_TLS },
12300   { "SHF_MASKOS", SHF_MASKOS },
12301   { "SHF_EXCLUDE", SHF_EXCLUDE },
12302 };
12303
12304 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
12305 bfd_boolean
12306 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12307                               struct flag_info *flaginfo,
12308                               asection *section)
12309 {
12310   const bfd_vma sh_flags = elf_section_flags (section);
12311
12312   if (!flaginfo->flags_initialized)
12313     {
12314       bfd *obfd = info->output_bfd;
12315       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12316       struct flag_info_list *tf = flaginfo->flag_list;
12317       int with_hex = 0;
12318       int without_hex = 0;
12319
12320       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
12321         {
12322           unsigned i;
12323           flagword (*lookup) (char *);
12324
12325           lookup = bed->elf_backend_lookup_section_flags_hook;
12326           if (lookup != NULL)
12327             {
12328               flagword hexval = (*lookup) ((char *) tf->name);
12329
12330               if (hexval != 0)
12331                 {
12332                   if (tf->with == with_flags)
12333                     with_hex |= hexval;
12334                   else if (tf->with == without_flags)
12335                     without_hex |= hexval;
12336                   tf->valid = TRUE;
12337                   continue;
12338                 }
12339             }
12340           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
12341             {
12342               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
12343                 {
12344                   if (tf->with == with_flags)
12345                     with_hex |= elf_flags_to_names[i].flag_value;
12346                   else if (tf->with == without_flags)
12347                     without_hex |= elf_flags_to_names[i].flag_value;
12348                   tf->valid = TRUE;
12349                   break;
12350                 }
12351             }
12352           if (!tf->valid)
12353             {
12354               info->callbacks->einfo 
12355                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12356               return FALSE;
12357             }
12358         }
12359       flaginfo->flags_initialized = TRUE;
12360       flaginfo->only_with_flags |= with_hex;
12361       flaginfo->not_with_flags |= without_hex;
12362     }
12363
12364   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
12365     return FALSE;
12366
12367   if ((flaginfo->not_with_flags & sh_flags) != 0)
12368     return FALSE;
12369
12370   return TRUE;
12371 }
12372
12373 struct alloc_got_off_arg {
12374   bfd_vma gotoff;
12375   struct bfd_link_info *info;
12376 };
12377
12378 /* We need a special top-level link routine to convert got reference counts
12379    to real got offsets.  */
12380
12381 static bfd_boolean
12382 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12383 {
12384   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12385   bfd *obfd = gofarg->info->output_bfd;
12386   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12387
12388   if (h->got.refcount > 0)
12389     {
12390       h->got.offset = gofarg->gotoff;
12391       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12392     }
12393   else
12394     h->got.offset = (bfd_vma) -1;
12395
12396   return TRUE;
12397 }
12398
12399 /* And an accompanying bit to work out final got entry offsets once
12400    we're done.  Should be called from final_link.  */
12401
12402 bfd_boolean
12403 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12404                                         struct bfd_link_info *info)
12405 {
12406   bfd *i;
12407   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12408   bfd_vma gotoff;
12409   struct alloc_got_off_arg gofarg;
12410
12411   BFD_ASSERT (abfd == info->output_bfd);
12412
12413   if (! is_elf_hash_table (info->hash))
12414     return FALSE;
12415
12416   /* The GOT offset is relative to the .got section, but the GOT header is
12417      put into the .got.plt section, if the backend uses it.  */
12418   if (bed->want_got_plt)
12419     gotoff = 0;
12420   else
12421     gotoff = bed->got_header_size;
12422
12423   /* Do the local .got entries first.  */
12424   for (i = info->input_bfds; i; i = i->link_next)
12425     {
12426       bfd_signed_vma *local_got;
12427       bfd_size_type j, locsymcount;
12428       Elf_Internal_Shdr *symtab_hdr;
12429
12430       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
12431         continue;
12432
12433       local_got = elf_local_got_refcounts (i);
12434       if (!local_got)
12435         continue;
12436
12437       symtab_hdr = &elf_tdata (i)->symtab_hdr;
12438       if (elf_bad_symtab (i))
12439         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12440       else
12441         locsymcount = symtab_hdr->sh_info;
12442
12443       for (j = 0; j < locsymcount; ++j)
12444         {
12445           if (local_got[j] > 0)
12446             {
12447               local_got[j] = gotoff;
12448               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
12449             }
12450           else
12451             local_got[j] = (bfd_vma) -1;
12452         }
12453     }
12454
12455   /* Then the global .got entries.  .plt refcounts are handled by
12456      adjust_dynamic_symbol  */
12457   gofarg.gotoff = gotoff;
12458   gofarg.info = info;
12459   elf_link_hash_traverse (elf_hash_table (info),
12460                           elf_gc_allocate_got_offsets,
12461                           &gofarg);
12462   return TRUE;
12463 }
12464
12465 /* Many folk need no more in the way of final link than this, once
12466    got entry reference counting is enabled.  */
12467
12468 bfd_boolean
12469 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
12470 {
12471   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
12472     return FALSE;
12473
12474   /* Invoke the regular ELF backend linker to do all the work.  */
12475   return bfd_elf_final_link (abfd, info);
12476 }
12477
12478 bfd_boolean
12479 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
12480 {
12481   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
12482
12483   if (rcookie->bad_symtab)
12484     rcookie->rel = rcookie->rels;
12485
12486   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
12487     {
12488       unsigned long r_symndx;
12489
12490       if (! rcookie->bad_symtab)
12491         if (rcookie->rel->r_offset > offset)
12492           return FALSE;
12493       if (rcookie->rel->r_offset != offset)
12494         continue;
12495
12496       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
12497       if (r_symndx == STN_UNDEF)
12498         return TRUE;
12499
12500       if (r_symndx >= rcookie->locsymcount
12501           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12502         {
12503           struct elf_link_hash_entry *h;
12504
12505           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
12506
12507           while (h->root.type == bfd_link_hash_indirect
12508                  || h->root.type == bfd_link_hash_warning)
12509             h = (struct elf_link_hash_entry *) h->root.u.i.link;
12510
12511           if ((h->root.type == bfd_link_hash_defined
12512                || h->root.type == bfd_link_hash_defweak)
12513               && discarded_section (h->root.u.def.section))
12514             return TRUE;
12515           else
12516             return FALSE;
12517         }
12518       else
12519         {
12520           /* It's not a relocation against a global symbol,
12521              but it could be a relocation against a local
12522              symbol for a discarded section.  */
12523           asection *isec;
12524           Elf_Internal_Sym *isym;
12525
12526           /* Need to: get the symbol; get the section.  */
12527           isym = &rcookie->locsyms[r_symndx];
12528           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
12529           if (isec != NULL && discarded_section (isec))
12530             return TRUE;
12531         }
12532       return FALSE;
12533     }
12534   return FALSE;
12535 }
12536
12537 /* Discard unneeded references to discarded sections.
12538    Returns TRUE if any section's size was changed.  */
12539 /* This function assumes that the relocations are in sorted order,
12540    which is true for all known assemblers.  */
12541
12542 bfd_boolean
12543 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
12544 {
12545   struct elf_reloc_cookie cookie;
12546   asection *stab, *eh;
12547   const struct elf_backend_data *bed;
12548   bfd *abfd;
12549   bfd_boolean ret = FALSE;
12550
12551   if (info->traditional_format
12552       || !is_elf_hash_table (info->hash))
12553     return FALSE;
12554
12555   _bfd_elf_begin_eh_frame_parsing (info);
12556   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
12557     {
12558       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12559         continue;
12560
12561       bed = get_elf_backend_data (abfd);
12562
12563       eh = NULL;
12564       if (!info->relocatable)
12565         {
12566           eh = bfd_get_section_by_name (abfd, ".eh_frame");
12567           while (eh != NULL
12568                  && (eh->size == 0
12569                      || bfd_is_abs_section (eh->output_section)))
12570             eh = bfd_get_next_section_by_name (eh);
12571         }
12572
12573       stab = bfd_get_section_by_name (abfd, ".stab");
12574       if (stab != NULL
12575           && (stab->size == 0
12576               || bfd_is_abs_section (stab->output_section)
12577               || stab->sec_info_type != SEC_INFO_TYPE_STABS))
12578         stab = NULL;
12579
12580       if (stab == NULL
12581           && eh == NULL
12582           && bed->elf_backend_discard_info == NULL)
12583         continue;
12584
12585       if (!init_reloc_cookie (&cookie, info, abfd))
12586         return FALSE;
12587
12588       if (stab != NULL
12589           && stab->reloc_count > 0
12590           && init_reloc_cookie_rels (&cookie, info, abfd, stab))
12591         {
12592           if (_bfd_discard_section_stabs (abfd, stab,
12593                                           elf_section_data (stab)->sec_info,
12594                                           bfd_elf_reloc_symbol_deleted_p,
12595                                           &cookie))
12596             ret = TRUE;
12597           fini_reloc_cookie_rels (&cookie, stab);
12598         }
12599
12600       while (eh != NULL
12601              && init_reloc_cookie_rels (&cookie, info, abfd, eh))
12602         {
12603           _bfd_elf_parse_eh_frame (abfd, info, eh, &cookie);
12604           if (_bfd_elf_discard_section_eh_frame (abfd, info, eh,
12605                                                  bfd_elf_reloc_symbol_deleted_p,
12606                                                  &cookie))
12607             ret = TRUE;
12608           fini_reloc_cookie_rels (&cookie, eh);
12609           eh = bfd_get_next_section_by_name (eh);
12610         }
12611
12612       if (bed->elf_backend_discard_info != NULL
12613           && (*bed->elf_backend_discard_info) (abfd, &cookie, info))
12614         ret = TRUE;
12615
12616       fini_reloc_cookie (&cookie, abfd);
12617     }
12618   _bfd_elf_end_eh_frame_parsing (info);
12619
12620   if (info->eh_frame_hdr
12621       && !info->relocatable
12622       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
12623     ret = TRUE;
12624
12625   return ret;
12626 }
12627
12628 bfd_boolean
12629 _bfd_elf_section_already_linked (bfd *abfd,
12630                                  asection *sec,
12631                                  struct bfd_link_info *info)
12632 {
12633   flagword flags;
12634   const char *name, *key;
12635   struct bfd_section_already_linked *l;
12636   struct bfd_section_already_linked_hash_entry *already_linked_list;
12637
12638   if (sec->output_section == bfd_abs_section_ptr)
12639     return FALSE;
12640
12641   flags = sec->flags;
12642
12643   /* Return if it isn't a linkonce section.  A comdat group section
12644      also has SEC_LINK_ONCE set.  */
12645   if ((flags & SEC_LINK_ONCE) == 0)
12646     return FALSE;
12647
12648   /* Don't put group member sections on our list of already linked
12649      sections.  They are handled as a group via their group section.  */
12650   if (elf_sec_group (sec) != NULL)
12651     return FALSE;
12652
12653   /* For a SHT_GROUP section, use the group signature as the key.  */
12654   name = sec->name;
12655   if ((flags & SEC_GROUP) != 0
12656       && elf_next_in_group (sec) != NULL
12657       && elf_group_name (elf_next_in_group (sec)) != NULL)
12658     key = elf_group_name (elf_next_in_group (sec));
12659   else
12660     {
12661       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
12662       if (CONST_STRNEQ (name, ".gnu.linkonce.")
12663           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
12664         key++;
12665       else
12666         /* Must be a user linkonce section that doesn't follow gcc's
12667            naming convention.  In this case we won't be matching
12668            single member groups.  */
12669         key = name;
12670     }
12671
12672   already_linked_list = bfd_section_already_linked_table_lookup (key);
12673
12674   for (l = already_linked_list->entry; l != NULL; l = l->next)
12675     {
12676       /* We may have 2 different types of sections on the list: group
12677          sections with a signature of <key> (<key> is some string),
12678          and linkonce sections named .gnu.linkonce.<type>.<key>.
12679          Match like sections.  LTO plugin sections are an exception.
12680          They are always named .gnu.linkonce.t.<key> and match either
12681          type of section.  */
12682       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
12683            && ((flags & SEC_GROUP) != 0
12684                || strcmp (name, l->sec->name) == 0))
12685           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
12686         {
12687           /* The section has already been linked.  See if we should
12688              issue a warning.  */
12689           if (!_bfd_handle_already_linked (sec, l, info))
12690             return FALSE;
12691
12692           if (flags & SEC_GROUP)
12693             {
12694               asection *first = elf_next_in_group (sec);
12695               asection *s = first;
12696
12697               while (s != NULL)
12698                 {
12699                   s->output_section = bfd_abs_section_ptr;
12700                   /* Record which group discards it.  */
12701                   s->kept_section = l->sec;
12702                   s = elf_next_in_group (s);
12703                   /* These lists are circular.  */
12704                   if (s == first)
12705                     break;
12706                 }
12707             }
12708
12709           return TRUE;
12710         }
12711     }
12712
12713   /* A single member comdat group section may be discarded by a
12714      linkonce section and vice versa.  */
12715   if ((flags & SEC_GROUP) != 0)
12716     {
12717       asection *first = elf_next_in_group (sec);
12718
12719       if (first != NULL && elf_next_in_group (first) == first)
12720         /* Check this single member group against linkonce sections.  */
12721         for (l = already_linked_list->entry; l != NULL; l = l->next)
12722           if ((l->sec->flags & SEC_GROUP) == 0
12723               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
12724             {
12725               first->output_section = bfd_abs_section_ptr;
12726               first->kept_section = l->sec;
12727               sec->output_section = bfd_abs_section_ptr;
12728               break;
12729             }
12730     }
12731   else
12732     /* Check this linkonce section against single member groups.  */
12733     for (l = already_linked_list->entry; l != NULL; l = l->next)
12734       if (l->sec->flags & SEC_GROUP)
12735         {
12736           asection *first = elf_next_in_group (l->sec);
12737
12738           if (first != NULL
12739               && elf_next_in_group (first) == first
12740               && bfd_elf_match_symbols_in_sections (first, sec, info))
12741             {
12742               sec->output_section = bfd_abs_section_ptr;
12743               sec->kept_section = first;
12744               break;
12745             }
12746         }
12747
12748   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
12749      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
12750      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
12751      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
12752      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
12753      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
12754      `.gnu.linkonce.t.F' section from a different bfd not requiring any
12755      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
12756      The reverse order cannot happen as there is never a bfd with only the
12757      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
12758      matter as here were are looking only for cross-bfd sections.  */
12759
12760   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
12761     for (l = already_linked_list->entry; l != NULL; l = l->next)
12762       if ((l->sec->flags & SEC_GROUP) == 0
12763           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
12764         {
12765           if (abfd != l->sec->owner)
12766             sec->output_section = bfd_abs_section_ptr;
12767           break;
12768         }
12769
12770   /* This is the first section with this name.  Record it.  */
12771   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
12772     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
12773   return sec->output_section == bfd_abs_section_ptr;
12774 }
12775
12776 bfd_boolean
12777 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
12778 {
12779   return sym->st_shndx == SHN_COMMON;
12780 }
12781
12782 unsigned int
12783 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
12784 {
12785   return SHN_COMMON;
12786 }
12787
12788 asection *
12789 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
12790 {
12791   return bfd_com_section_ptr;
12792 }
12793
12794 bfd_vma
12795 _bfd_elf_default_got_elt_size (bfd *abfd,
12796                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
12797                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
12798                                bfd *ibfd ATTRIBUTE_UNUSED,
12799                                unsigned long symndx ATTRIBUTE_UNUSED)
12800 {
12801   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12802   return bed->s->arch_size / 8;
12803 }
12804
12805 /* Routines to support the creation of dynamic relocs.  */
12806
12807 /* Returns the name of the dynamic reloc section associated with SEC.  */
12808
12809 static const char *
12810 get_dynamic_reloc_section_name (bfd *       abfd,
12811                                 asection *  sec,
12812                                 bfd_boolean is_rela)
12813 {
12814   char *name;
12815   const char *old_name = bfd_get_section_name (NULL, sec);
12816   const char *prefix = is_rela ? ".rela" : ".rel";
12817
12818   if (old_name == NULL)
12819     return NULL;
12820
12821   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
12822   sprintf (name, "%s%s", prefix, old_name); 
12823
12824   return name;
12825 }
12826
12827 /* Returns the dynamic reloc section associated with SEC.
12828    If necessary compute the name of the dynamic reloc section based
12829    on SEC's name (looked up in ABFD's string table) and the setting
12830    of IS_RELA.  */
12831
12832 asection *
12833 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
12834                                     asection *  sec,
12835                                     bfd_boolean is_rela)
12836 {
12837   asection * reloc_sec = elf_section_data (sec)->sreloc;
12838
12839   if (reloc_sec == NULL)
12840     {
12841       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
12842
12843       if (name != NULL)
12844         {
12845           reloc_sec = bfd_get_section_by_name (abfd, name);
12846
12847           if (reloc_sec != NULL)
12848             elf_section_data (sec)->sreloc = reloc_sec;
12849         }
12850     }
12851
12852   return reloc_sec;
12853 }
12854
12855 /* Returns the dynamic reloc section associated with SEC.  If the
12856    section does not exist it is created and attached to the DYNOBJ
12857    bfd and stored in the SRELOC field of SEC's elf_section_data
12858    structure.
12859
12860    ALIGNMENT is the alignment for the newly created section and
12861    IS_RELA defines whether the name should be .rela.<SEC's name>
12862    or .rel.<SEC's name>.  The section name is looked up in the
12863    string table associated with ABFD.  */
12864
12865 asection *
12866 _bfd_elf_make_dynamic_reloc_section (asection *         sec,
12867                                      bfd *              dynobj,
12868                                      unsigned int       alignment,
12869                                      bfd *              abfd,
12870                                      bfd_boolean        is_rela)
12871 {
12872   asection * reloc_sec = elf_section_data (sec)->sreloc;
12873
12874   if (reloc_sec == NULL)
12875     {
12876       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
12877
12878       if (name == NULL)
12879         return NULL;
12880
12881       reloc_sec = bfd_get_section_by_name (dynobj, name);
12882
12883       if (reloc_sec == NULL)
12884         {
12885           flagword flags;
12886
12887           flags = (SEC_HAS_CONTENTS | SEC_READONLY | SEC_IN_MEMORY | SEC_LINKER_CREATED);
12888           if ((sec->flags & SEC_ALLOC) != 0)
12889             flags |= SEC_ALLOC | SEC_LOAD;
12890
12891           reloc_sec = bfd_make_section_with_flags (dynobj, name, flags);
12892           if (reloc_sec != NULL)
12893             {
12894               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
12895                 reloc_sec = NULL;
12896             }
12897         }
12898
12899       elf_section_data (sec)->sreloc = reloc_sec;
12900     }
12901
12902   return reloc_sec;
12903 }
12904
12905 /* Copy the ELF symbol type associated with a linker hash entry.  */
12906 void
12907 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd ATTRIBUTE_UNUSED,
12908     struct bfd_link_hash_entry * hdest,
12909     struct bfd_link_hash_entry * hsrc)
12910 {
12911   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *)hdest;
12912   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *)hsrc;
12913
12914   ehdest->type = ehsrc->type;
12915   ehdest->target_internal = ehsrc->target_internal;
12916 }
12917
12918 /* Append a RELA relocation REL to section S in BFD.  */
12919
12920 void
12921 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
12922 {
12923   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12924   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
12925   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
12926   bed->s->swap_reloca_out (abfd, rel, loc);
12927 }
12928
12929 /* Append a REL relocation REL to section S in BFD.  */
12930
12931 void
12932 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
12933 {
12934   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12935   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
12936   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
12937   bed->s->swap_reloca_out (abfd, rel, loc);
12938 }