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