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