Assign file position for .strtab only if needed
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2014 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31
32 /* This struct is used to pass information to routines called via
33    elf_link_hash_traverse which must return failure.  */
34
35 struct elf_info_failed
36 {
37   struct bfd_link_info *info;
38   bfd_boolean failed;
39 };
40
41 /* This structure is used to pass information to
42    _bfd_elf_link_find_version_dependencies.  */
43
44 struct elf_find_verdep_info
45 {
46   /* General link information.  */
47   struct bfd_link_info *info;
48   /* The number of dependencies.  */
49   unsigned int vers;
50   /* Whether we had a failure.  */
51   bfd_boolean failed;
52 };
53
54 static bfd_boolean _bfd_elf_fix_symbol_flags
55   (struct elf_link_hash_entry *, struct elf_info_failed *);
56
57 /* Define a symbol in a dynamic linkage section.  */
58
59 struct elf_link_hash_entry *
60 _bfd_elf_define_linkage_sym (bfd *abfd,
61                              struct bfd_link_info *info,
62                              asection *sec,
63                              const char *name)
64 {
65   struct elf_link_hash_entry *h;
66   struct bfd_link_hash_entry *bh;
67   const struct elf_backend_data *bed;
68
69   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
70   if (h != NULL)
71     {
72       /* Zap symbol defined in an as-needed lib that wasn't linked.
73          This is a symptom of a larger problem:  Absolute symbols
74          defined in shared libraries can't be overridden, because we
75          lose the link to the bfd which is via the symbol section.  */
76       h->root.type = bfd_link_hash_new;
77     }
78
79   bh = &h->root;
80   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
81                                          sec, 0, NULL, FALSE,
82                                          get_elf_backend_data (abfd)->collect,
83                                          &bh))
84     return NULL;
85   h = (struct elf_link_hash_entry *) bh;
86   h->def_regular = 1;
87   h->non_elf = 0;
88   h->root.linker_def = 1;
89   h->type = STT_OBJECT;
90   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
91     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
92
93   bed = get_elf_backend_data (abfd);
94   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
95   return h;
96 }
97
98 bfd_boolean
99 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
100 {
101   flagword flags;
102   asection *s;
103   struct elf_link_hash_entry *h;
104   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
105   struct elf_link_hash_table *htab = elf_hash_table (info);
106
107   /* This function may be called more than once.  */
108   s = bfd_get_linker_section (abfd, ".got");
109   if (s != NULL)
110     return TRUE;
111
112   flags = bed->dynamic_sec_flags;
113
114   s = bfd_make_section_anyway_with_flags (abfd,
115                                           (bed->rela_plts_and_copies_p
116                                            ? ".rela.got" : ".rel.got"),
117                                           (bed->dynamic_sec_flags
118                                            | SEC_READONLY));
119   if (s == NULL
120       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
121     return FALSE;
122   htab->srelgot = s;
123
124   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
125   if (s == NULL
126       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
127     return FALSE;
128   htab->sgot = s;
129
130   if (bed->want_got_plt)
131     {
132       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
133       if (s == NULL
134           || !bfd_set_section_alignment (abfd, s,
135                                          bed->s->log_file_align))
136         return FALSE;
137       htab->sgotplt = s;
138     }
139
140   /* The first bit of the global offset table is the header.  */
141   s->size += bed->got_header_size;
142
143   if (bed->want_got_sym)
144     {
145       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
146          (or .got.plt) section.  We don't do this in the linker script
147          because we don't want to define the symbol if we are not creating
148          a global offset table.  */
149       h = _bfd_elf_define_linkage_sym (abfd, info, s,
150                                        "_GLOBAL_OFFSET_TABLE_");
151       elf_hash_table (info)->hgot = h;
152       if (h == NULL)
153         return FALSE;
154     }
155
156   return TRUE;
157 }
158 \f
159 /* Create a strtab to hold the dynamic symbol names.  */
160 static bfd_boolean
161 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
162 {
163   struct elf_link_hash_table *hash_table;
164
165   hash_table = elf_hash_table (info);
166   if (hash_table->dynobj == NULL)
167     hash_table->dynobj = abfd;
168
169   if (hash_table->dynstr == NULL)
170     {
171       hash_table->dynstr = _bfd_elf_strtab_init ();
172       if (hash_table->dynstr == NULL)
173         return FALSE;
174     }
175   return TRUE;
176 }
177
178 /* Create some sections which will be filled in with dynamic linking
179    information.  ABFD is an input file which requires dynamic sections
180    to be created.  The dynamic sections take up virtual memory space
181    when the final executable is run, so we need to create them before
182    addresses are assigned to the output sections.  We work out the
183    actual contents and size of these sections later.  */
184
185 bfd_boolean
186 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
187 {
188   flagword flags;
189   asection *s;
190   const struct elf_backend_data *bed;
191   struct elf_link_hash_entry *h;
192
193   if (! is_elf_hash_table (info->hash))
194     return FALSE;
195
196   if (elf_hash_table (info)->dynamic_sections_created)
197     return TRUE;
198
199   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
200     return FALSE;
201
202   abfd = elf_hash_table (info)->dynobj;
203   bed = get_elf_backend_data (abfd);
204
205   flags = bed->dynamic_sec_flags;
206
207   /* A dynamically linked executable has a .interp section, but a
208      shared library does not.  */
209   if (info->executable)
210     {
211       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
212                                               flags | SEC_READONLY);
213       if (s == NULL)
214         return FALSE;
215     }
216
217   /* Create sections to hold version informations.  These are removed
218      if they are not needed.  */
219   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
220                                           flags | SEC_READONLY);
221   if (s == NULL
222       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
223     return FALSE;
224
225   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
226                                           flags | SEC_READONLY);
227   if (s == NULL
228       || ! bfd_set_section_alignment (abfd, s, 1))
229     return FALSE;
230
231   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
232                                           flags | SEC_READONLY);
233   if (s == NULL
234       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
235     return FALSE;
236
237   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
238                                           flags | SEC_READONLY);
239   if (s == NULL
240       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
241     return FALSE;
242
243   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
244                                           flags | SEC_READONLY);
245   if (s == NULL)
246     return FALSE;
247
248   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
249   if (s == NULL
250       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
251     return FALSE;
252
253   /* The special symbol _DYNAMIC is always set to the start of the
254      .dynamic section.  We could set _DYNAMIC in a linker script, but we
255      only want to define it if we are, in fact, creating a .dynamic
256      section.  We don't want to define it if there is no .dynamic
257      section, since on some ELF platforms the start up code examines it
258      to decide how to initialize the process.  */
259   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
260   elf_hash_table (info)->hdynamic = h;
261   if (h == NULL)
262     return FALSE;
263
264   if (info->emit_hash)
265     {
266       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
267                                               flags | SEC_READONLY);
268       if (s == NULL
269           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
270         return FALSE;
271       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
272     }
273
274   if (info->emit_gnu_hash)
275     {
276       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
277                                               flags | SEC_READONLY);
278       if (s == NULL
279           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
280         return FALSE;
281       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
282          4 32-bit words followed by variable count of 64-bit words, then
283          variable count of 32-bit words.  */
284       if (bed->s->arch_size == 64)
285         elf_section_data (s)->this_hdr.sh_entsize = 0;
286       else
287         elf_section_data (s)->this_hdr.sh_entsize = 4;
288     }
289
290   /* Let the backend create the rest of the sections.  This lets the
291      backend set the right flags.  The backend will normally create
292      the .got and .plt sections.  */
293   if (bed->elf_backend_create_dynamic_sections == NULL
294       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
295     return FALSE;
296
297   elf_hash_table (info)->dynamic_sections_created = TRUE;
298
299   return TRUE;
300 }
301
302 /* Create dynamic sections when linking against a dynamic object.  */
303
304 bfd_boolean
305 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
306 {
307   flagword flags, pltflags;
308   struct elf_link_hash_entry *h;
309   asection *s;
310   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
311   struct elf_link_hash_table *htab = elf_hash_table (info);
312
313   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
314      .rel[a].bss sections.  */
315   flags = bed->dynamic_sec_flags;
316
317   pltflags = flags;
318   if (bed->plt_not_loaded)
319     /* We do not clear SEC_ALLOC here because we still want the OS to
320        allocate space for the section; it's just that there's nothing
321        to read in from the object file.  */
322     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
323   else
324     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
325   if (bed->plt_readonly)
326     pltflags |= SEC_READONLY;
327
328   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
329   if (s == NULL
330       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
331     return FALSE;
332   htab->splt = s;
333
334   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
335      .plt section.  */
336   if (bed->want_plt_sym)
337     {
338       h = _bfd_elf_define_linkage_sym (abfd, info, s,
339                                        "_PROCEDURE_LINKAGE_TABLE_");
340       elf_hash_table (info)->hplt = h;
341       if (h == NULL)
342         return FALSE;
343     }
344
345   s = bfd_make_section_anyway_with_flags (abfd,
346                                           (bed->rela_plts_and_copies_p
347                                            ? ".rela.plt" : ".rel.plt"),
348                                           flags | SEC_READONLY);
349   if (s == NULL
350       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
351     return FALSE;
352   htab->srelplt = s;
353
354   if (! _bfd_elf_create_got_section (abfd, info))
355     return FALSE;
356
357   if (bed->want_dynbss)
358     {
359       /* The .dynbss section is a place to put symbols which are defined
360          by dynamic objects, are referenced by regular objects, and are
361          not functions.  We must allocate space for them in the process
362          image and use a R_*_COPY reloc to tell the dynamic linker to
363          initialize them at run time.  The linker script puts the .dynbss
364          section into the .bss section of the final image.  */
365       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
366                                               (SEC_ALLOC | SEC_LINKER_CREATED));
367       if (s == NULL)
368         return FALSE;
369
370       /* The .rel[a].bss section holds copy relocs.  This section is not
371          normally needed.  We need to create it here, though, so that the
372          linker will map it to an output section.  We can't just create it
373          only if we need it, because we will not know whether we need it
374          until we have seen all the input files, and the first time the
375          main linker code calls BFD after examining all the input files
376          (size_dynamic_sections) the input sections have already been
377          mapped to the output sections.  If the section turns out not to
378          be needed, we can discard it later.  We will never need this
379          section when generating a shared object, since they do not use
380          copy relocs.  */
381       if (! info->shared)
382         {
383           s = bfd_make_section_anyway_with_flags (abfd,
384                                                   (bed->rela_plts_and_copies_p
385                                                    ? ".rela.bss" : ".rel.bss"),
386                                                   flags | SEC_READONLY);
387           if (s == NULL
388               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
389             return FALSE;
390         }
391     }
392
393   return TRUE;
394 }
395 \f
396 /* Record a new dynamic symbol.  We record the dynamic symbols as we
397    read the input files, since we need to have a list of all of them
398    before we can determine the final sizes of the output sections.
399    Note that we may actually call this function even though we are not
400    going to output any dynamic symbols; in some cases we know that a
401    symbol should be in the dynamic symbol table, but only if there is
402    one.  */
403
404 bfd_boolean
405 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
406                                     struct elf_link_hash_entry *h)
407 {
408   if (h->dynindx == -1)
409     {
410       struct elf_strtab_hash *dynstr;
411       char *p;
412       const char *name;
413       bfd_size_type indx;
414
415       /* XXX: The ABI draft says the linker must turn hidden and
416          internal symbols into STB_LOCAL symbols when producing the
417          DSO. However, if ld.so honors st_other in the dynamic table,
418          this would not be necessary.  */
419       switch (ELF_ST_VISIBILITY (h->other))
420         {
421         case STV_INTERNAL:
422         case STV_HIDDEN:
423           if (h->root.type != bfd_link_hash_undefined
424               && h->root.type != bfd_link_hash_undefweak)
425             {
426               h->forced_local = 1;
427               if (!elf_hash_table (info)->is_relocatable_executable)
428                 return TRUE;
429             }
430
431         default:
432           break;
433         }
434
435       h->dynindx = elf_hash_table (info)->dynsymcount;
436       ++elf_hash_table (info)->dynsymcount;
437
438       dynstr = elf_hash_table (info)->dynstr;
439       if (dynstr == NULL)
440         {
441           /* Create a strtab to hold the dynamic symbol names.  */
442           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
443           if (dynstr == NULL)
444             return FALSE;
445         }
446
447       /* We don't put any version information in the dynamic string
448          table.  */
449       name = h->root.root.string;
450       p = strchr (name, ELF_VER_CHR);
451       if (p != NULL)
452         /* We know that the p points into writable memory.  In fact,
453            there are only a few symbols that have read-only names, being
454            those like _GLOBAL_OFFSET_TABLE_ that are created specially
455            by the backends.  Most symbols will have names pointing into
456            an ELF string table read from a file, or to objalloc memory.  */
457         *p = 0;
458
459       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
460
461       if (p != NULL)
462         *p = ELF_VER_CHR;
463
464       if (indx == (bfd_size_type) -1)
465         return FALSE;
466       h->dynstr_index = indx;
467     }
468
469   return TRUE;
470 }
471 \f
472 /* Mark a symbol dynamic.  */
473
474 static void
475 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
476                                   struct elf_link_hash_entry *h,
477                                   Elf_Internal_Sym *sym)
478 {
479   struct bfd_elf_dynamic_list *d = info->dynamic_list;
480
481   /* It may be called more than once on the same H.  */
482   if(h->dynamic || info->relocatable)
483     return;
484
485   if ((info->dynamic_data
486        && (h->type == STT_OBJECT
487            || (sym != NULL
488                && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
489       || (d != NULL
490           && h->root.type == bfd_link_hash_new
491           && (*d->match) (&d->head, NULL, h->root.root.string)))
492     h->dynamic = 1;
493 }
494
495 /* Record an assignment to a symbol made by a linker script.  We need
496    this in case some dynamic object refers to this symbol.  */
497
498 bfd_boolean
499 bfd_elf_record_link_assignment (bfd *output_bfd,
500                                 struct bfd_link_info *info,
501                                 const char *name,
502                                 bfd_boolean provide,
503                                 bfd_boolean hidden)
504 {
505   struct elf_link_hash_entry *h, *hv;
506   struct elf_link_hash_table *htab;
507   const struct elf_backend_data *bed;
508
509   if (!is_elf_hash_table (info->hash))
510     return TRUE;
511
512   htab = elf_hash_table (info);
513   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
514   if (h == NULL)
515     return provide;
516
517   switch (h->root.type)
518     {
519     case bfd_link_hash_defined:
520     case bfd_link_hash_defweak:
521     case bfd_link_hash_common:
522       break;
523     case bfd_link_hash_undefweak:
524     case bfd_link_hash_undefined:
525       /* Since we're defining the symbol, don't let it seem to have not
526          been defined.  record_dynamic_symbol and size_dynamic_sections
527          may depend on this.  */
528       h->root.type = bfd_link_hash_new;
529       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
530         bfd_link_repair_undef_list (&htab->root);
531       break;
532     case bfd_link_hash_new:
533       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
534       h->non_elf = 0;
535       break;
536     case bfd_link_hash_indirect:
537       /* We had a versioned symbol in a dynamic library.  We make the
538          the versioned symbol point to this one.  */
539       bed = get_elf_backend_data (output_bfd);
540       hv = h;
541       while (hv->root.type == bfd_link_hash_indirect
542              || hv->root.type == bfd_link_hash_warning)
543         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
544       /* We don't need to update h->root.u since linker will set them
545          later.  */
546       h->root.type = bfd_link_hash_undefined;
547       hv->root.type = bfd_link_hash_indirect;
548       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
549       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
550       break;
551     case bfd_link_hash_warning:
552       abort ();
553       break;
554     }
555
556   /* If this symbol is being provided by the linker script, and it is
557      currently defined by a dynamic object, but not by a regular
558      object, then mark it as undefined so that the generic linker will
559      force the correct value.  */
560   if (provide
561       && h->def_dynamic
562       && !h->def_regular)
563     h->root.type = bfd_link_hash_undefined;
564
565   /* If this symbol is not being provided by the linker script, and it is
566      currently defined by a dynamic object, but not by a regular object,
567      then clear out any version information because the symbol will not be
568      associated with the dynamic object any more.  */
569   if (!provide
570       && h->def_dynamic
571       && !h->def_regular)
572     h->verinfo.verdef = NULL;
573
574   h->def_regular = 1;
575
576   if (hidden)
577     {
578       bed = get_elf_backend_data (output_bfd);
579       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
580         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
581       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
582     }
583
584   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
585      and executables.  */
586   if (!info->relocatable
587       && h->dynindx != -1
588       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
589           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
590     h->forced_local = 1;
591
592   if ((h->def_dynamic
593        || h->ref_dynamic
594        || info->shared
595        || (info->executable && elf_hash_table (info)->is_relocatable_executable))
596       && h->dynindx == -1)
597     {
598       if (! bfd_elf_link_record_dynamic_symbol (info, h))
599         return FALSE;
600
601       /* If this is a weak defined symbol, and we know a corresponding
602          real symbol from the same dynamic object, make sure the real
603          symbol is also made into a dynamic symbol.  */
604       if (h->u.weakdef != NULL
605           && h->u.weakdef->dynindx == -1)
606         {
607           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
608             return FALSE;
609         }
610     }
611
612   return TRUE;
613 }
614
615 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
616    success, and 2 on a failure caused by attempting to record a symbol
617    in a discarded section, eg. a discarded link-once section symbol.  */
618
619 int
620 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
621                                           bfd *input_bfd,
622                                           long input_indx)
623 {
624   bfd_size_type amt;
625   struct elf_link_local_dynamic_entry *entry;
626   struct elf_link_hash_table *eht;
627   struct elf_strtab_hash *dynstr;
628   unsigned long dynstr_index;
629   char *name;
630   Elf_External_Sym_Shndx eshndx;
631   char esym[sizeof (Elf64_External_Sym)];
632
633   if (! is_elf_hash_table (info->hash))
634     return 0;
635
636   /* See if the entry exists already.  */
637   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
638     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
639       return 1;
640
641   amt = sizeof (*entry);
642   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
643   if (entry == NULL)
644     return 0;
645
646   /* Go find the symbol, so that we can find it's name.  */
647   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
648                              1, input_indx, &entry->isym, esym, &eshndx))
649     {
650       bfd_release (input_bfd, entry);
651       return 0;
652     }
653
654   if (entry->isym.st_shndx != SHN_UNDEF
655       && entry->isym.st_shndx < SHN_LORESERVE)
656     {
657       asection *s;
658
659       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
660       if (s == NULL || bfd_is_abs_section (s->output_section))
661         {
662           /* We can still bfd_release here as nothing has done another
663              bfd_alloc.  We can't do this later in this function.  */
664           bfd_release (input_bfd, entry);
665           return 2;
666         }
667     }
668
669   name = (bfd_elf_string_from_elf_section
670           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
671            entry->isym.st_name));
672
673   dynstr = elf_hash_table (info)->dynstr;
674   if (dynstr == NULL)
675     {
676       /* Create a strtab to hold the dynamic symbol names.  */
677       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
678       if (dynstr == NULL)
679         return 0;
680     }
681
682   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
683   if (dynstr_index == (unsigned long) -1)
684     return 0;
685   entry->isym.st_name = dynstr_index;
686
687   eht = elf_hash_table (info);
688
689   entry->next = eht->dynlocal;
690   eht->dynlocal = entry;
691   entry->input_bfd = input_bfd;
692   entry->input_indx = input_indx;
693   eht->dynsymcount++;
694
695   /* Whatever binding the symbol had before, it's now local.  */
696   entry->isym.st_info
697     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
698
699   /* The dynindx will be set at the end of size_dynamic_sections.  */
700
701   return 1;
702 }
703
704 /* Return the dynindex of a local dynamic symbol.  */
705
706 long
707 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
708                                     bfd *input_bfd,
709                                     long input_indx)
710 {
711   struct elf_link_local_dynamic_entry *e;
712
713   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
714     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
715       return e->dynindx;
716   return -1;
717 }
718
719 /* This function is used to renumber the dynamic symbols, if some of
720    them are removed because they are marked as local.  This is called
721    via elf_link_hash_traverse.  */
722
723 static bfd_boolean
724 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
725                                       void *data)
726 {
727   size_t *count = (size_t *) data;
728
729   if (h->forced_local)
730     return TRUE;
731
732   if (h->dynindx != -1)
733     h->dynindx = ++(*count);
734
735   return TRUE;
736 }
737
738
739 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
740    STB_LOCAL binding.  */
741
742 static bfd_boolean
743 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
744                                             void *data)
745 {
746   size_t *count = (size_t *) data;
747
748   if (!h->forced_local)
749     return TRUE;
750
751   if (h->dynindx != -1)
752     h->dynindx = ++(*count);
753
754   return TRUE;
755 }
756
757 /* Return true if the dynamic symbol for a given section should be
758    omitted when creating a shared library.  */
759 bfd_boolean
760 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
761                                    struct bfd_link_info *info,
762                                    asection *p)
763 {
764   struct elf_link_hash_table *htab;
765
766   switch (elf_section_data (p)->this_hdr.sh_type)
767     {
768     case SHT_PROGBITS:
769     case SHT_NOBITS:
770       /* If sh_type is yet undecided, assume it could be
771          SHT_PROGBITS/SHT_NOBITS.  */
772     case SHT_NULL:
773       htab = elf_hash_table (info);
774       if (p == htab->tls_sec)
775         return FALSE;
776
777       if (htab->text_index_section != NULL)
778         return p != htab->text_index_section && p != htab->data_index_section;
779
780       if (strcmp (p->name, ".got") == 0
781           || strcmp (p->name, ".got.plt") == 0
782           || strcmp (p->name, ".plt") == 0)
783         {
784           asection *ip;
785
786           if (htab->dynobj != NULL
787               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
788               && ip->output_section == p)
789             return TRUE;
790         }
791       return FALSE;
792
793       /* There shouldn't be section relative relocations
794          against any other section.  */
795     default:
796       return TRUE;
797     }
798 }
799
800 /* Assign dynsym indices.  In a shared library we generate a section
801    symbol for each output section, which come first.  Next come symbols
802    which have been forced to local binding.  Then all of the back-end
803    allocated local dynamic syms, followed by the rest of the global
804    symbols.  */
805
806 static unsigned long
807 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
808                                 struct bfd_link_info *info,
809                                 unsigned long *section_sym_count)
810 {
811   unsigned long dynsymcount = 0;
812
813   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
814     {
815       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
816       asection *p;
817       for (p = output_bfd->sections; p ; p = p->next)
818         if ((p->flags & SEC_EXCLUDE) == 0
819             && (p->flags & SEC_ALLOC) != 0
820             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
821           elf_section_data (p)->dynindx = ++dynsymcount;
822         else
823           elf_section_data (p)->dynindx = 0;
824     }
825   *section_sym_count = dynsymcount;
826
827   elf_link_hash_traverse (elf_hash_table (info),
828                           elf_link_renumber_local_hash_table_dynsyms,
829                           &dynsymcount);
830
831   if (elf_hash_table (info)->dynlocal)
832     {
833       struct elf_link_local_dynamic_entry *p;
834       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
835         p->dynindx = ++dynsymcount;
836     }
837
838   elf_link_hash_traverse (elf_hash_table (info),
839                           elf_link_renumber_hash_table_dynsyms,
840                           &dynsymcount);
841
842   /* There is an unused NULL entry at the head of the table which
843      we must account for in our count.  Unless there weren't any
844      symbols, which means we'll have no table at all.  */
845   if (dynsymcount != 0)
846     ++dynsymcount;
847
848   elf_hash_table (info)->dynsymcount = dynsymcount;
849   return dynsymcount;
850 }
851
852 /* Merge st_other field.  */
853
854 static void
855 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
856                     const Elf_Internal_Sym *isym,
857                     bfd_boolean definition, bfd_boolean dynamic)
858 {
859   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
860
861   /* If st_other has a processor-specific meaning, specific
862      code might be needed here.  */
863   if (bed->elf_backend_merge_symbol_attribute)
864     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
865                                                 dynamic);
866
867   if (!dynamic)
868     {
869       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
870       unsigned hvis = ELF_ST_VISIBILITY (h->other);
871
872       /* Keep the most constraining visibility.  Leave the remainder
873          of the st_other field to elf_backend_merge_symbol_attribute.  */
874       if (symvis - 1 < hvis - 1)
875         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
876     }
877   else if (definition && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT)
878     h->protected_def = 1;
879 }
880
881 /* This function is called when we want to merge a new symbol with an
882    existing symbol.  It handles the various cases which arise when we
883    find a definition in a dynamic object, or when there is already a
884    definition in a dynamic object.  The new symbol is described by
885    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
886    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
887    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
888    of an old common symbol.  We set OVERRIDE if the old symbol is
889    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
890    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
891    to change.  By OK to change, we mean that we shouldn't warn if the
892    type or size does change.  */
893
894 static bfd_boolean
895 _bfd_elf_merge_symbol (bfd *abfd,
896                        struct bfd_link_info *info,
897                        const char *name,
898                        Elf_Internal_Sym *sym,
899                        asection **psec,
900                        bfd_vma *pvalue,
901                        struct elf_link_hash_entry **sym_hash,
902                        bfd **poldbfd,
903                        bfd_boolean *pold_weak,
904                        unsigned int *pold_alignment,
905                        bfd_boolean *skip,
906                        bfd_boolean *override,
907                        bfd_boolean *type_change_ok,
908                        bfd_boolean *size_change_ok)
909 {
910   asection *sec, *oldsec;
911   struct elf_link_hash_entry *h;
912   struct elf_link_hash_entry *hi;
913   struct elf_link_hash_entry *flip;
914   int bind;
915   bfd *oldbfd;
916   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
917   bfd_boolean newweak, oldweak, newfunc, oldfunc;
918   const struct elf_backend_data *bed;
919
920   *skip = FALSE;
921   *override = FALSE;
922
923   sec = *psec;
924   bind = ELF_ST_BIND (sym->st_info);
925
926   if (! bfd_is_und_section (sec))
927     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
928   else
929     h = ((struct elf_link_hash_entry *)
930          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
931   if (h == NULL)
932     return FALSE;
933   *sym_hash = h;
934
935   bed = get_elf_backend_data (abfd);
936
937   /* For merging, we only care about real symbols.  But we need to make
938      sure that indirect symbol dynamic flags are updated.  */
939   hi = h;
940   while (h->root.type == bfd_link_hash_indirect
941          || h->root.type == bfd_link_hash_warning)
942     h = (struct elf_link_hash_entry *) h->root.u.i.link;
943
944   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
945      existing symbol.  */
946
947   oldbfd = NULL;
948   oldsec = NULL;
949   switch (h->root.type)
950     {
951     default:
952       break;
953
954     case bfd_link_hash_undefined:
955     case bfd_link_hash_undefweak:
956       oldbfd = h->root.u.undef.abfd;
957       break;
958
959     case bfd_link_hash_defined:
960     case bfd_link_hash_defweak:
961       oldbfd = h->root.u.def.section->owner;
962       oldsec = h->root.u.def.section;
963       break;
964
965     case bfd_link_hash_common:
966       oldbfd = h->root.u.c.p->section->owner;
967       oldsec = h->root.u.c.p->section;
968       if (pold_alignment)
969         *pold_alignment = h->root.u.c.p->alignment_power;
970       break;
971     }
972   if (poldbfd && *poldbfd == NULL)
973     *poldbfd = oldbfd;
974
975   /* Differentiate strong and weak symbols.  */
976   newweak = bind == STB_WEAK;
977   oldweak = (h->root.type == bfd_link_hash_defweak
978              || h->root.type == bfd_link_hash_undefweak);
979   if (pold_weak)
980     *pold_weak = oldweak;
981
982   /* This code is for coping with dynamic objects, and is only useful
983      if we are doing an ELF link.  */
984   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
985     return TRUE;
986
987   /* We have to check it for every instance since the first few may be
988      references and not all compilers emit symbol type for undefined
989      symbols.  */
990   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
991
992   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
993      respectively, is from a dynamic object.  */
994
995   newdyn = (abfd->flags & DYNAMIC) != 0;
996
997   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
998      syms and defined syms in dynamic libraries respectively.
999      ref_dynamic on the other hand can be set for a symbol defined in
1000      a dynamic library, and def_dynamic may not be set;  When the
1001      definition in a dynamic lib is overridden by a definition in the
1002      executable use of the symbol in the dynamic lib becomes a
1003      reference to the executable symbol.  */
1004   if (newdyn)
1005     {
1006       if (bfd_is_und_section (sec))
1007         {
1008           if (bind != STB_WEAK)
1009             {
1010               h->ref_dynamic_nonweak = 1;
1011               hi->ref_dynamic_nonweak = 1;
1012             }
1013         }
1014       else
1015         {
1016           h->dynamic_def = 1;
1017           hi->dynamic_def = 1;
1018         }
1019     }
1020
1021   /* If we just created the symbol, mark it as being an ELF symbol.
1022      Other than that, there is nothing to do--there is no merge issue
1023      with a newly defined symbol--so we just return.  */
1024
1025   if (h->root.type == bfd_link_hash_new)
1026     {
1027       h->non_elf = 0;
1028       return TRUE;
1029     }
1030
1031   /* In cases involving weak versioned symbols, we may wind up trying
1032      to merge a symbol with itself.  Catch that here, to avoid the
1033      confusion that results if we try to override a symbol with
1034      itself.  The additional tests catch cases like
1035      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1036      dynamic object, which we do want to handle here.  */
1037   if (abfd == oldbfd
1038       && (newweak || oldweak)
1039       && ((abfd->flags & DYNAMIC) == 0
1040           || !h->def_regular))
1041     return TRUE;
1042
1043   olddyn = FALSE;
1044   if (oldbfd != NULL)
1045     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1046   else if (oldsec != NULL)
1047     {
1048       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1049          indices used by MIPS ELF.  */
1050       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1051     }
1052
1053   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1054      respectively, appear to be a definition rather than reference.  */
1055
1056   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1057
1058   olddef = (h->root.type != bfd_link_hash_undefined
1059             && h->root.type != bfd_link_hash_undefweak
1060             && h->root.type != bfd_link_hash_common);
1061
1062   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1063      respectively, appear to be a function.  */
1064
1065   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1066              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1067
1068   oldfunc = (h->type != STT_NOTYPE
1069              && bed->is_function_type (h->type));
1070
1071   /* When we try to create a default indirect symbol from the dynamic
1072      definition with the default version, we skip it if its type and
1073      the type of existing regular definition mismatch.  */
1074   if (pold_alignment == NULL
1075       && newdyn
1076       && newdef
1077       && !olddyn
1078       && (((olddef || h->root.type == bfd_link_hash_common)
1079            && ELF_ST_TYPE (sym->st_info) != h->type
1080            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1081            && h->type != STT_NOTYPE
1082            && !(newfunc && oldfunc))
1083           || (olddef
1084               && ((h->type == STT_GNU_IFUNC)
1085                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1086     {
1087       *skip = TRUE;
1088       return TRUE;
1089     }
1090
1091   /* Check TLS symbols.  We don't check undefined symbols introduced
1092      by "ld -u" which have no type (and oldbfd NULL), and we don't
1093      check symbols from plugins because they also have no type.  */
1094   if (oldbfd != NULL
1095       && (oldbfd->flags & BFD_PLUGIN) == 0
1096       && (abfd->flags & BFD_PLUGIN) == 0
1097       && ELF_ST_TYPE (sym->st_info) != h->type
1098       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1099     {
1100       bfd *ntbfd, *tbfd;
1101       bfd_boolean ntdef, tdef;
1102       asection *ntsec, *tsec;
1103
1104       if (h->type == STT_TLS)
1105         {
1106           ntbfd = abfd;
1107           ntsec = sec;
1108           ntdef = newdef;
1109           tbfd = oldbfd;
1110           tsec = oldsec;
1111           tdef = olddef;
1112         }
1113       else
1114         {
1115           ntbfd = oldbfd;
1116           ntsec = oldsec;
1117           ntdef = olddef;
1118           tbfd = abfd;
1119           tsec = sec;
1120           tdef = newdef;
1121         }
1122
1123       if (tdef && ntdef)
1124         (*_bfd_error_handler)
1125           (_("%s: TLS definition in %B section %A "
1126              "mismatches non-TLS definition in %B section %A"),
1127            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1128       else if (!tdef && !ntdef)
1129         (*_bfd_error_handler)
1130           (_("%s: TLS reference in %B "
1131              "mismatches non-TLS reference in %B"),
1132            tbfd, ntbfd, h->root.root.string);
1133       else if (tdef)
1134         (*_bfd_error_handler)
1135           (_("%s: TLS definition in %B section %A "
1136              "mismatches non-TLS reference in %B"),
1137            tbfd, tsec, ntbfd, h->root.root.string);
1138       else
1139         (*_bfd_error_handler)
1140           (_("%s: TLS reference in %B "
1141              "mismatches non-TLS definition in %B section %A"),
1142            tbfd, ntbfd, ntsec, h->root.root.string);
1143
1144       bfd_set_error (bfd_error_bad_value);
1145       return FALSE;
1146     }
1147
1148   /* If the old symbol has non-default visibility, we ignore the new
1149      definition from a dynamic object.  */
1150   if (newdyn
1151       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1152       && !bfd_is_und_section (sec))
1153     {
1154       *skip = TRUE;
1155       /* Make sure this symbol is dynamic.  */
1156       h->ref_dynamic = 1;
1157       hi->ref_dynamic = 1;
1158       /* A protected symbol has external availability. Make sure it is
1159          recorded as dynamic.
1160
1161          FIXME: Should we check type and size for protected symbol?  */
1162       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1163         return bfd_elf_link_record_dynamic_symbol (info, h);
1164       else
1165         return TRUE;
1166     }
1167   else if (!newdyn
1168            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1169            && h->def_dynamic)
1170     {
1171       /* If the new symbol with non-default visibility comes from a
1172          relocatable file and the old definition comes from a dynamic
1173          object, we remove the old definition.  */
1174       if (hi->root.type == bfd_link_hash_indirect)
1175         {
1176           /* Handle the case where the old dynamic definition is
1177              default versioned.  We need to copy the symbol info from
1178              the symbol with default version to the normal one if it
1179              was referenced before.  */
1180           if (h->ref_regular)
1181             {
1182               hi->root.type = h->root.type;
1183               h->root.type = bfd_link_hash_indirect;
1184               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1185
1186               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1187               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1188                 {
1189                   /* If the new symbol is hidden or internal, completely undo
1190                      any dynamic link state.  */
1191                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1192                   h->forced_local = 0;
1193                   h->ref_dynamic = 0;
1194                 }
1195               else
1196                 h->ref_dynamic = 1;
1197
1198               h->def_dynamic = 0;
1199               /* FIXME: Should we check type and size for protected symbol?  */
1200               h->size = 0;
1201               h->type = 0;
1202
1203               h = hi;
1204             }
1205           else
1206             h = hi;
1207         }
1208
1209       /* If the old symbol was undefined before, then it will still be
1210          on the undefs list.  If the new symbol is undefined or
1211          common, we can't make it bfd_link_hash_new here, because new
1212          undefined or common symbols will be added to the undefs list
1213          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1214          added twice to the undefs list.  Also, if the new symbol is
1215          undefweak then we don't want to lose the strong undef.  */
1216       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1217         {
1218           h->root.type = bfd_link_hash_undefined;
1219           h->root.u.undef.abfd = abfd;
1220         }
1221       else
1222         {
1223           h->root.type = bfd_link_hash_new;
1224           h->root.u.undef.abfd = NULL;
1225         }
1226
1227       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1228         {
1229           /* If the new symbol is hidden or internal, completely undo
1230              any dynamic link state.  */
1231           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1232           h->forced_local = 0;
1233           h->ref_dynamic = 0;
1234         }
1235       else
1236         h->ref_dynamic = 1;
1237       h->def_dynamic = 0;
1238       /* FIXME: Should we check type and size for protected symbol?  */
1239       h->size = 0;
1240       h->type = 0;
1241       return TRUE;
1242     }
1243
1244   /* If a new weak symbol definition comes from a regular file and the
1245      old symbol comes from a dynamic library, we treat the new one as
1246      strong.  Similarly, an old weak symbol definition from a regular
1247      file is treated as strong when the new symbol comes from a dynamic
1248      library.  Further, an old weak symbol from a dynamic library is
1249      treated as strong if the new symbol is from a dynamic library.
1250      This reflects the way glibc's ld.so works.
1251
1252      Do this before setting *type_change_ok or *size_change_ok so that
1253      we warn properly when dynamic library symbols are overridden.  */
1254
1255   if (newdef && !newdyn && olddyn)
1256     newweak = FALSE;
1257   if (olddef && newdyn)
1258     oldweak = FALSE;
1259
1260   /* Allow changes between different types of function symbol.  */
1261   if (newfunc && oldfunc)
1262     *type_change_ok = TRUE;
1263
1264   /* It's OK to change the type if either the existing symbol or the
1265      new symbol is weak.  A type change is also OK if the old symbol
1266      is undefined and the new symbol is defined.  */
1267
1268   if (oldweak
1269       || newweak
1270       || (newdef
1271           && h->root.type == bfd_link_hash_undefined))
1272     *type_change_ok = TRUE;
1273
1274   /* It's OK to change the size if either the existing symbol or the
1275      new symbol is weak, or if the old symbol is undefined.  */
1276
1277   if (*type_change_ok
1278       || h->root.type == bfd_link_hash_undefined)
1279     *size_change_ok = TRUE;
1280
1281   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1282      symbol, respectively, appears to be a common symbol in a dynamic
1283      object.  If a symbol appears in an uninitialized section, and is
1284      not weak, and is not a function, then it may be a common symbol
1285      which was resolved when the dynamic object was created.  We want
1286      to treat such symbols specially, because they raise special
1287      considerations when setting the symbol size: if the symbol
1288      appears as a common symbol in a regular object, and the size in
1289      the regular object is larger, we must make sure that we use the
1290      larger size.  This problematic case can always be avoided in C,
1291      but it must be handled correctly when using Fortran shared
1292      libraries.
1293
1294      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1295      likewise for OLDDYNCOMMON and OLDDEF.
1296
1297      Note that this test is just a heuristic, and that it is quite
1298      possible to have an uninitialized symbol in a shared object which
1299      is really a definition, rather than a common symbol.  This could
1300      lead to some minor confusion when the symbol really is a common
1301      symbol in some regular object.  However, I think it will be
1302      harmless.  */
1303
1304   if (newdyn
1305       && newdef
1306       && !newweak
1307       && (sec->flags & SEC_ALLOC) != 0
1308       && (sec->flags & SEC_LOAD) == 0
1309       && sym->st_size > 0
1310       && !newfunc)
1311     newdyncommon = TRUE;
1312   else
1313     newdyncommon = FALSE;
1314
1315   if (olddyn
1316       && olddef
1317       && h->root.type == bfd_link_hash_defined
1318       && h->def_dynamic
1319       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1320       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1321       && h->size > 0
1322       && !oldfunc)
1323     olddyncommon = TRUE;
1324   else
1325     olddyncommon = FALSE;
1326
1327   /* We now know everything about the old and new symbols.  We ask the
1328      backend to check if we can merge them.  */
1329   if (bed->merge_symbol != NULL)
1330     {
1331       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1332         return FALSE;
1333       sec = *psec;
1334     }
1335
1336   /* If both the old and the new symbols look like common symbols in a
1337      dynamic object, set the size of the symbol to the larger of the
1338      two.  */
1339
1340   if (olddyncommon
1341       && newdyncommon
1342       && sym->st_size != h->size)
1343     {
1344       /* Since we think we have two common symbols, issue a multiple
1345          common warning if desired.  Note that we only warn if the
1346          size is different.  If the size is the same, we simply let
1347          the old symbol override the new one as normally happens with
1348          symbols defined in dynamic objects.  */
1349
1350       if (! ((*info->callbacks->multiple_common)
1351              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1352         return FALSE;
1353
1354       if (sym->st_size > h->size)
1355         h->size = sym->st_size;
1356
1357       *size_change_ok = TRUE;
1358     }
1359
1360   /* If we are looking at a dynamic object, and we have found a
1361      definition, we need to see if the symbol was already defined by
1362      some other object.  If so, we want to use the existing
1363      definition, and we do not want to report a multiple symbol
1364      definition error; we do this by clobbering *PSEC to be
1365      bfd_und_section_ptr.
1366
1367      We treat a common symbol as a definition if the symbol in the
1368      shared library is a function, since common symbols always
1369      represent variables; this can cause confusion in principle, but
1370      any such confusion would seem to indicate an erroneous program or
1371      shared library.  We also permit a common symbol in a regular
1372      object to override a weak symbol in a shared object.  */
1373
1374   if (newdyn
1375       && newdef
1376       && (olddef
1377           || (h->root.type == bfd_link_hash_common
1378               && (newweak || newfunc))))
1379     {
1380       *override = TRUE;
1381       newdef = FALSE;
1382       newdyncommon = FALSE;
1383
1384       *psec = sec = bfd_und_section_ptr;
1385       *size_change_ok = TRUE;
1386
1387       /* If we get here when the old symbol is a common symbol, then
1388          we are explicitly letting it override a weak symbol or
1389          function in a dynamic object, and we don't want to warn about
1390          a type change.  If the old symbol is a defined symbol, a type
1391          change warning may still be appropriate.  */
1392
1393       if (h->root.type == bfd_link_hash_common)
1394         *type_change_ok = TRUE;
1395     }
1396
1397   /* Handle the special case of an old common symbol merging with a
1398      new symbol which looks like a common symbol in a shared object.
1399      We change *PSEC and *PVALUE to make the new symbol look like a
1400      common symbol, and let _bfd_generic_link_add_one_symbol do the
1401      right thing.  */
1402
1403   if (newdyncommon
1404       && h->root.type == bfd_link_hash_common)
1405     {
1406       *override = TRUE;
1407       newdef = FALSE;
1408       newdyncommon = FALSE;
1409       *pvalue = sym->st_size;
1410       *psec = sec = bed->common_section (oldsec);
1411       *size_change_ok = TRUE;
1412     }
1413
1414   /* Skip weak definitions of symbols that are already defined.  */
1415   if (newdef && olddef && newweak)
1416     {
1417       /* Don't skip new non-IR weak syms.  */
1418       if (!(oldbfd != NULL
1419             && (oldbfd->flags & BFD_PLUGIN) != 0
1420             && (abfd->flags & BFD_PLUGIN) == 0))
1421         {
1422           newdef = FALSE;
1423           *skip = TRUE;
1424         }
1425
1426       /* Merge st_other.  If the symbol already has a dynamic index,
1427          but visibility says it should not be visible, turn it into a
1428          local symbol.  */
1429       elf_merge_st_other (abfd, h, sym, newdef, newdyn);
1430       if (h->dynindx != -1)
1431         switch (ELF_ST_VISIBILITY (h->other))
1432           {
1433           case STV_INTERNAL:
1434           case STV_HIDDEN:
1435             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1436             break;
1437           }
1438     }
1439
1440   /* If the old symbol is from a dynamic object, and the new symbol is
1441      a definition which is not from a dynamic object, then the new
1442      symbol overrides the old symbol.  Symbols from regular files
1443      always take precedence over symbols from dynamic objects, even if
1444      they are defined after the dynamic object in the link.
1445
1446      As above, we again permit a common symbol in a regular object to
1447      override a definition in a shared object if the shared object
1448      symbol is a function or is weak.  */
1449
1450   flip = NULL;
1451   if (!newdyn
1452       && (newdef
1453           || (bfd_is_com_section (sec)
1454               && (oldweak || oldfunc)))
1455       && olddyn
1456       && olddef
1457       && h->def_dynamic)
1458     {
1459       /* Change the hash table entry to undefined, and let
1460          _bfd_generic_link_add_one_symbol do the right thing with the
1461          new definition.  */
1462
1463       h->root.type = bfd_link_hash_undefined;
1464       h->root.u.undef.abfd = h->root.u.def.section->owner;
1465       *size_change_ok = TRUE;
1466
1467       olddef = FALSE;
1468       olddyncommon = FALSE;
1469
1470       /* We again permit a type change when a common symbol may be
1471          overriding a function.  */
1472
1473       if (bfd_is_com_section (sec))
1474         {
1475           if (oldfunc)
1476             {
1477               /* If a common symbol overrides a function, make sure
1478                  that it isn't defined dynamically nor has type
1479                  function.  */
1480               h->def_dynamic = 0;
1481               h->type = STT_NOTYPE;
1482             }
1483           *type_change_ok = TRUE;
1484         }
1485
1486       if (hi->root.type == bfd_link_hash_indirect)
1487         flip = hi;
1488       else
1489         /* This union may have been set to be non-NULL when this symbol
1490            was seen in a dynamic object.  We must force the union to be
1491            NULL, so that it is correct for a regular symbol.  */
1492         h->verinfo.vertree = NULL;
1493     }
1494
1495   /* Handle the special case of a new common symbol merging with an
1496      old symbol that looks like it might be a common symbol defined in
1497      a shared object.  Note that we have already handled the case in
1498      which a new common symbol should simply override the definition
1499      in the shared library.  */
1500
1501   if (! newdyn
1502       && bfd_is_com_section (sec)
1503       && olddyncommon)
1504     {
1505       /* It would be best if we could set the hash table entry to a
1506          common symbol, but we don't know what to use for the section
1507          or the alignment.  */
1508       if (! ((*info->callbacks->multiple_common)
1509              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1510         return FALSE;
1511
1512       /* If the presumed common symbol in the dynamic object is
1513          larger, pretend that the new symbol has its size.  */
1514
1515       if (h->size > *pvalue)
1516         *pvalue = h->size;
1517
1518       /* We need to remember the alignment required by the symbol
1519          in the dynamic object.  */
1520       BFD_ASSERT (pold_alignment);
1521       *pold_alignment = h->root.u.def.section->alignment_power;
1522
1523       olddef = FALSE;
1524       olddyncommon = FALSE;
1525
1526       h->root.type = bfd_link_hash_undefined;
1527       h->root.u.undef.abfd = h->root.u.def.section->owner;
1528
1529       *size_change_ok = TRUE;
1530       *type_change_ok = TRUE;
1531
1532       if (hi->root.type == bfd_link_hash_indirect)
1533         flip = hi;
1534       else
1535         h->verinfo.vertree = NULL;
1536     }
1537
1538   if (flip != NULL)
1539     {
1540       /* Handle the case where we had a versioned symbol in a dynamic
1541          library and now find a definition in a normal object.  In this
1542          case, we make the versioned symbol point to the normal one.  */
1543       flip->root.type = h->root.type;
1544       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1545       h->root.type = bfd_link_hash_indirect;
1546       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1547       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1548       if (h->def_dynamic)
1549         {
1550           h->def_dynamic = 0;
1551           flip->ref_dynamic = 1;
1552         }
1553     }
1554
1555   return TRUE;
1556 }
1557
1558 /* This function is called to create an indirect symbol from the
1559    default for the symbol with the default version if needed. The
1560    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1561    set DYNSYM if the new indirect symbol is dynamic.  */
1562
1563 static bfd_boolean
1564 _bfd_elf_add_default_symbol (bfd *abfd,
1565                              struct bfd_link_info *info,
1566                              struct elf_link_hash_entry *h,
1567                              const char *name,
1568                              Elf_Internal_Sym *sym,
1569                              asection *sec,
1570                              bfd_vma value,
1571                              bfd **poldbfd,
1572                              bfd_boolean *dynsym)
1573 {
1574   bfd_boolean type_change_ok;
1575   bfd_boolean size_change_ok;
1576   bfd_boolean skip;
1577   char *shortname;
1578   struct elf_link_hash_entry *hi;
1579   struct bfd_link_hash_entry *bh;
1580   const struct elf_backend_data *bed;
1581   bfd_boolean collect;
1582   bfd_boolean dynamic;
1583   bfd_boolean override;
1584   char *p;
1585   size_t len, shortlen;
1586   asection *tmp_sec;
1587
1588   /* If this symbol has a version, and it is the default version, we
1589      create an indirect symbol from the default name to the fully
1590      decorated name.  This will cause external references which do not
1591      specify a version to be bound to this version of the symbol.  */
1592   p = strchr (name, ELF_VER_CHR);
1593   if (p == NULL || p[1] != ELF_VER_CHR)
1594     return TRUE;
1595
1596   bed = get_elf_backend_data (abfd);
1597   collect = bed->collect;
1598   dynamic = (abfd->flags & DYNAMIC) != 0;
1599
1600   shortlen = p - name;
1601   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1602   if (shortname == NULL)
1603     return FALSE;
1604   memcpy (shortname, name, shortlen);
1605   shortname[shortlen] = '\0';
1606
1607   /* We are going to create a new symbol.  Merge it with any existing
1608      symbol with this name.  For the purposes of the merge, act as
1609      though we were defining the symbol we just defined, although we
1610      actually going to define an indirect symbol.  */
1611   type_change_ok = FALSE;
1612   size_change_ok = FALSE;
1613   tmp_sec = sec;
1614   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1615                               &hi, poldbfd, NULL, NULL, &skip, &override,
1616                               &type_change_ok, &size_change_ok))
1617     return FALSE;
1618
1619   if (skip)
1620     goto nondefault;
1621
1622   if (! override)
1623     {
1624       bh = &hi->root;
1625       if (! (_bfd_generic_link_add_one_symbol
1626              (info, abfd, shortname, BSF_INDIRECT, bfd_ind_section_ptr,
1627               0, name, FALSE, collect, &bh)))
1628         return FALSE;
1629       hi = (struct elf_link_hash_entry *) bh;
1630     }
1631   else
1632     {
1633       /* In this case the symbol named SHORTNAME is overriding the
1634          indirect symbol we want to add.  We were planning on making
1635          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1636          is the name without a version.  NAME is the fully versioned
1637          name, and it is the default version.
1638
1639          Overriding means that we already saw a definition for the
1640          symbol SHORTNAME in a regular object, and it is overriding
1641          the symbol defined in the dynamic object.
1642
1643          When this happens, we actually want to change NAME, the
1644          symbol we just added, to refer to SHORTNAME.  This will cause
1645          references to NAME in the shared object to become references
1646          to SHORTNAME in the regular object.  This is what we expect
1647          when we override a function in a shared object: that the
1648          references in the shared object will be mapped to the
1649          definition in the regular object.  */
1650
1651       while (hi->root.type == bfd_link_hash_indirect
1652              || hi->root.type == bfd_link_hash_warning)
1653         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1654
1655       h->root.type = bfd_link_hash_indirect;
1656       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1657       if (h->def_dynamic)
1658         {
1659           h->def_dynamic = 0;
1660           hi->ref_dynamic = 1;
1661           if (hi->ref_regular
1662               || hi->def_regular)
1663             {
1664               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1665                 return FALSE;
1666             }
1667         }
1668
1669       /* Now set HI to H, so that the following code will set the
1670          other fields correctly.  */
1671       hi = h;
1672     }
1673
1674   /* Check if HI is a warning symbol.  */
1675   if (hi->root.type == bfd_link_hash_warning)
1676     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1677
1678   /* If there is a duplicate definition somewhere, then HI may not
1679      point to an indirect symbol.  We will have reported an error to
1680      the user in that case.  */
1681
1682   if (hi->root.type == bfd_link_hash_indirect)
1683     {
1684       struct elf_link_hash_entry *ht;
1685
1686       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1687       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1688
1689       /* A reference to the SHORTNAME symbol from a dynamic library
1690          will be satisfied by the versioned symbol at runtime.  In
1691          effect, we have a reference to the versioned symbol.  */
1692       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1693       hi->dynamic_def |= ht->dynamic_def;
1694
1695       /* See if the new flags lead us to realize that the symbol must
1696          be dynamic.  */
1697       if (! *dynsym)
1698         {
1699           if (! dynamic)
1700             {
1701               if (! info->executable
1702                   || hi->def_dynamic
1703                   || hi->ref_dynamic)
1704                 *dynsym = TRUE;
1705             }
1706           else
1707             {
1708               if (hi->ref_regular)
1709                 *dynsym = TRUE;
1710             }
1711         }
1712     }
1713
1714   /* We also need to define an indirection from the nondefault version
1715      of the symbol.  */
1716
1717 nondefault:
1718   len = strlen (name);
1719   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1720   if (shortname == NULL)
1721     return FALSE;
1722   memcpy (shortname, name, shortlen);
1723   memcpy (shortname + shortlen, p + 1, len - shortlen);
1724
1725   /* Once again, merge with any existing symbol.  */
1726   type_change_ok = FALSE;
1727   size_change_ok = FALSE;
1728   tmp_sec = sec;
1729   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1730                               &hi, poldbfd, NULL, NULL, &skip, &override,
1731                               &type_change_ok, &size_change_ok))
1732     return FALSE;
1733
1734   if (skip)
1735     return TRUE;
1736
1737   if (override)
1738     {
1739       /* Here SHORTNAME is a versioned name, so we don't expect to see
1740          the type of override we do in the case above unless it is
1741          overridden by a versioned definition.  */
1742       if (hi->root.type != bfd_link_hash_defined
1743           && hi->root.type != bfd_link_hash_defweak)
1744         (*_bfd_error_handler)
1745           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1746            abfd, shortname);
1747     }
1748   else
1749     {
1750       bh = &hi->root;
1751       if (! (_bfd_generic_link_add_one_symbol
1752              (info, abfd, shortname, BSF_INDIRECT,
1753               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1754         return FALSE;
1755       hi = (struct elf_link_hash_entry *) bh;
1756
1757       /* If there is a duplicate definition somewhere, then HI may not
1758          point to an indirect symbol.  We will have reported an error
1759          to the user in that case.  */
1760
1761       if (hi->root.type == bfd_link_hash_indirect)
1762         {
1763           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1764           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1765           hi->dynamic_def |= h->dynamic_def;
1766
1767           /* See if the new flags lead us to realize that the symbol
1768              must be dynamic.  */
1769           if (! *dynsym)
1770             {
1771               if (! dynamic)
1772                 {
1773                   if (! info->executable
1774                       || hi->ref_dynamic)
1775                     *dynsym = TRUE;
1776                 }
1777               else
1778                 {
1779                   if (hi->ref_regular)
1780                     *dynsym = TRUE;
1781                 }
1782             }
1783         }
1784     }
1785
1786   return TRUE;
1787 }
1788 \f
1789 /* This routine is used to export all defined symbols into the dynamic
1790    symbol table.  It is called via elf_link_hash_traverse.  */
1791
1792 static bfd_boolean
1793 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1794 {
1795   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1796
1797   /* Ignore indirect symbols.  These are added by the versioning code.  */
1798   if (h->root.type == bfd_link_hash_indirect)
1799     return TRUE;
1800
1801   /* Ignore this if we won't export it.  */
1802   if (!eif->info->export_dynamic && !h->dynamic)
1803     return TRUE;
1804
1805   if (h->dynindx == -1
1806       && (h->def_regular || h->ref_regular)
1807       && ! bfd_hide_sym_by_version (eif->info->version_info,
1808                                     h->root.root.string))
1809     {
1810       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1811         {
1812           eif->failed = TRUE;
1813           return FALSE;
1814         }
1815     }
1816
1817   return TRUE;
1818 }
1819 \f
1820 /* Look through the symbols which are defined in other shared
1821    libraries and referenced here.  Update the list of version
1822    dependencies.  This will be put into the .gnu.version_r section.
1823    This function is called via elf_link_hash_traverse.  */
1824
1825 static bfd_boolean
1826 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1827                                          void *data)
1828 {
1829   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1830   Elf_Internal_Verneed *t;
1831   Elf_Internal_Vernaux *a;
1832   bfd_size_type amt;
1833
1834   /* We only care about symbols defined in shared objects with version
1835      information.  */
1836   if (!h->def_dynamic
1837       || h->def_regular
1838       || h->dynindx == -1
1839       || h->verinfo.verdef == NULL
1840       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
1841           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
1842     return TRUE;
1843
1844   /* See if we already know about this version.  */
1845   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1846        t != NULL;
1847        t = t->vn_nextref)
1848     {
1849       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1850         continue;
1851
1852       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1853         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1854           return TRUE;
1855
1856       break;
1857     }
1858
1859   /* This is a new version.  Add it to tree we are building.  */
1860
1861   if (t == NULL)
1862     {
1863       amt = sizeof *t;
1864       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
1865       if (t == NULL)
1866         {
1867           rinfo->failed = TRUE;
1868           return FALSE;
1869         }
1870
1871       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1872       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
1873       elf_tdata (rinfo->info->output_bfd)->verref = t;
1874     }
1875
1876   amt = sizeof *a;
1877   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
1878   if (a == NULL)
1879     {
1880       rinfo->failed = TRUE;
1881       return FALSE;
1882     }
1883
1884   /* Note that we are copying a string pointer here, and testing it
1885      above.  If bfd_elf_string_from_elf_section is ever changed to
1886      discard the string data when low in memory, this will have to be
1887      fixed.  */
1888   a->vna_nodename = h->verinfo.verdef->vd_nodename;
1889
1890   a->vna_flags = h->verinfo.verdef->vd_flags;
1891   a->vna_nextptr = t->vn_auxptr;
1892
1893   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1894   ++rinfo->vers;
1895
1896   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1897
1898   t->vn_auxptr = a;
1899
1900   return TRUE;
1901 }
1902
1903 /* Figure out appropriate versions for all the symbols.  We may not
1904    have the version number script until we have read all of the input
1905    files, so until that point we don't know which symbols should be
1906    local.  This function is called via elf_link_hash_traverse.  */
1907
1908 static bfd_boolean
1909 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
1910 {
1911   struct elf_info_failed *sinfo;
1912   struct bfd_link_info *info;
1913   const struct elf_backend_data *bed;
1914   struct elf_info_failed eif;
1915   char *p;
1916   bfd_size_type amt;
1917
1918   sinfo = (struct elf_info_failed *) data;
1919   info = sinfo->info;
1920
1921   /* Fix the symbol flags.  */
1922   eif.failed = FALSE;
1923   eif.info = info;
1924   if (! _bfd_elf_fix_symbol_flags (h, &eif))
1925     {
1926       if (eif.failed)
1927         sinfo->failed = TRUE;
1928       return FALSE;
1929     }
1930
1931   /* We only need version numbers for symbols defined in regular
1932      objects.  */
1933   if (!h->def_regular)
1934     return TRUE;
1935
1936   bed = get_elf_backend_data (info->output_bfd);
1937   p = strchr (h->root.root.string, ELF_VER_CHR);
1938   if (p != NULL && h->verinfo.vertree == NULL)
1939     {
1940       struct bfd_elf_version_tree *t;
1941       bfd_boolean hidden;
1942
1943       hidden = TRUE;
1944
1945       /* There are two consecutive ELF_VER_CHR characters if this is
1946          not a hidden symbol.  */
1947       ++p;
1948       if (*p == ELF_VER_CHR)
1949         {
1950           hidden = FALSE;
1951           ++p;
1952         }
1953
1954       /* If there is no version string, we can just return out.  */
1955       if (*p == '\0')
1956         {
1957           if (hidden)
1958             h->hidden = 1;
1959           return TRUE;
1960         }
1961
1962       /* Look for the version.  If we find it, it is no longer weak.  */
1963       for (t = sinfo->info->version_info; t != NULL; t = t->next)
1964         {
1965           if (strcmp (t->name, p) == 0)
1966             {
1967               size_t len;
1968               char *alc;
1969               struct bfd_elf_version_expr *d;
1970
1971               len = p - h->root.root.string;
1972               alc = (char *) bfd_malloc (len);
1973               if (alc == NULL)
1974                 {
1975                   sinfo->failed = TRUE;
1976                   return FALSE;
1977                 }
1978               memcpy (alc, h->root.root.string, len - 1);
1979               alc[len - 1] = '\0';
1980               if (alc[len - 2] == ELF_VER_CHR)
1981                 alc[len - 2] = '\0';
1982
1983               h->verinfo.vertree = t;
1984               t->used = TRUE;
1985               d = NULL;
1986
1987               if (t->globals.list != NULL)
1988                 d = (*t->match) (&t->globals, NULL, alc);
1989
1990               /* See if there is anything to force this symbol to
1991                  local scope.  */
1992               if (d == NULL && t->locals.list != NULL)
1993                 {
1994                   d = (*t->match) (&t->locals, NULL, alc);
1995                   if (d != NULL
1996                       && h->dynindx != -1
1997                       && ! info->export_dynamic)
1998                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1999                 }
2000
2001               free (alc);
2002               break;
2003             }
2004         }
2005
2006       /* If we are building an application, we need to create a
2007          version node for this version.  */
2008       if (t == NULL && info->executable)
2009         {
2010           struct bfd_elf_version_tree **pp;
2011           int version_index;
2012
2013           /* If we aren't going to export this symbol, we don't need
2014              to worry about it.  */
2015           if (h->dynindx == -1)
2016             return TRUE;
2017
2018           amt = sizeof *t;
2019           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2020           if (t == NULL)
2021             {
2022               sinfo->failed = TRUE;
2023               return FALSE;
2024             }
2025
2026           t->name = p;
2027           t->name_indx = (unsigned int) -1;
2028           t->used = TRUE;
2029
2030           version_index = 1;
2031           /* Don't count anonymous version tag.  */
2032           if (sinfo->info->version_info != NULL
2033               && sinfo->info->version_info->vernum == 0)
2034             version_index = 0;
2035           for (pp = &sinfo->info->version_info;
2036                *pp != NULL;
2037                pp = &(*pp)->next)
2038             ++version_index;
2039           t->vernum = version_index;
2040
2041           *pp = t;
2042
2043           h->verinfo.vertree = t;
2044         }
2045       else if (t == NULL)
2046         {
2047           /* We could not find the version for a symbol when
2048              generating a shared archive.  Return an error.  */
2049           (*_bfd_error_handler)
2050             (_("%B: version node not found for symbol %s"),
2051              info->output_bfd, h->root.root.string);
2052           bfd_set_error (bfd_error_bad_value);
2053           sinfo->failed = TRUE;
2054           return FALSE;
2055         }
2056
2057       if (hidden)
2058         h->hidden = 1;
2059     }
2060
2061   /* If we don't have a version for this symbol, see if we can find
2062      something.  */
2063   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2064     {
2065       bfd_boolean hide;
2066
2067       h->verinfo.vertree
2068         = bfd_find_version_for_sym (sinfo->info->version_info,
2069                                     h->root.root.string, &hide);
2070       if (h->verinfo.vertree != NULL && hide)
2071         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2072     }
2073
2074   return TRUE;
2075 }
2076 \f
2077 /* Read and swap the relocs from the section indicated by SHDR.  This
2078    may be either a REL or a RELA section.  The relocations are
2079    translated into RELA relocations and stored in INTERNAL_RELOCS,
2080    which should have already been allocated to contain enough space.
2081    The EXTERNAL_RELOCS are a buffer where the external form of the
2082    relocations should be stored.
2083
2084    Returns FALSE if something goes wrong.  */
2085
2086 static bfd_boolean
2087 elf_link_read_relocs_from_section (bfd *abfd,
2088                                    asection *sec,
2089                                    Elf_Internal_Shdr *shdr,
2090                                    void *external_relocs,
2091                                    Elf_Internal_Rela *internal_relocs)
2092 {
2093   const struct elf_backend_data *bed;
2094   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2095   const bfd_byte *erela;
2096   const bfd_byte *erelaend;
2097   Elf_Internal_Rela *irela;
2098   Elf_Internal_Shdr *symtab_hdr;
2099   size_t nsyms;
2100
2101   /* Position ourselves at the start of the section.  */
2102   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2103     return FALSE;
2104
2105   /* Read the relocations.  */
2106   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2107     return FALSE;
2108
2109   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2110   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2111
2112   bed = get_elf_backend_data (abfd);
2113
2114   /* Convert the external relocations to the internal format.  */
2115   if (shdr->sh_entsize == bed->s->sizeof_rel)
2116     swap_in = bed->s->swap_reloc_in;
2117   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2118     swap_in = bed->s->swap_reloca_in;
2119   else
2120     {
2121       bfd_set_error (bfd_error_wrong_format);
2122       return FALSE;
2123     }
2124
2125   erela = (const bfd_byte *) external_relocs;
2126   erelaend = erela + shdr->sh_size;
2127   irela = internal_relocs;
2128   while (erela < erelaend)
2129     {
2130       bfd_vma r_symndx;
2131
2132       (*swap_in) (abfd, erela, irela);
2133       r_symndx = ELF32_R_SYM (irela->r_info);
2134       if (bed->s->arch_size == 64)
2135         r_symndx >>= 24;
2136       if (nsyms > 0)
2137         {
2138           if ((size_t) r_symndx >= nsyms)
2139             {
2140               (*_bfd_error_handler)
2141                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2142                    " for offset 0x%lx in section `%A'"),
2143                  abfd, sec,
2144                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2145               bfd_set_error (bfd_error_bad_value);
2146               return FALSE;
2147             }
2148         }
2149       else if (r_symndx != STN_UNDEF)
2150         {
2151           (*_bfd_error_handler)
2152             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2153                " when the object file has no symbol table"),
2154              abfd, sec,
2155              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2156           bfd_set_error (bfd_error_bad_value);
2157           return FALSE;
2158         }
2159       irela += bed->s->int_rels_per_ext_rel;
2160       erela += shdr->sh_entsize;
2161     }
2162
2163   return TRUE;
2164 }
2165
2166 /* Read and swap the relocs for a section O.  They may have been
2167    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2168    not NULL, they are used as buffers to read into.  They are known to
2169    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2170    the return value is allocated using either malloc or bfd_alloc,
2171    according to the KEEP_MEMORY argument.  If O has two relocation
2172    sections (both REL and RELA relocations), then the REL_HDR
2173    relocations will appear first in INTERNAL_RELOCS, followed by the
2174    RELA_HDR relocations.  */
2175
2176 Elf_Internal_Rela *
2177 _bfd_elf_link_read_relocs (bfd *abfd,
2178                            asection *o,
2179                            void *external_relocs,
2180                            Elf_Internal_Rela *internal_relocs,
2181                            bfd_boolean keep_memory)
2182 {
2183   void *alloc1 = NULL;
2184   Elf_Internal_Rela *alloc2 = NULL;
2185   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2186   struct bfd_elf_section_data *esdo = elf_section_data (o);
2187   Elf_Internal_Rela *internal_rela_relocs;
2188
2189   if (esdo->relocs != NULL)
2190     return esdo->relocs;
2191
2192   if (o->reloc_count == 0)
2193     return NULL;
2194
2195   if (internal_relocs == NULL)
2196     {
2197       bfd_size_type size;
2198
2199       size = o->reloc_count;
2200       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2201       if (keep_memory)
2202         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2203       else
2204         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2205       if (internal_relocs == NULL)
2206         goto error_return;
2207     }
2208
2209   if (external_relocs == NULL)
2210     {
2211       bfd_size_type size = 0;
2212
2213       if (esdo->rel.hdr)
2214         size += esdo->rel.hdr->sh_size;
2215       if (esdo->rela.hdr)
2216         size += esdo->rela.hdr->sh_size;
2217
2218       alloc1 = bfd_malloc (size);
2219       if (alloc1 == NULL)
2220         goto error_return;
2221       external_relocs = alloc1;
2222     }
2223
2224   internal_rela_relocs = internal_relocs;
2225   if (esdo->rel.hdr)
2226     {
2227       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2228                                               external_relocs,
2229                                               internal_relocs))
2230         goto error_return;
2231       external_relocs = (((bfd_byte *) external_relocs)
2232                          + esdo->rel.hdr->sh_size);
2233       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2234                                * bed->s->int_rels_per_ext_rel);
2235     }
2236
2237   if (esdo->rela.hdr
2238       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2239                                               external_relocs,
2240                                               internal_rela_relocs)))
2241     goto error_return;
2242
2243   /* Cache the results for next time, if we can.  */
2244   if (keep_memory)
2245     esdo->relocs = internal_relocs;
2246
2247   if (alloc1 != NULL)
2248     free (alloc1);
2249
2250   /* Don't free alloc2, since if it was allocated we are passing it
2251      back (under the name of internal_relocs).  */
2252
2253   return internal_relocs;
2254
2255  error_return:
2256   if (alloc1 != NULL)
2257     free (alloc1);
2258   if (alloc2 != NULL)
2259     {
2260       if (keep_memory)
2261         bfd_release (abfd, alloc2);
2262       else
2263         free (alloc2);
2264     }
2265   return NULL;
2266 }
2267
2268 /* Compute the size of, and allocate space for, REL_HDR which is the
2269    section header for a section containing relocations for O.  */
2270
2271 static bfd_boolean
2272 _bfd_elf_link_size_reloc_section (bfd *abfd,
2273                                   struct bfd_elf_section_reloc_data *reldata)
2274 {
2275   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2276
2277   /* That allows us to calculate the size of the section.  */
2278   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2279
2280   /* The contents field must last into write_object_contents, so we
2281      allocate it with bfd_alloc rather than malloc.  Also since we
2282      cannot be sure that the contents will actually be filled in,
2283      we zero the allocated space.  */
2284   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2285   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2286     return FALSE;
2287
2288   if (reldata->hashes == NULL && reldata->count)
2289     {
2290       struct elf_link_hash_entry **p;
2291
2292       p = (struct elf_link_hash_entry **)
2293           bfd_zmalloc (reldata->count * sizeof (struct elf_link_hash_entry *));
2294       if (p == NULL)
2295         return FALSE;
2296
2297       reldata->hashes = p;
2298     }
2299
2300   return TRUE;
2301 }
2302
2303 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2304    originated from the section given by INPUT_REL_HDR) to the
2305    OUTPUT_BFD.  */
2306
2307 bfd_boolean
2308 _bfd_elf_link_output_relocs (bfd *output_bfd,
2309                              asection *input_section,
2310                              Elf_Internal_Shdr *input_rel_hdr,
2311                              Elf_Internal_Rela *internal_relocs,
2312                              struct elf_link_hash_entry **rel_hash
2313                                ATTRIBUTE_UNUSED)
2314 {
2315   Elf_Internal_Rela *irela;
2316   Elf_Internal_Rela *irelaend;
2317   bfd_byte *erel;
2318   struct bfd_elf_section_reloc_data *output_reldata;
2319   asection *output_section;
2320   const struct elf_backend_data *bed;
2321   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2322   struct bfd_elf_section_data *esdo;
2323
2324   output_section = input_section->output_section;
2325
2326   bed = get_elf_backend_data (output_bfd);
2327   esdo = elf_section_data (output_section);
2328   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2329     {
2330       output_reldata = &esdo->rel;
2331       swap_out = bed->s->swap_reloc_out;
2332     }
2333   else if (esdo->rela.hdr
2334            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2335     {
2336       output_reldata = &esdo->rela;
2337       swap_out = bed->s->swap_reloca_out;
2338     }
2339   else
2340     {
2341       (*_bfd_error_handler)
2342         (_("%B: relocation size mismatch in %B section %A"),
2343          output_bfd, input_section->owner, input_section);
2344       bfd_set_error (bfd_error_wrong_format);
2345       return FALSE;
2346     }
2347
2348   erel = output_reldata->hdr->contents;
2349   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2350   irela = internal_relocs;
2351   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2352                       * bed->s->int_rels_per_ext_rel);
2353   while (irela < irelaend)
2354     {
2355       (*swap_out) (output_bfd, irela, erel);
2356       irela += bed->s->int_rels_per_ext_rel;
2357       erel += input_rel_hdr->sh_entsize;
2358     }
2359
2360   /* Bump the counter, so that we know where to add the next set of
2361      relocations.  */
2362   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2363
2364   return TRUE;
2365 }
2366 \f
2367 /* Make weak undefined symbols in PIE dynamic.  */
2368
2369 bfd_boolean
2370 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2371                                  struct elf_link_hash_entry *h)
2372 {
2373   if (info->pie
2374       && h->dynindx == -1
2375       && h->root.type == bfd_link_hash_undefweak)
2376     return bfd_elf_link_record_dynamic_symbol (info, h);
2377
2378   return TRUE;
2379 }
2380
2381 /* Fix up the flags for a symbol.  This handles various cases which
2382    can only be fixed after all the input files are seen.  This is
2383    currently called by both adjust_dynamic_symbol and
2384    assign_sym_version, which is unnecessary but perhaps more robust in
2385    the face of future changes.  */
2386
2387 static bfd_boolean
2388 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2389                            struct elf_info_failed *eif)
2390 {
2391   const struct elf_backend_data *bed;
2392
2393   /* If this symbol was mentioned in a non-ELF file, try to set
2394      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2395      permit a non-ELF file to correctly refer to a symbol defined in
2396      an ELF dynamic object.  */
2397   if (h->non_elf)
2398     {
2399       while (h->root.type == bfd_link_hash_indirect)
2400         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2401
2402       if (h->root.type != bfd_link_hash_defined
2403           && h->root.type != bfd_link_hash_defweak)
2404         {
2405           h->ref_regular = 1;
2406           h->ref_regular_nonweak = 1;
2407         }
2408       else
2409         {
2410           if (h->root.u.def.section->owner != NULL
2411               && (bfd_get_flavour (h->root.u.def.section->owner)
2412                   == bfd_target_elf_flavour))
2413             {
2414               h->ref_regular = 1;
2415               h->ref_regular_nonweak = 1;
2416             }
2417           else
2418             h->def_regular = 1;
2419         }
2420
2421       if (h->dynindx == -1
2422           && (h->def_dynamic
2423               || h->ref_dynamic))
2424         {
2425           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2426             {
2427               eif->failed = TRUE;
2428               return FALSE;
2429             }
2430         }
2431     }
2432   else
2433     {
2434       /* Unfortunately, NON_ELF is only correct if the symbol
2435          was first seen in a non-ELF file.  Fortunately, if the symbol
2436          was first seen in an ELF file, we're probably OK unless the
2437          symbol was defined in a non-ELF file.  Catch that case here.
2438          FIXME: We're still in trouble if the symbol was first seen in
2439          a dynamic object, and then later in a non-ELF regular object.  */
2440       if ((h->root.type == bfd_link_hash_defined
2441            || h->root.type == bfd_link_hash_defweak)
2442           && !h->def_regular
2443           && (h->root.u.def.section->owner != NULL
2444               ? (bfd_get_flavour (h->root.u.def.section->owner)
2445                  != bfd_target_elf_flavour)
2446               : (bfd_is_abs_section (h->root.u.def.section)
2447                  && !h->def_dynamic)))
2448         h->def_regular = 1;
2449     }
2450
2451   /* Backend specific symbol fixup.  */
2452   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2453   if (bed->elf_backend_fixup_symbol
2454       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2455     return FALSE;
2456
2457   /* If this is a final link, and the symbol was defined as a common
2458      symbol in a regular object file, and there was no definition in
2459      any dynamic object, then the linker will have allocated space for
2460      the symbol in a common section but the DEF_REGULAR
2461      flag will not have been set.  */
2462   if (h->root.type == bfd_link_hash_defined
2463       && !h->def_regular
2464       && h->ref_regular
2465       && !h->def_dynamic
2466       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2467     h->def_regular = 1;
2468
2469   /* If -Bsymbolic was used (which means to bind references to global
2470      symbols to the definition within the shared object), and this
2471      symbol was defined in a regular object, then it actually doesn't
2472      need a PLT entry.  Likewise, if the symbol has non-default
2473      visibility.  If the symbol has hidden or internal visibility, we
2474      will force it local.  */
2475   if (h->needs_plt
2476       && eif->info->shared
2477       && is_elf_hash_table (eif->info->hash)
2478       && (SYMBOLIC_BIND (eif->info, h)
2479           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2480       && h->def_regular)
2481     {
2482       bfd_boolean force_local;
2483
2484       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2485                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2486       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2487     }
2488
2489   /* If a weak undefined symbol has non-default visibility, we also
2490      hide it from the dynamic linker.  */
2491   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2492       && h->root.type == bfd_link_hash_undefweak)
2493     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2494
2495   /* If this is a weak defined symbol in a dynamic object, and we know
2496      the real definition in the dynamic object, copy interesting flags
2497      over to the real definition.  */
2498   if (h->u.weakdef != NULL)
2499     {
2500       /* If the real definition is defined by a regular object file,
2501          don't do anything special.  See the longer description in
2502          _bfd_elf_adjust_dynamic_symbol, below.  */
2503       if (h->u.weakdef->def_regular)
2504         h->u.weakdef = NULL;
2505       else
2506         {
2507           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2508
2509           while (h->root.type == bfd_link_hash_indirect)
2510             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2511
2512           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2513                       || h->root.type == bfd_link_hash_defweak);
2514           BFD_ASSERT (weakdef->def_dynamic);
2515           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2516                       || weakdef->root.type == bfd_link_hash_defweak);
2517           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2518         }
2519     }
2520
2521   return TRUE;
2522 }
2523
2524 /* Make the backend pick a good value for a dynamic symbol.  This is
2525    called via elf_link_hash_traverse, and also calls itself
2526    recursively.  */
2527
2528 static bfd_boolean
2529 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2530 {
2531   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2532   bfd *dynobj;
2533   const struct elf_backend_data *bed;
2534
2535   if (! is_elf_hash_table (eif->info->hash))
2536     return FALSE;
2537
2538   /* Ignore indirect symbols.  These are added by the versioning code.  */
2539   if (h->root.type == bfd_link_hash_indirect)
2540     return TRUE;
2541
2542   /* Fix the symbol flags.  */
2543   if (! _bfd_elf_fix_symbol_flags (h, eif))
2544     return FALSE;
2545
2546   /* If this symbol does not require a PLT entry, and it is not
2547      defined by a dynamic object, or is not referenced by a regular
2548      object, ignore it.  We do have to handle a weak defined symbol,
2549      even if no regular object refers to it, if we decided to add it
2550      to the dynamic symbol table.  FIXME: Do we normally need to worry
2551      about symbols which are defined by one dynamic object and
2552      referenced by another one?  */
2553   if (!h->needs_plt
2554       && h->type != STT_GNU_IFUNC
2555       && (h->def_regular
2556           || !h->def_dynamic
2557           || (!h->ref_regular
2558               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2559     {
2560       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2561       return TRUE;
2562     }
2563
2564   /* If we've already adjusted this symbol, don't do it again.  This
2565      can happen via a recursive call.  */
2566   if (h->dynamic_adjusted)
2567     return TRUE;
2568
2569   /* Don't look at this symbol again.  Note that we must set this
2570      after checking the above conditions, because we may look at a
2571      symbol once, decide not to do anything, and then get called
2572      recursively later after REF_REGULAR is set below.  */
2573   h->dynamic_adjusted = 1;
2574
2575   /* If this is a weak definition, and we know a real definition, and
2576      the real symbol is not itself defined by a regular object file,
2577      then get a good value for the real definition.  We handle the
2578      real symbol first, for the convenience of the backend routine.
2579
2580      Note that there is a confusing case here.  If the real definition
2581      is defined by a regular object file, we don't get the real symbol
2582      from the dynamic object, but we do get the weak symbol.  If the
2583      processor backend uses a COPY reloc, then if some routine in the
2584      dynamic object changes the real symbol, we will not see that
2585      change in the corresponding weak symbol.  This is the way other
2586      ELF linkers work as well, and seems to be a result of the shared
2587      library model.
2588
2589      I will clarify this issue.  Most SVR4 shared libraries define the
2590      variable _timezone and define timezone as a weak synonym.  The
2591      tzset call changes _timezone.  If you write
2592        extern int timezone;
2593        int _timezone = 5;
2594        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2595      you might expect that, since timezone is a synonym for _timezone,
2596      the same number will print both times.  However, if the processor
2597      backend uses a COPY reloc, then actually timezone will be copied
2598      into your process image, and, since you define _timezone
2599      yourself, _timezone will not.  Thus timezone and _timezone will
2600      wind up at different memory locations.  The tzset call will set
2601      _timezone, leaving timezone unchanged.  */
2602
2603   if (h->u.weakdef != NULL)
2604     {
2605       /* If we get to this point, there is an implicit reference to
2606          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2607       h->u.weakdef->ref_regular = 1;
2608
2609       /* Ensure that the backend adjust_dynamic_symbol function sees
2610          H->U.WEAKDEF before H by recursively calling ourselves.  */
2611       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2612         return FALSE;
2613     }
2614
2615   /* If a symbol has no type and no size and does not require a PLT
2616      entry, then we are probably about to do the wrong thing here: we
2617      are probably going to create a COPY reloc for an empty object.
2618      This case can arise when a shared object is built with assembly
2619      code, and the assembly code fails to set the symbol type.  */
2620   if (h->size == 0
2621       && h->type == STT_NOTYPE
2622       && !h->needs_plt)
2623     (*_bfd_error_handler)
2624       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2625        h->root.root.string);
2626
2627   dynobj = elf_hash_table (eif->info)->dynobj;
2628   bed = get_elf_backend_data (dynobj);
2629
2630   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2631     {
2632       eif->failed = TRUE;
2633       return FALSE;
2634     }
2635
2636   return TRUE;
2637 }
2638
2639 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2640    DYNBSS.  */
2641
2642 bfd_boolean
2643 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2644                               struct elf_link_hash_entry *h,
2645                               asection *dynbss)
2646 {
2647   unsigned int power_of_two;
2648   bfd_vma mask;
2649   asection *sec = h->root.u.def.section;
2650
2651   /* The section aligment of definition is the maximum alignment
2652      requirement of symbols defined in the section.  Since we don't
2653      know the symbol alignment requirement, we start with the
2654      maximum alignment and check low bits of the symbol address
2655      for the minimum alignment.  */
2656   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2657   mask = ((bfd_vma) 1 << power_of_two) - 1;
2658   while ((h->root.u.def.value & mask) != 0)
2659     {
2660        mask >>= 1;
2661        --power_of_two;
2662     }
2663
2664   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2665                                                 dynbss))
2666     {
2667       /* Adjust the section alignment if needed.  */
2668       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2669                                        power_of_two))
2670         return FALSE;
2671     }
2672
2673   /* We make sure that the symbol will be aligned properly.  */
2674   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2675
2676   /* Define the symbol as being at this point in DYNBSS.  */
2677   h->root.u.def.section = dynbss;
2678   h->root.u.def.value = dynbss->size;
2679
2680   /* Increment the size of DYNBSS to make room for the symbol.  */
2681   dynbss->size += h->size;
2682
2683   if (h->protected_def)
2684     {
2685       info->callbacks->einfo
2686         (_("%P: copy reloc against protected `%T' is invalid\n"),
2687          h->root.root.string);
2688       bfd_set_error (bfd_error_bad_value);
2689       return FALSE;
2690     }
2691
2692   return TRUE;
2693 }
2694
2695 /* Adjust all external symbols pointing into SEC_MERGE sections
2696    to reflect the object merging within the sections.  */
2697
2698 static bfd_boolean
2699 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2700 {
2701   asection *sec;
2702
2703   if ((h->root.type == bfd_link_hash_defined
2704        || h->root.type == bfd_link_hash_defweak)
2705       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2706       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2707     {
2708       bfd *output_bfd = (bfd *) data;
2709
2710       h->root.u.def.value =
2711         _bfd_merged_section_offset (output_bfd,
2712                                     &h->root.u.def.section,
2713                                     elf_section_data (sec)->sec_info,
2714                                     h->root.u.def.value);
2715     }
2716
2717   return TRUE;
2718 }
2719
2720 /* Returns false if the symbol referred to by H should be considered
2721    to resolve local to the current module, and true if it should be
2722    considered to bind dynamically.  */
2723
2724 bfd_boolean
2725 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2726                            struct bfd_link_info *info,
2727                            bfd_boolean not_local_protected)
2728 {
2729   bfd_boolean binding_stays_local_p;
2730   const struct elf_backend_data *bed;
2731   struct elf_link_hash_table *hash_table;
2732
2733   if (h == NULL)
2734     return FALSE;
2735
2736   while (h->root.type == bfd_link_hash_indirect
2737          || h->root.type == bfd_link_hash_warning)
2738     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2739
2740   /* If it was forced local, then clearly it's not dynamic.  */
2741   if (h->dynindx == -1)
2742     return FALSE;
2743   if (h->forced_local)
2744     return FALSE;
2745
2746   /* Identify the cases where name binding rules say that a
2747      visible symbol resolves locally.  */
2748   binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2749
2750   switch (ELF_ST_VISIBILITY (h->other))
2751     {
2752     case STV_INTERNAL:
2753     case STV_HIDDEN:
2754       return FALSE;
2755
2756     case STV_PROTECTED:
2757       hash_table = elf_hash_table (info);
2758       if (!is_elf_hash_table (hash_table))
2759         return FALSE;
2760
2761       bed = get_elf_backend_data (hash_table->dynobj);
2762
2763       /* Proper resolution for function pointer equality may require
2764          that these symbols perhaps be resolved dynamically, even though
2765          we should be resolving them to the current module.  */
2766       if (!not_local_protected || !bed->is_function_type (h->type))
2767         binding_stays_local_p = TRUE;
2768       break;
2769
2770     default:
2771       break;
2772     }
2773
2774   /* If it isn't defined locally, then clearly it's dynamic.  */
2775   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2776     return TRUE;
2777
2778   /* Otherwise, the symbol is dynamic if binding rules don't tell
2779      us that it remains local.  */
2780   return !binding_stays_local_p;
2781 }
2782
2783 /* Return true if the symbol referred to by H should be considered
2784    to resolve local to the current module, and false otherwise.  Differs
2785    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2786    undefined symbols.  The two functions are virtually identical except
2787    for the place where forced_local and dynindx == -1 are tested.  If
2788    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2789    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2790    the symbol is local only for defined symbols.
2791    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2792    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2793    treatment of undefined weak symbols.  For those that do not make
2794    undefined weak symbols dynamic, both functions may return false.  */
2795
2796 bfd_boolean
2797 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2798                               struct bfd_link_info *info,
2799                               bfd_boolean local_protected)
2800 {
2801   const struct elf_backend_data *bed;
2802   struct elf_link_hash_table *hash_table;
2803
2804   /* If it's a local sym, of course we resolve locally.  */
2805   if (h == NULL)
2806     return TRUE;
2807
2808   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2809   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2810       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2811     return TRUE;
2812
2813   /* Common symbols that become definitions don't get the DEF_REGULAR
2814      flag set, so test it first, and don't bail out.  */
2815   if (ELF_COMMON_DEF_P (h))
2816     /* Do nothing.  */;
2817   /* If we don't have a definition in a regular file, then we can't
2818      resolve locally.  The sym is either undefined or dynamic.  */
2819   else if (!h->def_regular)
2820     return FALSE;
2821
2822   /* Forced local symbols resolve locally.  */
2823   if (h->forced_local)
2824     return TRUE;
2825
2826   /* As do non-dynamic symbols.  */
2827   if (h->dynindx == -1)
2828     return TRUE;
2829
2830   /* At this point, we know the symbol is defined and dynamic.  In an
2831      executable it must resolve locally, likewise when building symbolic
2832      shared libraries.  */
2833   if (info->executable || SYMBOLIC_BIND (info, h))
2834     return TRUE;
2835
2836   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2837      with default visibility might not resolve locally.  */
2838   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2839     return FALSE;
2840
2841   hash_table = elf_hash_table (info);
2842   if (!is_elf_hash_table (hash_table))
2843     return TRUE;
2844
2845   bed = get_elf_backend_data (hash_table->dynobj);
2846
2847   /* STV_PROTECTED non-function symbols are local.  */
2848   if (!bed->is_function_type (h->type))
2849     return TRUE;
2850
2851   /* Function pointer equality tests may require that STV_PROTECTED
2852      symbols be treated as dynamic symbols.  If the address of a
2853      function not defined in an executable is set to that function's
2854      plt entry in the executable, then the address of the function in
2855      a shared library must also be the plt entry in the executable.  */
2856   return local_protected;
2857 }
2858
2859 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2860    aligned.  Returns the first TLS output section.  */
2861
2862 struct bfd_section *
2863 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2864 {
2865   struct bfd_section *sec, *tls;
2866   unsigned int align = 0;
2867
2868   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2869     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2870       break;
2871   tls = sec;
2872
2873   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2874     if (sec->alignment_power > align)
2875       align = sec->alignment_power;
2876
2877   elf_hash_table (info)->tls_sec = tls;
2878
2879   /* Ensure the alignment of the first section is the largest alignment,
2880      so that the tls segment starts aligned.  */
2881   if (tls != NULL)
2882     tls->alignment_power = align;
2883
2884   return tls;
2885 }
2886
2887 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2888 static bfd_boolean
2889 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2890                                   Elf_Internal_Sym *sym)
2891 {
2892   const struct elf_backend_data *bed;
2893
2894   /* Local symbols do not count, but target specific ones might.  */
2895   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2896       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2897     return FALSE;
2898
2899   bed = get_elf_backend_data (abfd);
2900   /* Function symbols do not count.  */
2901   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
2902     return FALSE;
2903
2904   /* If the section is undefined, then so is the symbol.  */
2905   if (sym->st_shndx == SHN_UNDEF)
2906     return FALSE;
2907
2908   /* If the symbol is defined in the common section, then
2909      it is a common definition and so does not count.  */
2910   if (bed->common_definition (sym))
2911     return FALSE;
2912
2913   /* If the symbol is in a target specific section then we
2914      must rely upon the backend to tell us what it is.  */
2915   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
2916     /* FIXME - this function is not coded yet:
2917
2918        return _bfd_is_global_symbol_definition (abfd, sym);
2919
2920        Instead for now assume that the definition is not global,
2921        Even if this is wrong, at least the linker will behave
2922        in the same way that it used to do.  */
2923     return FALSE;
2924
2925   return TRUE;
2926 }
2927
2928 /* Search the symbol table of the archive element of the archive ABFD
2929    whose archive map contains a mention of SYMDEF, and determine if
2930    the symbol is defined in this element.  */
2931 static bfd_boolean
2932 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
2933 {
2934   Elf_Internal_Shdr * hdr;
2935   bfd_size_type symcount;
2936   bfd_size_type extsymcount;
2937   bfd_size_type extsymoff;
2938   Elf_Internal_Sym *isymbuf;
2939   Elf_Internal_Sym *isym;
2940   Elf_Internal_Sym *isymend;
2941   bfd_boolean result;
2942
2943   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
2944   if (abfd == NULL)
2945     return FALSE;
2946
2947   if (! bfd_check_format (abfd, bfd_object))
2948     return FALSE;
2949
2950   /* Select the appropriate symbol table.  */
2951   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
2952     hdr = &elf_tdata (abfd)->symtab_hdr;
2953   else
2954     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2955
2956   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
2957
2958   /* The sh_info field of the symtab header tells us where the
2959      external symbols start.  We don't care about the local symbols.  */
2960   if (elf_bad_symtab (abfd))
2961     {
2962       extsymcount = symcount;
2963       extsymoff = 0;
2964     }
2965   else
2966     {
2967       extsymcount = symcount - hdr->sh_info;
2968       extsymoff = hdr->sh_info;
2969     }
2970
2971   if (extsymcount == 0)
2972     return FALSE;
2973
2974   /* Read in the symbol table.  */
2975   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
2976                                   NULL, NULL, NULL);
2977   if (isymbuf == NULL)
2978     return FALSE;
2979
2980   /* Scan the symbol table looking for SYMDEF.  */
2981   result = FALSE;
2982   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
2983     {
2984       const char *name;
2985
2986       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
2987                                               isym->st_name);
2988       if (name == NULL)
2989         break;
2990
2991       if (strcmp (name, symdef->name) == 0)
2992         {
2993           result = is_global_data_symbol_definition (abfd, isym);
2994           break;
2995         }
2996     }
2997
2998   free (isymbuf);
2999
3000   return result;
3001 }
3002 \f
3003 /* Add an entry to the .dynamic table.  */
3004
3005 bfd_boolean
3006 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3007                             bfd_vma tag,
3008                             bfd_vma val)
3009 {
3010   struct elf_link_hash_table *hash_table;
3011   const struct elf_backend_data *bed;
3012   asection *s;
3013   bfd_size_type newsize;
3014   bfd_byte *newcontents;
3015   Elf_Internal_Dyn dyn;
3016
3017   hash_table = elf_hash_table (info);
3018   if (! is_elf_hash_table (hash_table))
3019     return FALSE;
3020
3021   bed = get_elf_backend_data (hash_table->dynobj);
3022   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3023   BFD_ASSERT (s != NULL);
3024
3025   newsize = s->size + bed->s->sizeof_dyn;
3026   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3027   if (newcontents == NULL)
3028     return FALSE;
3029
3030   dyn.d_tag = tag;
3031   dyn.d_un.d_val = val;
3032   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3033
3034   s->size = newsize;
3035   s->contents = newcontents;
3036
3037   return TRUE;
3038 }
3039
3040 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3041    otherwise just check whether one already exists.  Returns -1 on error,
3042    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3043
3044 static int
3045 elf_add_dt_needed_tag (bfd *abfd,
3046                        struct bfd_link_info *info,
3047                        const char *soname,
3048                        bfd_boolean do_it)
3049 {
3050   struct elf_link_hash_table *hash_table;
3051   bfd_size_type strindex;
3052
3053   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3054     return -1;
3055
3056   hash_table = elf_hash_table (info);
3057   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3058   if (strindex == (bfd_size_type) -1)
3059     return -1;
3060
3061   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3062     {
3063       asection *sdyn;
3064       const struct elf_backend_data *bed;
3065       bfd_byte *extdyn;
3066
3067       bed = get_elf_backend_data (hash_table->dynobj);
3068       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3069       if (sdyn != NULL)
3070         for (extdyn = sdyn->contents;
3071              extdyn < sdyn->contents + sdyn->size;
3072              extdyn += bed->s->sizeof_dyn)
3073           {
3074             Elf_Internal_Dyn dyn;
3075
3076             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3077             if (dyn.d_tag == DT_NEEDED
3078                 && dyn.d_un.d_val == strindex)
3079               {
3080                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3081                 return 1;
3082               }
3083           }
3084     }
3085
3086   if (do_it)
3087     {
3088       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3089         return -1;
3090
3091       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3092         return -1;
3093     }
3094   else
3095     /* We were just checking for existence of the tag.  */
3096     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3097
3098   return 0;
3099 }
3100
3101 static bfd_boolean
3102 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3103 {
3104   for (; needed != NULL; needed = needed->next)
3105     if ((elf_dyn_lib_class (needed->by) & DYN_AS_NEEDED) == 0
3106         && strcmp (soname, needed->name) == 0)
3107       return TRUE;
3108
3109   return FALSE;
3110 }
3111
3112 /* Sort symbol by value, section, and size.  */
3113 static int
3114 elf_sort_symbol (const void *arg1, const void *arg2)
3115 {
3116   const struct elf_link_hash_entry *h1;
3117   const struct elf_link_hash_entry *h2;
3118   bfd_signed_vma vdiff;
3119
3120   h1 = *(const struct elf_link_hash_entry **) arg1;
3121   h2 = *(const struct elf_link_hash_entry **) arg2;
3122   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3123   if (vdiff != 0)
3124     return vdiff > 0 ? 1 : -1;
3125   else
3126     {
3127       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3128       if (sdiff != 0)
3129         return sdiff > 0 ? 1 : -1;
3130     }
3131   vdiff = h1->size - h2->size;
3132   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3133 }
3134
3135 /* This function is used to adjust offsets into .dynstr for
3136    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3137
3138 static bfd_boolean
3139 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3140 {
3141   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3142
3143   if (h->dynindx != -1)
3144     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3145   return TRUE;
3146 }
3147
3148 /* Assign string offsets in .dynstr, update all structures referencing
3149    them.  */
3150
3151 static bfd_boolean
3152 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3153 {
3154   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3155   struct elf_link_local_dynamic_entry *entry;
3156   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3157   bfd *dynobj = hash_table->dynobj;
3158   asection *sdyn;
3159   bfd_size_type size;
3160   const struct elf_backend_data *bed;
3161   bfd_byte *extdyn;
3162
3163   _bfd_elf_strtab_finalize (dynstr);
3164   size = _bfd_elf_strtab_size (dynstr);
3165
3166   bed = get_elf_backend_data (dynobj);
3167   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3168   BFD_ASSERT (sdyn != NULL);
3169
3170   /* Update all .dynamic entries referencing .dynstr strings.  */
3171   for (extdyn = sdyn->contents;
3172        extdyn < sdyn->contents + sdyn->size;
3173        extdyn += bed->s->sizeof_dyn)
3174     {
3175       Elf_Internal_Dyn dyn;
3176
3177       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3178       switch (dyn.d_tag)
3179         {
3180         case DT_STRSZ:
3181           dyn.d_un.d_val = size;
3182           break;
3183         case DT_NEEDED:
3184         case DT_SONAME:
3185         case DT_RPATH:
3186         case DT_RUNPATH:
3187         case DT_FILTER:
3188         case DT_AUXILIARY:
3189         case DT_AUDIT:
3190         case DT_DEPAUDIT:
3191           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3192           break;
3193         default:
3194           continue;
3195         }
3196       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3197     }
3198
3199   /* Now update local dynamic symbols.  */
3200   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3201     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3202                                                   entry->isym.st_name);
3203
3204   /* And the rest of dynamic symbols.  */
3205   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3206
3207   /* Adjust version definitions.  */
3208   if (elf_tdata (output_bfd)->cverdefs)
3209     {
3210       asection *s;
3211       bfd_byte *p;
3212       bfd_size_type i;
3213       Elf_Internal_Verdef def;
3214       Elf_Internal_Verdaux defaux;
3215
3216       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3217       p = s->contents;
3218       do
3219         {
3220           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3221                                    &def);
3222           p += sizeof (Elf_External_Verdef);
3223           if (def.vd_aux != sizeof (Elf_External_Verdef))
3224             continue;
3225           for (i = 0; i < def.vd_cnt; ++i)
3226             {
3227               _bfd_elf_swap_verdaux_in (output_bfd,
3228                                         (Elf_External_Verdaux *) p, &defaux);
3229               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3230                                                         defaux.vda_name);
3231               _bfd_elf_swap_verdaux_out (output_bfd,
3232                                          &defaux, (Elf_External_Verdaux *) p);
3233               p += sizeof (Elf_External_Verdaux);
3234             }
3235         }
3236       while (def.vd_next);
3237     }
3238
3239   /* Adjust version references.  */
3240   if (elf_tdata (output_bfd)->verref)
3241     {
3242       asection *s;
3243       bfd_byte *p;
3244       bfd_size_type i;
3245       Elf_Internal_Verneed need;
3246       Elf_Internal_Vernaux needaux;
3247
3248       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3249       p = s->contents;
3250       do
3251         {
3252           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3253                                     &need);
3254           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3255           _bfd_elf_swap_verneed_out (output_bfd, &need,
3256                                      (Elf_External_Verneed *) p);
3257           p += sizeof (Elf_External_Verneed);
3258           for (i = 0; i < need.vn_cnt; ++i)
3259             {
3260               _bfd_elf_swap_vernaux_in (output_bfd,
3261                                         (Elf_External_Vernaux *) p, &needaux);
3262               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3263                                                          needaux.vna_name);
3264               _bfd_elf_swap_vernaux_out (output_bfd,
3265                                          &needaux,
3266                                          (Elf_External_Vernaux *) p);
3267               p += sizeof (Elf_External_Vernaux);
3268             }
3269         }
3270       while (need.vn_next);
3271     }
3272
3273   return TRUE;
3274 }
3275 \f
3276 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3277    The default is to only match when the INPUT and OUTPUT are exactly
3278    the same target.  */
3279
3280 bfd_boolean
3281 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3282                                     const bfd_target *output)
3283 {
3284   return input == output;
3285 }
3286
3287 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3288    This version is used when different targets for the same architecture
3289    are virtually identical.  */
3290
3291 bfd_boolean
3292 _bfd_elf_relocs_compatible (const bfd_target *input,
3293                             const bfd_target *output)
3294 {
3295   const struct elf_backend_data *obed, *ibed;
3296
3297   if (input == output)
3298     return TRUE;
3299
3300   ibed = xvec_get_elf_backend_data (input);
3301   obed = xvec_get_elf_backend_data (output);
3302
3303   if (ibed->arch != obed->arch)
3304     return FALSE;
3305
3306   /* If both backends are using this function, deem them compatible.  */
3307   return ibed->relocs_compatible == obed->relocs_compatible;
3308 }
3309
3310 /* Make a special call to the linker "notice" function to tell it that
3311    we are about to handle an as-needed lib, or have finished
3312    processing the lib.  */ 
3313
3314 bfd_boolean
3315 _bfd_elf_notice_as_needed (bfd *ibfd,
3316                            struct bfd_link_info *info,
3317                            enum notice_asneeded_action act)
3318 {
3319   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3320 }
3321
3322 /* Add symbols from an ELF object file to the linker hash table.  */
3323
3324 static bfd_boolean
3325 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3326 {
3327   Elf_Internal_Ehdr *ehdr;
3328   Elf_Internal_Shdr *hdr;
3329   bfd_size_type symcount;
3330   bfd_size_type extsymcount;
3331   bfd_size_type extsymoff;
3332   struct elf_link_hash_entry **sym_hash;
3333   bfd_boolean dynamic;
3334   Elf_External_Versym *extversym = NULL;
3335   Elf_External_Versym *ever;
3336   struct elf_link_hash_entry *weaks;
3337   struct elf_link_hash_entry **nondeflt_vers = NULL;
3338   bfd_size_type nondeflt_vers_cnt = 0;
3339   Elf_Internal_Sym *isymbuf = NULL;
3340   Elf_Internal_Sym *isym;
3341   Elf_Internal_Sym *isymend;
3342   const struct elf_backend_data *bed;
3343   bfd_boolean add_needed;
3344   struct elf_link_hash_table *htab;
3345   bfd_size_type amt;
3346   void *alloc_mark = NULL;
3347   struct bfd_hash_entry **old_table = NULL;
3348   unsigned int old_size = 0;
3349   unsigned int old_count = 0;
3350   void *old_tab = NULL;
3351   void *old_ent;
3352   struct bfd_link_hash_entry *old_undefs = NULL;
3353   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3354   long old_dynsymcount = 0;
3355   bfd_size_type old_dynstr_size = 0;
3356   size_t tabsize = 0;
3357   asection *s;
3358   bfd_boolean just_syms;
3359
3360   htab = elf_hash_table (info);
3361   bed = get_elf_backend_data (abfd);
3362
3363   if ((abfd->flags & DYNAMIC) == 0)
3364     dynamic = FALSE;
3365   else
3366     {
3367       dynamic = TRUE;
3368
3369       /* You can't use -r against a dynamic object.  Also, there's no
3370          hope of using a dynamic object which does not exactly match
3371          the format of the output file.  */
3372       if (info->relocatable
3373           || !is_elf_hash_table (htab)
3374           || info->output_bfd->xvec != abfd->xvec)
3375         {
3376           if (info->relocatable)
3377             bfd_set_error (bfd_error_invalid_operation);
3378           else
3379             bfd_set_error (bfd_error_wrong_format);
3380           goto error_return;
3381         }
3382     }
3383
3384   ehdr = elf_elfheader (abfd);
3385   if (info->warn_alternate_em
3386       && bed->elf_machine_code != ehdr->e_machine
3387       && ((bed->elf_machine_alt1 != 0
3388            && ehdr->e_machine == bed->elf_machine_alt1)
3389           || (bed->elf_machine_alt2 != 0
3390               && ehdr->e_machine == bed->elf_machine_alt2)))
3391     info->callbacks->einfo
3392       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3393        ehdr->e_machine, abfd, bed->elf_machine_code);
3394
3395   /* As a GNU extension, any input sections which are named
3396      .gnu.warning.SYMBOL are treated as warning symbols for the given
3397      symbol.  This differs from .gnu.warning sections, which generate
3398      warnings when they are included in an output file.  */
3399   /* PR 12761: Also generate this warning when building shared libraries.  */
3400   for (s = abfd->sections; s != NULL; s = s->next)
3401     {
3402       const char *name;
3403
3404       name = bfd_get_section_name (abfd, s);
3405       if (CONST_STRNEQ (name, ".gnu.warning."))
3406         {
3407           char *msg;
3408           bfd_size_type sz;
3409
3410           name += sizeof ".gnu.warning." - 1;
3411
3412           /* If this is a shared object, then look up the symbol
3413              in the hash table.  If it is there, and it is already
3414              been defined, then we will not be using the entry
3415              from this shared object, so we don't need to warn.
3416              FIXME: If we see the definition in a regular object
3417              later on, we will warn, but we shouldn't.  The only
3418              fix is to keep track of what warnings we are supposed
3419              to emit, and then handle them all at the end of the
3420              link.  */
3421           if (dynamic)
3422             {
3423               struct elf_link_hash_entry *h;
3424
3425               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3426
3427               /* FIXME: What about bfd_link_hash_common?  */
3428               if (h != NULL
3429                   && (h->root.type == bfd_link_hash_defined
3430                       || h->root.type == bfd_link_hash_defweak))
3431                 continue;
3432             }
3433
3434           sz = s->size;
3435           msg = (char *) bfd_alloc (abfd, sz + 1);
3436           if (msg == NULL)
3437             goto error_return;
3438
3439           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3440             goto error_return;
3441
3442           msg[sz] = '\0';
3443
3444           if (! (_bfd_generic_link_add_one_symbol
3445                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3446                   FALSE, bed->collect, NULL)))
3447             goto error_return;
3448
3449           if (!info->relocatable && info->executable)
3450             {
3451               /* Clobber the section size so that the warning does
3452                  not get copied into the output file.  */
3453               s->size = 0;
3454
3455               /* Also set SEC_EXCLUDE, so that symbols defined in
3456                  the warning section don't get copied to the output.  */
3457               s->flags |= SEC_EXCLUDE;
3458             }
3459         }
3460     }
3461
3462   just_syms = ((s = abfd->sections) != NULL
3463                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3464
3465   add_needed = TRUE;
3466   if (! dynamic)
3467     {
3468       /* If we are creating a shared library, create all the dynamic
3469          sections immediately.  We need to attach them to something,
3470          so we attach them to this BFD, provided it is the right
3471          format and is not from ld --just-symbols.  FIXME: If there
3472          are no input BFD's of the same format as the output, we can't
3473          make a shared library.  */
3474       if (!just_syms
3475           && info->shared
3476           && is_elf_hash_table (htab)
3477           && info->output_bfd->xvec == abfd->xvec
3478           && !htab->dynamic_sections_created)
3479         {
3480           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3481             goto error_return;
3482         }
3483     }
3484   else if (!is_elf_hash_table (htab))
3485     goto error_return;
3486   else
3487     {
3488       const char *soname = NULL;
3489       char *audit = NULL;
3490       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3491       int ret;
3492
3493       /* ld --just-symbols and dynamic objects don't mix very well.
3494          ld shouldn't allow it.  */
3495       if (just_syms)
3496         abort ();
3497
3498       /* If this dynamic lib was specified on the command line with
3499          --as-needed in effect, then we don't want to add a DT_NEEDED
3500          tag unless the lib is actually used.  Similary for libs brought
3501          in by another lib's DT_NEEDED.  When --no-add-needed is used
3502          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3503          any dynamic library in DT_NEEDED tags in the dynamic lib at
3504          all.  */
3505       add_needed = (elf_dyn_lib_class (abfd)
3506                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3507                        | DYN_NO_NEEDED)) == 0;
3508
3509       s = bfd_get_section_by_name (abfd, ".dynamic");
3510       if (s != NULL)
3511         {
3512           bfd_byte *dynbuf;
3513           bfd_byte *extdyn;
3514           unsigned int elfsec;
3515           unsigned long shlink;
3516
3517           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3518             {
3519 error_free_dyn:
3520               free (dynbuf);
3521               goto error_return;
3522             }
3523
3524           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3525           if (elfsec == SHN_BAD)
3526             goto error_free_dyn;
3527           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3528
3529           for (extdyn = dynbuf;
3530                extdyn < dynbuf + s->size;
3531                extdyn += bed->s->sizeof_dyn)
3532             {
3533               Elf_Internal_Dyn dyn;
3534
3535               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3536               if (dyn.d_tag == DT_SONAME)
3537                 {
3538                   unsigned int tagv = dyn.d_un.d_val;
3539                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3540                   if (soname == NULL)
3541                     goto error_free_dyn;
3542                 }
3543               if (dyn.d_tag == DT_NEEDED)
3544                 {
3545                   struct bfd_link_needed_list *n, **pn;
3546                   char *fnm, *anm;
3547                   unsigned int tagv = dyn.d_un.d_val;
3548
3549                   amt = sizeof (struct bfd_link_needed_list);
3550                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3551                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3552                   if (n == NULL || fnm == NULL)
3553                     goto error_free_dyn;
3554                   amt = strlen (fnm) + 1;
3555                   anm = (char *) bfd_alloc (abfd, amt);
3556                   if (anm == NULL)
3557                     goto error_free_dyn;
3558                   memcpy (anm, fnm, amt);
3559                   n->name = anm;
3560                   n->by = abfd;
3561                   n->next = NULL;
3562                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3563                     ;
3564                   *pn = n;
3565                 }
3566               if (dyn.d_tag == DT_RUNPATH)
3567                 {
3568                   struct bfd_link_needed_list *n, **pn;
3569                   char *fnm, *anm;
3570                   unsigned int tagv = dyn.d_un.d_val;
3571
3572                   amt = sizeof (struct bfd_link_needed_list);
3573                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3574                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3575                   if (n == NULL || fnm == NULL)
3576                     goto error_free_dyn;
3577                   amt = strlen (fnm) + 1;
3578                   anm = (char *) bfd_alloc (abfd, amt);
3579                   if (anm == NULL)
3580                     goto error_free_dyn;
3581                   memcpy (anm, fnm, amt);
3582                   n->name = anm;
3583                   n->by = abfd;
3584                   n->next = NULL;
3585                   for (pn = & runpath;
3586                        *pn != NULL;
3587                        pn = &(*pn)->next)
3588                     ;
3589                   *pn = n;
3590                 }
3591               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3592               if (!runpath && dyn.d_tag == DT_RPATH)
3593                 {
3594                   struct bfd_link_needed_list *n, **pn;
3595                   char *fnm, *anm;
3596                   unsigned int tagv = dyn.d_un.d_val;
3597
3598                   amt = sizeof (struct bfd_link_needed_list);
3599                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3600                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3601                   if (n == NULL || fnm == NULL)
3602                     goto error_free_dyn;
3603                   amt = strlen (fnm) + 1;
3604                   anm = (char *) bfd_alloc (abfd, amt);
3605                   if (anm == NULL)
3606                     goto error_free_dyn;
3607                   memcpy (anm, fnm, amt);
3608                   n->name = anm;
3609                   n->by = abfd;
3610                   n->next = NULL;
3611                   for (pn = & rpath;
3612                        *pn != NULL;
3613                        pn = &(*pn)->next)
3614                     ;
3615                   *pn = n;
3616                 }
3617               if (dyn.d_tag == DT_AUDIT)
3618                 {
3619                   unsigned int tagv = dyn.d_un.d_val;
3620                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3621                 }
3622             }
3623
3624           free (dynbuf);
3625         }
3626
3627       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3628          frees all more recently bfd_alloc'd blocks as well.  */
3629       if (runpath)
3630         rpath = runpath;
3631
3632       if (rpath)
3633         {
3634           struct bfd_link_needed_list **pn;
3635           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3636             ;
3637           *pn = rpath;
3638         }
3639
3640       /* We do not want to include any of the sections in a dynamic
3641          object in the output file.  We hack by simply clobbering the
3642          list of sections in the BFD.  This could be handled more
3643          cleanly by, say, a new section flag; the existing
3644          SEC_NEVER_LOAD flag is not the one we want, because that one
3645          still implies that the section takes up space in the output
3646          file.  */
3647       bfd_section_list_clear (abfd);
3648
3649       /* Find the name to use in a DT_NEEDED entry that refers to this
3650          object.  If the object has a DT_SONAME entry, we use it.
3651          Otherwise, if the generic linker stuck something in
3652          elf_dt_name, we use that.  Otherwise, we just use the file
3653          name.  */
3654       if (soname == NULL || *soname == '\0')
3655         {
3656           soname = elf_dt_name (abfd);
3657           if (soname == NULL || *soname == '\0')
3658             soname = bfd_get_filename (abfd);
3659         }
3660
3661       /* Save the SONAME because sometimes the linker emulation code
3662          will need to know it.  */
3663       elf_dt_name (abfd) = soname;
3664
3665       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3666       if (ret < 0)
3667         goto error_return;
3668
3669       /* If we have already included this dynamic object in the
3670          link, just ignore it.  There is no reason to include a
3671          particular dynamic object more than once.  */
3672       if (ret > 0)
3673         return TRUE;
3674
3675       /* Save the DT_AUDIT entry for the linker emulation code. */
3676       elf_dt_audit (abfd) = audit;
3677     }
3678
3679   /* If this is a dynamic object, we always link against the .dynsym
3680      symbol table, not the .symtab symbol table.  The dynamic linker
3681      will only see the .dynsym symbol table, so there is no reason to
3682      look at .symtab for a dynamic object.  */
3683
3684   if (! dynamic || elf_dynsymtab (abfd) == 0)
3685     hdr = &elf_tdata (abfd)->symtab_hdr;
3686   else
3687     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3688
3689   symcount = hdr->sh_size / bed->s->sizeof_sym;
3690
3691   /* The sh_info field of the symtab header tells us where the
3692      external symbols start.  We don't care about the local symbols at
3693      this point.  */
3694   if (elf_bad_symtab (abfd))
3695     {
3696       extsymcount = symcount;
3697       extsymoff = 0;
3698     }
3699   else
3700     {
3701       extsymcount = symcount - hdr->sh_info;
3702       extsymoff = hdr->sh_info;
3703     }
3704
3705   sym_hash = elf_sym_hashes (abfd);
3706   if (extsymcount != 0)
3707     {
3708       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3709                                       NULL, NULL, NULL);
3710       if (isymbuf == NULL)
3711         goto error_return;
3712
3713       if (sym_hash == NULL)
3714         {
3715           /* We store a pointer to the hash table entry for each
3716              external symbol.  */
3717           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3718           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3719           if (sym_hash == NULL)
3720             goto error_free_sym;
3721           elf_sym_hashes (abfd) = sym_hash;
3722         }
3723     }
3724
3725   if (dynamic)
3726     {
3727       /* Read in any version definitions.  */
3728       if (!_bfd_elf_slurp_version_tables (abfd,
3729                                           info->default_imported_symver))
3730         goto error_free_sym;
3731
3732       /* Read in the symbol versions, but don't bother to convert them
3733          to internal format.  */
3734       if (elf_dynversym (abfd) != 0)
3735         {
3736           Elf_Internal_Shdr *versymhdr;
3737
3738           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3739           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3740           if (extversym == NULL)
3741             goto error_free_sym;
3742           amt = versymhdr->sh_size;
3743           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3744               || bfd_bread (extversym, amt, abfd) != amt)
3745             goto error_free_vers;
3746         }
3747     }
3748
3749   /* If we are loading an as-needed shared lib, save the symbol table
3750      state before we start adding symbols.  If the lib turns out
3751      to be unneeded, restore the state.  */
3752   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3753     {
3754       unsigned int i;
3755       size_t entsize;
3756
3757       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3758         {
3759           struct bfd_hash_entry *p;
3760           struct elf_link_hash_entry *h;
3761
3762           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3763             {
3764               h = (struct elf_link_hash_entry *) p;
3765               entsize += htab->root.table.entsize;
3766               if (h->root.type == bfd_link_hash_warning)
3767                 entsize += htab->root.table.entsize;
3768             }
3769         }
3770
3771       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3772       old_tab = bfd_malloc (tabsize + entsize);
3773       if (old_tab == NULL)
3774         goto error_free_vers;
3775
3776       /* Remember the current objalloc pointer, so that all mem for
3777          symbols added can later be reclaimed.  */
3778       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3779       if (alloc_mark == NULL)
3780         goto error_free_vers;
3781
3782       /* Make a special call to the linker "notice" function to
3783          tell it that we are about to handle an as-needed lib.  */
3784       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
3785         goto error_free_vers;
3786
3787       /* Clone the symbol table.  Remember some pointers into the
3788          symbol table, and dynamic symbol count.  */
3789       old_ent = (char *) old_tab + tabsize;
3790       memcpy (old_tab, htab->root.table.table, tabsize);
3791       old_undefs = htab->root.undefs;
3792       old_undefs_tail = htab->root.undefs_tail;
3793       old_table = htab->root.table.table;
3794       old_size = htab->root.table.size;
3795       old_count = htab->root.table.count;
3796       old_dynsymcount = htab->dynsymcount;
3797       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
3798
3799       for (i = 0; i < htab->root.table.size; i++)
3800         {
3801           struct bfd_hash_entry *p;
3802           struct elf_link_hash_entry *h;
3803
3804           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3805             {
3806               memcpy (old_ent, p, htab->root.table.entsize);
3807               old_ent = (char *) old_ent + htab->root.table.entsize;
3808               h = (struct elf_link_hash_entry *) p;
3809               if (h->root.type == bfd_link_hash_warning)
3810                 {
3811                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3812                   old_ent = (char *) old_ent + htab->root.table.entsize;
3813                 }
3814             }
3815         }
3816     }
3817
3818   weaks = NULL;
3819   ever = extversym != NULL ? extversym + extsymoff : NULL;
3820   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3821        isym < isymend;
3822        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3823     {
3824       int bind;
3825       bfd_vma value;
3826       asection *sec, *new_sec;
3827       flagword flags;
3828       const char *name;
3829       struct elf_link_hash_entry *h;
3830       struct elf_link_hash_entry *hi;
3831       bfd_boolean definition;
3832       bfd_boolean size_change_ok;
3833       bfd_boolean type_change_ok;
3834       bfd_boolean new_weakdef;
3835       bfd_boolean new_weak;
3836       bfd_boolean old_weak;
3837       bfd_boolean override;
3838       bfd_boolean common;
3839       unsigned int old_alignment;
3840       bfd *old_bfd;
3841
3842       override = FALSE;
3843
3844       flags = BSF_NO_FLAGS;
3845       sec = NULL;
3846       value = isym->st_value;
3847       common = bed->common_definition (isym);
3848
3849       bind = ELF_ST_BIND (isym->st_info);
3850       switch (bind)
3851         {
3852         case STB_LOCAL:
3853           /* This should be impossible, since ELF requires that all
3854              global symbols follow all local symbols, and that sh_info
3855              point to the first global symbol.  Unfortunately, Irix 5
3856              screws this up.  */
3857           continue;
3858
3859         case STB_GLOBAL:
3860           if (isym->st_shndx != SHN_UNDEF && !common)
3861             flags = BSF_GLOBAL;
3862           break;
3863
3864         case STB_WEAK:
3865           flags = BSF_WEAK;
3866           break;
3867
3868         case STB_GNU_UNIQUE:
3869           flags = BSF_GNU_UNIQUE;
3870           break;
3871
3872         default:
3873           /* Leave it up to the processor backend.  */
3874           break;
3875         }
3876
3877       if (isym->st_shndx == SHN_UNDEF)
3878         sec = bfd_und_section_ptr;
3879       else if (isym->st_shndx == SHN_ABS)
3880         sec = bfd_abs_section_ptr;
3881       else if (isym->st_shndx == SHN_COMMON)
3882         {
3883           sec = bfd_com_section_ptr;
3884           /* What ELF calls the size we call the value.  What ELF
3885              calls the value we call the alignment.  */
3886           value = isym->st_size;
3887         }
3888       else
3889         {
3890           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3891           if (sec == NULL)
3892             sec = bfd_abs_section_ptr;
3893           else if (discarded_section (sec))
3894             {
3895               /* Symbols from discarded section are undefined.  We keep
3896                  its visibility.  */
3897               sec = bfd_und_section_ptr;
3898               isym->st_shndx = SHN_UNDEF;
3899             }
3900           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3901             value -= sec->vma;
3902         }
3903
3904       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3905                                               isym->st_name);
3906       if (name == NULL)
3907         goto error_free_vers;
3908
3909       if (isym->st_shndx == SHN_COMMON
3910           && (abfd->flags & BFD_PLUGIN) != 0)
3911         {
3912           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
3913
3914           if (xc == NULL)
3915             {
3916               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
3917                                  | SEC_EXCLUDE);
3918               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
3919               if (xc == NULL)
3920                 goto error_free_vers;
3921             }
3922           sec = xc;
3923         }
3924       else if (isym->st_shndx == SHN_COMMON
3925                && ELF_ST_TYPE (isym->st_info) == STT_TLS
3926                && !info->relocatable)
3927         {
3928           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
3929
3930           if (tcomm == NULL)
3931             {
3932               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
3933                                  | SEC_LINKER_CREATED);
3934               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
3935               if (tcomm == NULL)
3936                 goto error_free_vers;
3937             }
3938           sec = tcomm;
3939         }
3940       else if (bed->elf_add_symbol_hook)
3941         {
3942           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
3943                                              &sec, &value))
3944             goto error_free_vers;
3945
3946           /* The hook function sets the name to NULL if this symbol
3947              should be skipped for some reason.  */
3948           if (name == NULL)
3949             continue;
3950         }
3951
3952       /* Sanity check that all possibilities were handled.  */
3953       if (sec == NULL)
3954         {
3955           bfd_set_error (bfd_error_bad_value);
3956           goto error_free_vers;
3957         }
3958
3959       /* Silently discard TLS symbols from --just-syms.  There's
3960          no way to combine a static TLS block with a new TLS block
3961          for this executable.  */
3962       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
3963           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
3964         continue;
3965
3966       if (bfd_is_und_section (sec)
3967           || bfd_is_com_section (sec))
3968         definition = FALSE;
3969       else
3970         definition = TRUE;
3971
3972       size_change_ok = FALSE;
3973       type_change_ok = bed->type_change_ok;
3974       old_weak = FALSE;
3975       old_alignment = 0;
3976       old_bfd = NULL;
3977       new_sec = sec;
3978
3979       if (is_elf_hash_table (htab))
3980         {
3981           Elf_Internal_Versym iver;
3982           unsigned int vernum = 0;
3983           bfd_boolean skip;
3984
3985           if (ever == NULL)
3986             {
3987               if (info->default_imported_symver)
3988                 /* Use the default symbol version created earlier.  */
3989                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
3990               else
3991                 iver.vs_vers = 0;
3992             }
3993           else
3994             _bfd_elf_swap_versym_in (abfd, ever, &iver);
3995
3996           vernum = iver.vs_vers & VERSYM_VERSION;
3997
3998           /* If this is a hidden symbol, or if it is not version
3999              1, we append the version name to the symbol name.
4000              However, we do not modify a non-hidden absolute symbol
4001              if it is not a function, because it might be the version
4002              symbol itself.  FIXME: What if it isn't?  */
4003           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4004               || (vernum > 1
4005                   && (!bfd_is_abs_section (sec)
4006                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4007             {
4008               const char *verstr;
4009               size_t namelen, verlen, newlen;
4010               char *newname, *p;
4011
4012               if (isym->st_shndx != SHN_UNDEF)
4013                 {
4014                   if (vernum > elf_tdata (abfd)->cverdefs)
4015                     verstr = NULL;
4016                   else if (vernum > 1)
4017                     verstr =
4018                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4019                   else
4020                     verstr = "";
4021
4022                   if (verstr == NULL)
4023                     {
4024                       (*_bfd_error_handler)
4025                         (_("%B: %s: invalid version %u (max %d)"),
4026                          abfd, name, vernum,
4027                          elf_tdata (abfd)->cverdefs);
4028                       bfd_set_error (bfd_error_bad_value);
4029                       goto error_free_vers;
4030                     }
4031                 }
4032               else
4033                 {
4034                   /* We cannot simply test for the number of
4035                      entries in the VERNEED section since the
4036                      numbers for the needed versions do not start
4037                      at 0.  */
4038                   Elf_Internal_Verneed *t;
4039
4040                   verstr = NULL;
4041                   for (t = elf_tdata (abfd)->verref;
4042                        t != NULL;
4043                        t = t->vn_nextref)
4044                     {
4045                       Elf_Internal_Vernaux *a;
4046
4047                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4048                         {
4049                           if (a->vna_other == vernum)
4050                             {
4051                               verstr = a->vna_nodename;
4052                               break;
4053                             }
4054                         }
4055                       if (a != NULL)
4056                         break;
4057                     }
4058                   if (verstr == NULL)
4059                     {
4060                       (*_bfd_error_handler)
4061                         (_("%B: %s: invalid needed version %d"),
4062                          abfd, name, vernum);
4063                       bfd_set_error (bfd_error_bad_value);
4064                       goto error_free_vers;
4065                     }
4066                 }
4067
4068               namelen = strlen (name);
4069               verlen = strlen (verstr);
4070               newlen = namelen + verlen + 2;
4071               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4072                   && isym->st_shndx != SHN_UNDEF)
4073                 ++newlen;
4074
4075               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4076               if (newname == NULL)
4077                 goto error_free_vers;
4078               memcpy (newname, name, namelen);
4079               p = newname + namelen;
4080               *p++ = ELF_VER_CHR;
4081               /* If this is a defined non-hidden version symbol,
4082                  we add another @ to the name.  This indicates the
4083                  default version of the symbol.  */
4084               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4085                   && isym->st_shndx != SHN_UNDEF)
4086                 *p++ = ELF_VER_CHR;
4087               memcpy (p, verstr, verlen + 1);
4088
4089               name = newname;
4090             }
4091
4092           /* If this symbol has default visibility and the user has
4093              requested we not re-export it, then mark it as hidden.  */
4094           if (definition
4095               && !dynamic
4096               && (abfd->no_export
4097                   || (abfd->my_archive && abfd->my_archive->no_export))
4098               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4099             isym->st_other = (STV_HIDDEN
4100                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4101
4102           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4103                                       sym_hash, &old_bfd, &old_weak,
4104                                       &old_alignment, &skip, &override,
4105                                       &type_change_ok, &size_change_ok))
4106             goto error_free_vers;
4107
4108           if (skip)
4109             continue;
4110
4111           if (override)
4112             definition = FALSE;
4113
4114           h = *sym_hash;
4115           while (h->root.type == bfd_link_hash_indirect
4116                  || h->root.type == bfd_link_hash_warning)
4117             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4118
4119           if (elf_tdata (abfd)->verdef != NULL
4120               && vernum > 1
4121               && definition)
4122             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4123         }
4124
4125       if (! (_bfd_generic_link_add_one_symbol
4126              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4127               (struct bfd_link_hash_entry **) sym_hash)))
4128         goto error_free_vers;
4129
4130       h = *sym_hash;
4131       /* We need to make sure that indirect symbol dynamic flags are
4132          updated.  */
4133       hi = h;
4134       while (h->root.type == bfd_link_hash_indirect
4135              || h->root.type == bfd_link_hash_warning)
4136         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4137
4138       *sym_hash = h;
4139
4140       new_weak = (flags & BSF_WEAK) != 0;
4141       new_weakdef = FALSE;
4142       if (dynamic
4143           && definition
4144           && new_weak
4145           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4146           && is_elf_hash_table (htab)
4147           && h->u.weakdef == NULL)
4148         {
4149           /* Keep a list of all weak defined non function symbols from
4150              a dynamic object, using the weakdef field.  Later in this
4151              function we will set the weakdef field to the correct
4152              value.  We only put non-function symbols from dynamic
4153              objects on this list, because that happens to be the only
4154              time we need to know the normal symbol corresponding to a
4155              weak symbol, and the information is time consuming to
4156              figure out.  If the weakdef field is not already NULL,
4157              then this symbol was already defined by some previous
4158              dynamic object, and we will be using that previous
4159              definition anyhow.  */
4160
4161           h->u.weakdef = weaks;
4162           weaks = h;
4163           new_weakdef = TRUE;
4164         }
4165
4166       /* Set the alignment of a common symbol.  */
4167       if ((common || bfd_is_com_section (sec))
4168           && h->root.type == bfd_link_hash_common)
4169         {
4170           unsigned int align;
4171
4172           if (common)
4173             align = bfd_log2 (isym->st_value);
4174           else
4175             {
4176               /* The new symbol is a common symbol in a shared object.
4177                  We need to get the alignment from the section.  */
4178               align = new_sec->alignment_power;
4179             }
4180           if (align > old_alignment)
4181             h->root.u.c.p->alignment_power = align;
4182           else
4183             h->root.u.c.p->alignment_power = old_alignment;
4184         }
4185
4186       if (is_elf_hash_table (htab))
4187         {
4188           /* Set a flag in the hash table entry indicating the type of
4189              reference or definition we just found.  A dynamic symbol
4190              is one which is referenced or defined by both a regular
4191              object and a shared object.  */
4192           bfd_boolean dynsym = FALSE;
4193
4194           /* Plugin symbols aren't normal.  Don't set def_regular or
4195              ref_regular for them, or make them dynamic.  */
4196           if ((abfd->flags & BFD_PLUGIN) != 0)
4197             ;
4198           else if (! dynamic)
4199             {
4200               if (! definition)
4201                 {
4202                   h->ref_regular = 1;
4203                   if (bind != STB_WEAK)
4204                     h->ref_regular_nonweak = 1;
4205                 }
4206               else
4207                 {
4208                   h->def_regular = 1;
4209                   if (h->def_dynamic)
4210                     {
4211                       h->def_dynamic = 0;
4212                       h->ref_dynamic = 1;
4213                     }
4214                 }
4215
4216               /* If the indirect symbol has been forced local, don't
4217                  make the real symbol dynamic.  */
4218               if ((h == hi || !hi->forced_local)
4219                   && (! info->executable
4220                       || h->def_dynamic
4221                       || h->ref_dynamic))
4222                 dynsym = TRUE;
4223             }
4224           else
4225             {
4226               if (! definition)
4227                 {
4228                   h->ref_dynamic = 1;
4229                   hi->ref_dynamic = 1;
4230                 }
4231               else
4232                 {
4233                   h->def_dynamic = 1;
4234                   hi->def_dynamic = 1;
4235                 }
4236
4237               /* If the indirect symbol has been forced local, don't
4238                  make the real symbol dynamic.  */
4239               if ((h == hi || !hi->forced_local)
4240                   && (h->def_regular
4241                       || h->ref_regular
4242                       || (h->u.weakdef != NULL
4243                           && ! new_weakdef
4244                           && h->u.weakdef->dynindx != -1)))
4245                 dynsym = TRUE;
4246             }
4247
4248           /* Check to see if we need to add an indirect symbol for
4249              the default name.  */
4250           if (definition
4251               || (!override && h->root.type == bfd_link_hash_common))
4252             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4253                                               sec, value, &old_bfd, &dynsym))
4254               goto error_free_vers;
4255
4256           /* Check the alignment when a common symbol is involved. This
4257              can change when a common symbol is overridden by a normal
4258              definition or a common symbol is ignored due to the old
4259              normal definition. We need to make sure the maximum
4260              alignment is maintained.  */
4261           if ((old_alignment || common)
4262               && h->root.type != bfd_link_hash_common)
4263             {
4264               unsigned int common_align;
4265               unsigned int normal_align;
4266               unsigned int symbol_align;
4267               bfd *normal_bfd;
4268               bfd *common_bfd;
4269
4270               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4271                           || h->root.type == bfd_link_hash_defweak);
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 is"
4303                          " 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
4317               && isym->st_shndx != SHN_UNDEF
4318               && (definition || h->size == 0))
4319             {
4320               if (h->size != 0
4321                   && h->size != isym->st_size
4322                   && ! size_change_ok)
4323                 (*_bfd_error_handler)
4324                   (_("Warning: size of symbol `%s' changed"
4325                      " from %lu in %B to %lu in %B"),
4326                    old_bfd, abfd,
4327                    name, (unsigned long) h->size,
4328                    (unsigned long) isym->st_size);
4329
4330               h->size = isym->st_size;
4331             }
4332
4333           /* If this is a common symbol, then we always want H->SIZE
4334              to be the size of the common symbol.  The code just above
4335              won't fix the size if a common symbol becomes larger.  We
4336              don't warn about a size change here, because that is
4337              covered by --warn-common.  Allow changes between different
4338              function types.  */
4339           if (h->root.type == bfd_link_hash_common)
4340             h->size = h->root.u.c.size;
4341
4342           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4343               && ((definition && !new_weak)
4344                   || (old_weak && h->root.type == bfd_link_hash_common)
4345                   || h->type == STT_NOTYPE))
4346             {
4347               unsigned int type = ELF_ST_TYPE (isym->st_info);
4348
4349               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4350                  symbol.  */
4351               if (type == STT_GNU_IFUNC
4352                   && (abfd->flags & DYNAMIC) != 0)
4353                 type = STT_FUNC;
4354
4355               if (h->type != type)
4356                 {
4357                   if (h->type != STT_NOTYPE && ! type_change_ok)
4358                     (*_bfd_error_handler)
4359                       (_("Warning: type of symbol `%s' changed"
4360                          " from %d to %d in %B"),
4361                        abfd, name, h->type, type);
4362
4363                   h->type = type;
4364                 }
4365             }
4366
4367           /* Merge st_other field.  */
4368           elf_merge_st_other (abfd, h, isym, definition, dynamic);
4369
4370           /* We don't want to make debug symbol dynamic.  */
4371           if (definition && (sec->flags & SEC_DEBUGGING) && !info->relocatable)
4372             dynsym = FALSE;
4373
4374           /* Nor should we make plugin symbols dynamic.  */
4375           if ((abfd->flags & BFD_PLUGIN) != 0)
4376             dynsym = FALSE;
4377
4378           if (definition)
4379             {
4380               h->target_internal = isym->st_target_internal;
4381               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4382             }
4383
4384           if (definition && !dynamic)
4385             {
4386               char *p = strchr (name, ELF_VER_CHR);
4387               if (p != NULL && p[1] != ELF_VER_CHR)
4388                 {
4389                   /* Queue non-default versions so that .symver x, x@FOO
4390                      aliases can be checked.  */
4391                   if (!nondeflt_vers)
4392                     {
4393                       amt = ((isymend - isym + 1)
4394                              * sizeof (struct elf_link_hash_entry *));
4395                       nondeflt_vers =
4396                           (struct elf_link_hash_entry **) bfd_malloc (amt);
4397                       if (!nondeflt_vers)
4398                         goto error_free_vers;
4399                     }
4400                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4401                 }
4402             }
4403
4404           if (dynsym && h->dynindx == -1)
4405             {
4406               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4407                 goto error_free_vers;
4408               if (h->u.weakdef != NULL
4409                   && ! new_weakdef
4410                   && h->u.weakdef->dynindx == -1)
4411                 {
4412                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4413                     goto error_free_vers;
4414                 }
4415             }
4416           else if (dynsym && h->dynindx != -1)
4417             /* If the symbol already has a dynamic index, but
4418                visibility says it should not be visible, turn it into
4419                a local symbol.  */
4420             switch (ELF_ST_VISIBILITY (h->other))
4421               {
4422               case STV_INTERNAL:
4423               case STV_HIDDEN:
4424                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4425                 dynsym = FALSE;
4426                 break;
4427               }
4428
4429           /* Don't add DT_NEEDED for references from the dummy bfd.  */
4430           if (!add_needed
4431               && definition
4432               && ((dynsym
4433                    && h->ref_regular_nonweak
4434                    && (old_bfd == NULL
4435                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4436                   || (h->ref_dynamic_nonweak
4437                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4438                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4439             {
4440               int ret;
4441               const char *soname = elf_dt_name (abfd);
4442
4443               info->callbacks->minfo ("%!", soname, old_bfd,
4444                                       h->root.root.string);
4445
4446               /* A symbol from a library loaded via DT_NEEDED of some
4447                  other library is referenced by a regular object.
4448                  Add a DT_NEEDED entry for it.  Issue an error if
4449                  --no-add-needed is used and the reference was not
4450                  a weak one.  */
4451               if (old_bfd != NULL
4452                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4453                 {
4454                   (*_bfd_error_handler)
4455                     (_("%B: undefined reference to symbol '%s'"),
4456                      old_bfd, name);
4457                   bfd_set_error (bfd_error_missing_dso);
4458                   goto error_free_vers;
4459                 }
4460
4461               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4462                   (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4463
4464               add_needed = TRUE;
4465               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4466               if (ret < 0)
4467                 goto error_free_vers;
4468
4469               BFD_ASSERT (ret == 0);
4470             }
4471         }
4472     }
4473
4474   if (extversym != NULL)
4475     {
4476       free (extversym);
4477       extversym = NULL;
4478     }
4479
4480   if (isymbuf != NULL)
4481     {
4482       free (isymbuf);
4483       isymbuf = NULL;
4484     }
4485
4486   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4487     {
4488       unsigned int i;
4489
4490       /* Restore the symbol table.  */
4491       old_ent = (char *) old_tab + tabsize;
4492       memset (elf_sym_hashes (abfd), 0,
4493               extsymcount * sizeof (struct elf_link_hash_entry *));
4494       htab->root.table.table = old_table;
4495       htab->root.table.size = old_size;
4496       htab->root.table.count = old_count;
4497       memcpy (htab->root.table.table, old_tab, tabsize);
4498       htab->root.undefs = old_undefs;
4499       htab->root.undefs_tail = old_undefs_tail;
4500       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4501       for (i = 0; i < htab->root.table.size; i++)
4502         {
4503           struct bfd_hash_entry *p;
4504           struct elf_link_hash_entry *h;
4505           bfd_size_type size;
4506           unsigned int alignment_power;
4507
4508           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4509             {
4510               h = (struct elf_link_hash_entry *) p;
4511               if (h->root.type == bfd_link_hash_warning)
4512                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4513               if (h->dynindx >= old_dynsymcount
4514                   && h->dynstr_index < old_dynstr_size)
4515                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4516
4517               /* Preserve the maximum alignment and size for common
4518                  symbols even if this dynamic lib isn't on DT_NEEDED
4519                  since it can still be loaded at run time by another
4520                  dynamic lib.  */
4521               if (h->root.type == bfd_link_hash_common)
4522                 {
4523                   size = h->root.u.c.size;
4524                   alignment_power = h->root.u.c.p->alignment_power;
4525                 }
4526               else
4527                 {
4528                   size = 0;
4529                   alignment_power = 0;
4530                 }
4531               memcpy (p, old_ent, htab->root.table.entsize);
4532               old_ent = (char *) old_ent + htab->root.table.entsize;
4533               h = (struct elf_link_hash_entry *) p;
4534               if (h->root.type == bfd_link_hash_warning)
4535                 {
4536                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4537                   old_ent = (char *) old_ent + htab->root.table.entsize;
4538                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4539                 }
4540               if (h->root.type == bfd_link_hash_common)
4541                 {
4542                   if (size > h->root.u.c.size)
4543                     h->root.u.c.size = size;
4544                   if (alignment_power > h->root.u.c.p->alignment_power)
4545                     h->root.u.c.p->alignment_power = alignment_power;
4546                 }
4547             }
4548         }
4549
4550       /* Make a special call to the linker "notice" function to
4551          tell it that symbols added for crefs may need to be removed.  */
4552       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4553         goto error_free_vers;
4554
4555       free (old_tab);
4556       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4557                            alloc_mark);
4558       if (nondeflt_vers != NULL)
4559         free (nondeflt_vers);
4560       return TRUE;
4561     }
4562
4563   if (old_tab != NULL)
4564     {
4565       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4566         goto error_free_vers;
4567       free (old_tab);
4568       old_tab = NULL;
4569     }
4570
4571   /* Now that all the symbols from this input file are created, handle
4572      .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4573   if (nondeflt_vers != NULL)
4574     {
4575       bfd_size_type cnt, symidx;
4576
4577       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4578         {
4579           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4580           char *shortname, *p;
4581
4582           p = strchr (h->root.root.string, ELF_VER_CHR);
4583           if (p == NULL
4584               || (h->root.type != bfd_link_hash_defined
4585                   && h->root.type != bfd_link_hash_defweak))
4586             continue;
4587
4588           amt = p - h->root.root.string;
4589           shortname = (char *) bfd_malloc (amt + 1);
4590           if (!shortname)
4591             goto error_free_vers;
4592           memcpy (shortname, h->root.root.string, amt);
4593           shortname[amt] = '\0';
4594
4595           hi = (struct elf_link_hash_entry *)
4596                bfd_link_hash_lookup (&htab->root, shortname,
4597                                      FALSE, FALSE, FALSE);
4598           if (hi != NULL
4599               && hi->root.type == h->root.type
4600               && hi->root.u.def.value == h->root.u.def.value
4601               && hi->root.u.def.section == h->root.u.def.section)
4602             {
4603               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4604               hi->root.type = bfd_link_hash_indirect;
4605               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4606               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4607               sym_hash = elf_sym_hashes (abfd);
4608               if (sym_hash)
4609                 for (symidx = 0; symidx < extsymcount; ++symidx)
4610                   if (sym_hash[symidx] == hi)
4611                     {
4612                       sym_hash[symidx] = h;
4613                       break;
4614                     }
4615             }
4616           free (shortname);
4617         }
4618       free (nondeflt_vers);
4619       nondeflt_vers = NULL;
4620     }
4621
4622   /* Now set the weakdefs field correctly for all the weak defined
4623      symbols we found.  The only way to do this is to search all the
4624      symbols.  Since we only need the information for non functions in
4625      dynamic objects, that's the only time we actually put anything on
4626      the list WEAKS.  We need this information so that if a regular
4627      object refers to a symbol defined weakly in a dynamic object, the
4628      real symbol in the dynamic object is also put in the dynamic
4629      symbols; we also must arrange for both symbols to point to the
4630      same memory location.  We could handle the general case of symbol
4631      aliasing, but a general symbol alias can only be generated in
4632      assembler code, handling it correctly would be very time
4633      consuming, and other ELF linkers don't handle general aliasing
4634      either.  */
4635   if (weaks != NULL)
4636     {
4637       struct elf_link_hash_entry **hpp;
4638       struct elf_link_hash_entry **hppend;
4639       struct elf_link_hash_entry **sorted_sym_hash;
4640       struct elf_link_hash_entry *h;
4641       size_t sym_count;
4642
4643       /* Since we have to search the whole symbol list for each weak
4644          defined symbol, search time for N weak defined symbols will be
4645          O(N^2). Binary search will cut it down to O(NlogN).  */
4646       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4647       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4648       if (sorted_sym_hash == NULL)
4649         goto error_return;
4650       sym_hash = sorted_sym_hash;
4651       hpp = elf_sym_hashes (abfd);
4652       hppend = hpp + extsymcount;
4653       sym_count = 0;
4654       for (; hpp < hppend; hpp++)
4655         {
4656           h = *hpp;
4657           if (h != NULL
4658               && h->root.type == bfd_link_hash_defined
4659               && !bed->is_function_type (h->type))
4660             {
4661               *sym_hash = h;
4662               sym_hash++;
4663               sym_count++;
4664             }
4665         }
4666
4667       qsort (sorted_sym_hash, sym_count,
4668              sizeof (struct elf_link_hash_entry *),
4669              elf_sort_symbol);
4670
4671       while (weaks != NULL)
4672         {
4673           struct elf_link_hash_entry *hlook;
4674           asection *slook;
4675           bfd_vma vlook;
4676           size_t i, j, idx = 0;
4677
4678           hlook = weaks;
4679           weaks = hlook->u.weakdef;
4680           hlook->u.weakdef = NULL;
4681
4682           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4683                       || hlook->root.type == bfd_link_hash_defweak
4684                       || hlook->root.type == bfd_link_hash_common
4685                       || hlook->root.type == bfd_link_hash_indirect);
4686           slook = hlook->root.u.def.section;
4687           vlook = hlook->root.u.def.value;
4688
4689           i = 0;
4690           j = sym_count;
4691           while (i != j)
4692             {
4693               bfd_signed_vma vdiff;
4694               idx = (i + j) / 2;
4695               h = sorted_sym_hash[idx];
4696               vdiff = vlook - h->root.u.def.value;
4697               if (vdiff < 0)
4698                 j = idx;
4699               else if (vdiff > 0)
4700                 i = idx + 1;
4701               else
4702                 {
4703                   long sdiff = slook->id - h->root.u.def.section->id;
4704                   if (sdiff < 0)
4705                     j = idx;
4706                   else if (sdiff > 0)
4707                     i = idx + 1;
4708                   else
4709                     break;
4710                 }
4711             }
4712
4713           /* We didn't find a value/section match.  */
4714           if (i == j)
4715             continue;
4716
4717           /* With multiple aliases, or when the weak symbol is already
4718              strongly defined, we have multiple matching symbols and
4719              the binary search above may land on any of them.  Step
4720              one past the matching symbol(s).  */
4721           while (++idx != j)
4722             {
4723               h = sorted_sym_hash[idx];
4724               if (h->root.u.def.section != slook
4725                   || h->root.u.def.value != vlook)
4726                 break;
4727             }
4728
4729           /* Now look back over the aliases.  Since we sorted by size
4730              as well as value and section, we'll choose the one with
4731              the largest size.  */
4732           while (idx-- != i)
4733             {
4734               h = sorted_sym_hash[idx];
4735
4736               /* Stop if value or section doesn't match.  */
4737               if (h->root.u.def.section != slook
4738                   || h->root.u.def.value != vlook)
4739                 break;
4740               else if (h != hlook)
4741                 {
4742                   hlook->u.weakdef = h;
4743
4744                   /* If the weak definition is in the list of dynamic
4745                      symbols, make sure the real definition is put
4746                      there as well.  */
4747                   if (hlook->dynindx != -1 && h->dynindx == -1)
4748                     {
4749                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4750                         {
4751                         err_free_sym_hash:
4752                           free (sorted_sym_hash);
4753                           goto error_return;
4754                         }
4755                     }
4756
4757                   /* If the real definition is in the list of dynamic
4758                      symbols, make sure the weak definition is put
4759                      there as well.  If we don't do this, then the
4760                      dynamic loader might not merge the entries for the
4761                      real definition and the weak definition.  */
4762                   if (h->dynindx != -1 && hlook->dynindx == -1)
4763                     {
4764                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4765                         goto err_free_sym_hash;
4766                     }
4767                   break;
4768                 }
4769             }
4770         }
4771
4772       free (sorted_sym_hash);
4773     }
4774
4775   if (bed->check_directives
4776       && !(*bed->check_directives) (abfd, info))
4777     return FALSE;
4778
4779   /* If this object is the same format as the output object, and it is
4780      not a shared library, then let the backend look through the
4781      relocs.
4782
4783      This is required to build global offset table entries and to
4784      arrange for dynamic relocs.  It is not required for the
4785      particular common case of linking non PIC code, even when linking
4786      against shared libraries, but unfortunately there is no way of
4787      knowing whether an object file has been compiled PIC or not.
4788      Looking through the relocs is not particularly time consuming.
4789      The problem is that we must either (1) keep the relocs in memory,
4790      which causes the linker to require additional runtime memory or
4791      (2) read the relocs twice from the input file, which wastes time.
4792      This would be a good case for using mmap.
4793
4794      I have no idea how to handle linking PIC code into a file of a
4795      different format.  It probably can't be done.  */
4796   if (! dynamic
4797       && is_elf_hash_table (htab)
4798       && bed->check_relocs != NULL
4799       && elf_object_id (abfd) == elf_hash_table_id (htab)
4800       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4801     {
4802       asection *o;
4803
4804       for (o = abfd->sections; o != NULL; o = o->next)
4805         {
4806           Elf_Internal_Rela *internal_relocs;
4807           bfd_boolean ok;
4808
4809           if ((o->flags & SEC_RELOC) == 0
4810               || o->reloc_count == 0
4811               || ((info->strip == strip_all || info->strip == strip_debugger)
4812                   && (o->flags & SEC_DEBUGGING) != 0)
4813               || bfd_is_abs_section (o->output_section))
4814             continue;
4815
4816           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4817                                                        info->keep_memory);
4818           if (internal_relocs == NULL)
4819             goto error_return;
4820
4821           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4822
4823           if (elf_section_data (o)->relocs != internal_relocs)
4824             free (internal_relocs);
4825
4826           if (! ok)
4827             goto error_return;
4828         }
4829     }
4830
4831   /* If this is a non-traditional link, try to optimize the handling
4832      of the .stab/.stabstr sections.  */
4833   if (! dynamic
4834       && ! info->traditional_format
4835       && is_elf_hash_table (htab)
4836       && (info->strip != strip_all && info->strip != strip_debugger))
4837     {
4838       asection *stabstr;
4839
4840       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4841       if (stabstr != NULL)
4842         {
4843           bfd_size_type string_offset = 0;
4844           asection *stab;
4845
4846           for (stab = abfd->sections; stab; stab = stab->next)
4847             if (CONST_STRNEQ (stab->name, ".stab")
4848                 && (!stab->name[5] ||
4849                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4850                 && (stab->flags & SEC_MERGE) == 0
4851                 && !bfd_is_abs_section (stab->output_section))
4852               {
4853                 struct bfd_elf_section_data *secdata;
4854
4855                 secdata = elf_section_data (stab);
4856                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4857                                                stabstr, &secdata->sec_info,
4858                                                &string_offset))
4859                   goto error_return;
4860                 if (secdata->sec_info)
4861                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
4862             }
4863         }
4864     }
4865
4866   if (is_elf_hash_table (htab) && add_needed)
4867     {
4868       /* Add this bfd to the loaded list.  */
4869       struct elf_link_loaded_list *n;
4870
4871       n = (struct elf_link_loaded_list *)
4872           bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4873       if (n == NULL)
4874         goto error_return;
4875       n->abfd = abfd;
4876       n->next = htab->loaded;
4877       htab->loaded = n;
4878     }
4879
4880   return TRUE;
4881
4882  error_free_vers:
4883   if (old_tab != NULL)
4884     free (old_tab);
4885   if (nondeflt_vers != NULL)
4886     free (nondeflt_vers);
4887   if (extversym != NULL)
4888     free (extversym);
4889  error_free_sym:
4890   if (isymbuf != NULL)
4891     free (isymbuf);
4892  error_return:
4893   return FALSE;
4894 }
4895
4896 /* Return the linker hash table entry of a symbol that might be
4897    satisfied by an archive symbol.  Return -1 on error.  */
4898
4899 struct elf_link_hash_entry *
4900 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4901                                 struct bfd_link_info *info,
4902                                 const char *name)
4903 {
4904   struct elf_link_hash_entry *h;
4905   char *p, *copy;
4906   size_t len, first;
4907
4908   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
4909   if (h != NULL)
4910     return h;
4911
4912   /* If this is a default version (the name contains @@), look up the
4913      symbol again with only one `@' as well as without the version.
4914      The effect is that references to the symbol with and without the
4915      version will be matched by the default symbol in the archive.  */
4916
4917   p = strchr (name, ELF_VER_CHR);
4918   if (p == NULL || p[1] != ELF_VER_CHR)
4919     return h;
4920
4921   /* First check with only one `@'.  */
4922   len = strlen (name);
4923   copy = (char *) bfd_alloc (abfd, len);
4924   if (copy == NULL)
4925     return (struct elf_link_hash_entry *) 0 - 1;
4926
4927   first = p - name + 1;
4928   memcpy (copy, name, first);
4929   memcpy (copy + first, name + first + 1, len - first);
4930
4931   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
4932   if (h == NULL)
4933     {
4934       /* We also need to check references to the symbol without the
4935          version.  */
4936       copy[first - 1] = '\0';
4937       h = elf_link_hash_lookup (elf_hash_table (info), copy,
4938                                 FALSE, FALSE, TRUE);
4939     }
4940
4941   bfd_release (abfd, copy);
4942   return h;
4943 }
4944
4945 /* Add symbols from an ELF archive file to the linker hash table.  We
4946    don't use _bfd_generic_link_add_archive_symbols because we need to
4947    handle versioned symbols.
4948
4949    Fortunately, ELF archive handling is simpler than that done by
4950    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4951    oddities.  In ELF, if we find a symbol in the archive map, and the
4952    symbol is currently undefined, we know that we must pull in that
4953    object file.
4954
4955    Unfortunately, we do have to make multiple passes over the symbol
4956    table until nothing further is resolved.  */
4957
4958 static bfd_boolean
4959 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4960 {
4961   symindex c;
4962   unsigned char *included = NULL;
4963   carsym *symdefs;
4964   bfd_boolean loop;
4965   bfd_size_type amt;
4966   const struct elf_backend_data *bed;
4967   struct elf_link_hash_entry * (*archive_symbol_lookup)
4968     (bfd *, struct bfd_link_info *, const char *);
4969
4970   if (! bfd_has_map (abfd))
4971     {
4972       /* An empty archive is a special case.  */
4973       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4974         return TRUE;
4975       bfd_set_error (bfd_error_no_armap);
4976       return FALSE;
4977     }
4978
4979   /* Keep track of all symbols we know to be already defined, and all
4980      files we know to be already included.  This is to speed up the
4981      second and subsequent passes.  */
4982   c = bfd_ardata (abfd)->symdef_count;
4983   if (c == 0)
4984     return TRUE;
4985   amt = c;
4986   amt *= sizeof (*included);
4987   included = (unsigned char *) bfd_zmalloc (amt);
4988   if (included == NULL)
4989     return FALSE;
4990
4991   symdefs = bfd_ardata (abfd)->symdefs;
4992   bed = get_elf_backend_data (abfd);
4993   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
4994
4995   do
4996     {
4997       file_ptr last;
4998       symindex i;
4999       carsym *symdef;
5000       carsym *symdefend;
5001
5002       loop = FALSE;
5003       last = -1;
5004
5005       symdef = symdefs;
5006       symdefend = symdef + c;
5007       for (i = 0; symdef < symdefend; symdef++, i++)
5008         {
5009           struct elf_link_hash_entry *h;
5010           bfd *element;
5011           struct bfd_link_hash_entry *undefs_tail;
5012           symindex mark;
5013
5014           if (included[i])
5015             continue;
5016           if (symdef->file_offset == last)
5017             {
5018               included[i] = TRUE;
5019               continue;
5020             }
5021
5022           h = archive_symbol_lookup (abfd, info, symdef->name);
5023           if (h == (struct elf_link_hash_entry *) 0 - 1)
5024             goto error_return;
5025
5026           if (h == NULL)
5027             continue;
5028
5029           if (h->root.type == bfd_link_hash_common)
5030             {
5031               /* We currently have a common symbol.  The archive map contains
5032                  a reference to this symbol, so we may want to include it.  We
5033                  only want to include it however, if this archive element
5034                  contains a definition of the symbol, not just another common
5035                  declaration of it.
5036
5037                  Unfortunately some archivers (including GNU ar) will put
5038                  declarations of common symbols into their archive maps, as
5039                  well as real definitions, so we cannot just go by the archive
5040                  map alone.  Instead we must read in the element's symbol
5041                  table and check that to see what kind of symbol definition
5042                  this is.  */
5043               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5044                 continue;
5045             }
5046           else if (h->root.type != bfd_link_hash_undefined)
5047             {
5048               if (h->root.type != bfd_link_hash_undefweak)
5049                 /* Symbol must be defined.  Don't check it again.  */
5050                 included[i] = TRUE;
5051               continue;
5052             }
5053
5054           /* We need to include this archive member.  */
5055           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5056           if (element == NULL)
5057             goto error_return;
5058
5059           if (! bfd_check_format (element, bfd_object))
5060             goto error_return;
5061
5062           undefs_tail = info->hash->undefs_tail;
5063
5064           if (!(*info->callbacks
5065                 ->add_archive_element) (info, element, symdef->name, &element))
5066             goto error_return;
5067           if (!bfd_link_add_symbols (element, info))
5068             goto error_return;
5069
5070           /* If there are any new undefined symbols, we need to make
5071              another pass through the archive in order to see whether
5072              they can be defined.  FIXME: This isn't perfect, because
5073              common symbols wind up on undefs_tail and because an
5074              undefined symbol which is defined later on in this pass
5075              does not require another pass.  This isn't a bug, but it
5076              does make the code less efficient than it could be.  */
5077           if (undefs_tail != info->hash->undefs_tail)
5078             loop = TRUE;
5079
5080           /* Look backward to mark all symbols from this object file
5081              which we have already seen in this pass.  */
5082           mark = i;
5083           do
5084             {
5085               included[mark] = TRUE;
5086               if (mark == 0)
5087                 break;
5088               --mark;
5089             }
5090           while (symdefs[mark].file_offset == symdef->file_offset);
5091
5092           /* We mark subsequent symbols from this object file as we go
5093              on through the loop.  */
5094           last = symdef->file_offset;
5095         }
5096     }
5097   while (loop);
5098
5099   free (included);
5100
5101   return TRUE;
5102
5103  error_return:
5104   if (included != NULL)
5105     free (included);
5106   return FALSE;
5107 }
5108
5109 /* Given an ELF BFD, add symbols to the global hash table as
5110    appropriate.  */
5111
5112 bfd_boolean
5113 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5114 {
5115   switch (bfd_get_format (abfd))
5116     {
5117     case bfd_object:
5118       return elf_link_add_object_symbols (abfd, info);
5119     case bfd_archive:
5120       return elf_link_add_archive_symbols (abfd, info);
5121     default:
5122       bfd_set_error (bfd_error_wrong_format);
5123       return FALSE;
5124     }
5125 }
5126 \f
5127 struct hash_codes_info
5128 {
5129   unsigned long *hashcodes;
5130   bfd_boolean error;
5131 };
5132
5133 /* This function will be called though elf_link_hash_traverse to store
5134    all hash value of the exported symbols in an array.  */
5135
5136 static bfd_boolean
5137 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5138 {
5139   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5140   const char *name;
5141   char *p;
5142   unsigned long ha;
5143   char *alc = NULL;
5144
5145   /* Ignore indirect symbols.  These are added by the versioning code.  */
5146   if (h->dynindx == -1)
5147     return TRUE;
5148
5149   name = h->root.root.string;
5150   p = strchr (name, ELF_VER_CHR);
5151   if (p != NULL)
5152     {
5153       alc = (char *) bfd_malloc (p - name + 1);
5154       if (alc == NULL)
5155         {
5156           inf->error = TRUE;
5157           return FALSE;
5158         }
5159       memcpy (alc, name, p - name);
5160       alc[p - name] = '\0';
5161       name = alc;
5162     }
5163
5164   /* Compute the hash value.  */
5165   ha = bfd_elf_hash (name);
5166
5167   /* Store the found hash value in the array given as the argument.  */
5168   *(inf->hashcodes)++ = ha;
5169
5170   /* And store it in the struct so that we can put it in the hash table
5171      later.  */
5172   h->u.elf_hash_value = ha;
5173
5174   if (alc != NULL)
5175     free (alc);
5176
5177   return TRUE;
5178 }
5179
5180 struct collect_gnu_hash_codes
5181 {
5182   bfd *output_bfd;
5183   const struct elf_backend_data *bed;
5184   unsigned long int nsyms;
5185   unsigned long int maskbits;
5186   unsigned long int *hashcodes;
5187   unsigned long int *hashval;
5188   unsigned long int *indx;
5189   unsigned long int *counts;
5190   bfd_vma *bitmask;
5191   bfd_byte *contents;
5192   long int min_dynindx;
5193   unsigned long int bucketcount;
5194   unsigned long int symindx;
5195   long int local_indx;
5196   long int shift1, shift2;
5197   unsigned long int mask;
5198   bfd_boolean error;
5199 };
5200
5201 /* This function will be called though elf_link_hash_traverse to store
5202    all hash value of the exported symbols in an array.  */
5203
5204 static bfd_boolean
5205 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5206 {
5207   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5208   const char *name;
5209   char *p;
5210   unsigned long ha;
5211   char *alc = NULL;
5212
5213   /* Ignore indirect symbols.  These are added by the versioning code.  */
5214   if (h->dynindx == -1)
5215     return TRUE;
5216
5217   /* Ignore also local symbols and undefined symbols.  */
5218   if (! (*s->bed->elf_hash_symbol) (h))
5219     return TRUE;
5220
5221   name = h->root.root.string;
5222   p = strchr (name, ELF_VER_CHR);
5223   if (p != NULL)
5224     {
5225       alc = (char *) bfd_malloc (p - name + 1);
5226       if (alc == NULL)
5227         {
5228           s->error = TRUE;
5229           return FALSE;
5230         }
5231       memcpy (alc, name, p - name);
5232       alc[p - name] = '\0';
5233       name = alc;
5234     }
5235
5236   /* Compute the hash value.  */
5237   ha = bfd_elf_gnu_hash (name);
5238
5239   /* Store the found hash value in the array for compute_bucket_count,
5240      and also for .dynsym reordering purposes.  */
5241   s->hashcodes[s->nsyms] = ha;
5242   s->hashval[h->dynindx] = ha;
5243   ++s->nsyms;
5244   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5245     s->min_dynindx = h->dynindx;
5246
5247   if (alc != NULL)
5248     free (alc);
5249
5250   return TRUE;
5251 }
5252
5253 /* This function will be called though elf_link_hash_traverse to do
5254    final dynaminc symbol renumbering.  */
5255
5256 static bfd_boolean
5257 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5258 {
5259   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5260   unsigned long int bucket;
5261   unsigned long int val;
5262
5263   /* Ignore indirect symbols.  */
5264   if (h->dynindx == -1)
5265     return TRUE;
5266
5267   /* Ignore also local symbols and undefined symbols.  */
5268   if (! (*s->bed->elf_hash_symbol) (h))
5269     {
5270       if (h->dynindx >= s->min_dynindx)
5271         h->dynindx = s->local_indx++;
5272       return TRUE;
5273     }
5274
5275   bucket = s->hashval[h->dynindx] % s->bucketcount;
5276   val = (s->hashval[h->dynindx] >> s->shift1)
5277         & ((s->maskbits >> s->shift1) - 1);
5278   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5279   s->bitmask[val]
5280     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5281   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5282   if (s->counts[bucket] == 1)
5283     /* Last element terminates the chain.  */
5284     val |= 1;
5285   bfd_put_32 (s->output_bfd, val,
5286               s->contents + (s->indx[bucket] - s->symindx) * 4);
5287   --s->counts[bucket];
5288   h->dynindx = s->indx[bucket]++;
5289   return TRUE;
5290 }
5291
5292 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5293
5294 bfd_boolean
5295 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5296 {
5297   return !(h->forced_local
5298            || h->root.type == bfd_link_hash_undefined
5299            || h->root.type == bfd_link_hash_undefweak
5300            || ((h->root.type == bfd_link_hash_defined
5301                 || h->root.type == bfd_link_hash_defweak)
5302                && h->root.u.def.section->output_section == NULL));
5303 }
5304
5305 /* Array used to determine the number of hash table buckets to use
5306    based on the number of symbols there are.  If there are fewer than
5307    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5308    fewer than 37 we use 17 buckets, and so forth.  We never use more
5309    than 32771 buckets.  */
5310
5311 static const size_t elf_buckets[] =
5312 {
5313   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5314   16411, 32771, 0
5315 };
5316
5317 /* Compute bucket count for hashing table.  We do not use a static set
5318    of possible tables sizes anymore.  Instead we determine for all
5319    possible reasonable sizes of the table the outcome (i.e., the
5320    number of collisions etc) and choose the best solution.  The
5321    weighting functions are not too simple to allow the table to grow
5322    without bounds.  Instead one of the weighting factors is the size.
5323    Therefore the result is always a good payoff between few collisions
5324    (= short chain lengths) and table size.  */
5325 static size_t
5326 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5327                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5328                       unsigned long int nsyms,
5329                       int gnu_hash)
5330 {
5331   size_t best_size = 0;
5332   unsigned long int i;
5333
5334   /* We have a problem here.  The following code to optimize the table
5335      size requires an integer type with more the 32 bits.  If
5336      BFD_HOST_U_64_BIT is set we know about such a type.  */
5337 #ifdef BFD_HOST_U_64_BIT
5338   if (info->optimize)
5339     {
5340       size_t minsize;
5341       size_t maxsize;
5342       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5343       bfd *dynobj = elf_hash_table (info)->dynobj;
5344       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5345       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5346       unsigned long int *counts;
5347       bfd_size_type amt;
5348       unsigned int no_improvement_count = 0;
5349
5350       /* Possible optimization parameters: if we have NSYMS symbols we say
5351          that the hashing table must at least have NSYMS/4 and at most
5352          2*NSYMS buckets.  */
5353       minsize = nsyms / 4;
5354       if (minsize == 0)
5355         minsize = 1;
5356       best_size = maxsize = nsyms * 2;
5357       if (gnu_hash)
5358         {
5359           if (minsize < 2)
5360             minsize = 2;
5361           if ((best_size & 31) == 0)
5362             ++best_size;
5363         }
5364
5365       /* Create array where we count the collisions in.  We must use bfd_malloc
5366          since the size could be large.  */
5367       amt = maxsize;
5368       amt *= sizeof (unsigned long int);
5369       counts = (unsigned long int *) bfd_malloc (amt);
5370       if (counts == NULL)
5371         return 0;
5372
5373       /* Compute the "optimal" size for the hash table.  The criteria is a
5374          minimal chain length.  The minor criteria is (of course) the size
5375          of the table.  */
5376       for (i = minsize; i < maxsize; ++i)
5377         {
5378           /* Walk through the array of hashcodes and count the collisions.  */
5379           BFD_HOST_U_64_BIT max;
5380           unsigned long int j;
5381           unsigned long int fact;
5382
5383           if (gnu_hash && (i & 31) == 0)
5384             continue;
5385
5386           memset (counts, '\0', i * sizeof (unsigned long int));
5387
5388           /* Determine how often each hash bucket is used.  */
5389           for (j = 0; j < nsyms; ++j)
5390             ++counts[hashcodes[j] % i];
5391
5392           /* For the weight function we need some information about the
5393              pagesize on the target.  This is information need not be 100%
5394              accurate.  Since this information is not available (so far) we
5395              define it here to a reasonable default value.  If it is crucial
5396              to have a better value some day simply define this value.  */
5397 # ifndef BFD_TARGET_PAGESIZE
5398 #  define BFD_TARGET_PAGESIZE   (4096)
5399 # endif
5400
5401           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5402              and the chains.  */
5403           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5404
5405 # if 1
5406           /* Variant 1: optimize for short chains.  We add the squares
5407              of all the chain lengths (which favors many small chain
5408              over a few long chains).  */
5409           for (j = 0; j < i; ++j)
5410             max += counts[j] * counts[j];
5411
5412           /* This adds penalties for the overall size of the table.  */
5413           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5414           max *= fact * fact;
5415 # else
5416           /* Variant 2: Optimize a lot more for small table.  Here we
5417              also add squares of the size but we also add penalties for
5418              empty slots (the +1 term).  */
5419           for (j = 0; j < i; ++j)
5420             max += (1 + counts[j]) * (1 + counts[j]);
5421
5422           /* The overall size of the table is considered, but not as
5423              strong as in variant 1, where it is squared.  */
5424           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5425           max *= fact;
5426 # endif
5427
5428           /* Compare with current best results.  */
5429           if (max < best_chlen)
5430             {
5431               best_chlen = max;
5432               best_size = i;
5433               no_improvement_count = 0;
5434             }
5435           /* PR 11843: Avoid futile long searches for the best bucket size
5436              when there are a large number of symbols.  */
5437           else if (++no_improvement_count == 100)
5438             break;
5439         }
5440
5441       free (counts);
5442     }
5443   else
5444 #endif /* defined (BFD_HOST_U_64_BIT) */
5445     {
5446       /* This is the fallback solution if no 64bit type is available or if we
5447          are not supposed to spend much time on optimizations.  We select the
5448          bucket count using a fixed set of numbers.  */
5449       for (i = 0; elf_buckets[i] != 0; i++)
5450         {
5451           best_size = elf_buckets[i];
5452           if (nsyms < elf_buckets[i + 1])
5453             break;
5454         }
5455       if (gnu_hash && best_size < 2)
5456         best_size = 2;
5457     }
5458
5459   return best_size;
5460 }
5461
5462 /* Size any SHT_GROUP section for ld -r.  */
5463
5464 bfd_boolean
5465 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5466 {
5467   bfd *ibfd;
5468
5469   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5470     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5471         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5472       return FALSE;
5473   return TRUE;
5474 }
5475
5476 /* Set a default stack segment size.  The value in INFO wins.  If it
5477    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5478    undefined it is initialized.  */
5479
5480 bfd_boolean
5481 bfd_elf_stack_segment_size (bfd *output_bfd,
5482                             struct bfd_link_info *info,
5483                             const char *legacy_symbol,
5484                             bfd_vma default_size)
5485 {
5486   struct elf_link_hash_entry *h = NULL;
5487
5488   /* Look for legacy symbol.  */
5489   if (legacy_symbol)
5490     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5491                               FALSE, FALSE, FALSE);
5492   if (h && (h->root.type == bfd_link_hash_defined
5493             || h->root.type == bfd_link_hash_defweak)
5494       && h->def_regular
5495       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5496     {
5497       /* The symbol has no type if specified on the command line.  */
5498       h->type = STT_OBJECT;
5499       if (info->stacksize)
5500         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5501                                output_bfd, legacy_symbol);
5502       else if (h->root.u.def.section != bfd_abs_section_ptr)
5503         (*_bfd_error_handler) (_("%B: %s not absolute"),
5504                                output_bfd, legacy_symbol);
5505       else
5506         info->stacksize = h->root.u.def.value;
5507     }
5508
5509   if (!info->stacksize)
5510     /* If the user didn't set a size, or explicitly inhibit the
5511        size, set it now.  */
5512     info->stacksize = default_size;
5513
5514   /* Provide the legacy symbol, if it is referenced.  */
5515   if (h && (h->root.type == bfd_link_hash_undefined
5516             || h->root.type == bfd_link_hash_undefweak))
5517     {
5518       struct bfd_link_hash_entry *bh = NULL;
5519
5520       if (!(_bfd_generic_link_add_one_symbol
5521             (info, output_bfd, legacy_symbol,
5522              BSF_GLOBAL, bfd_abs_section_ptr,
5523              info->stacksize >= 0 ? info->stacksize : 0,
5524              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5525         return FALSE;
5526
5527       h = (struct elf_link_hash_entry *) bh;
5528       h->def_regular = 1;
5529       h->type = STT_OBJECT;
5530     }
5531
5532   return TRUE;
5533 }
5534
5535 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5536    called by the ELF linker emulation before_allocation routine.  We
5537    must set the sizes of the sections before the linker sets the
5538    addresses of the various sections.  */
5539
5540 bfd_boolean
5541 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5542                                const char *soname,
5543                                const char *rpath,
5544                                const char *filter_shlib,
5545                                const char *audit,
5546                                const char *depaudit,
5547                                const char * const *auxiliary_filters,
5548                                struct bfd_link_info *info,
5549                                asection **sinterpptr)
5550 {
5551   bfd_size_type soname_indx;
5552   bfd *dynobj;
5553   const struct elf_backend_data *bed;
5554   struct elf_info_failed asvinfo;
5555
5556   *sinterpptr = NULL;
5557
5558   soname_indx = (bfd_size_type) -1;
5559
5560   if (!is_elf_hash_table (info->hash))
5561     return TRUE;
5562
5563   bed = get_elf_backend_data (output_bfd);
5564
5565   /* Any syms created from now on start with -1 in
5566      got.refcount/offset and plt.refcount/offset.  */
5567   elf_hash_table (info)->init_got_refcount
5568     = elf_hash_table (info)->init_got_offset;
5569   elf_hash_table (info)->init_plt_refcount
5570     = elf_hash_table (info)->init_plt_offset;
5571
5572   if (info->relocatable
5573       && !_bfd_elf_size_group_sections (info))
5574     return FALSE;
5575
5576   /* The backend may have to create some sections regardless of whether
5577      we're dynamic or not.  */
5578   if (bed->elf_backend_always_size_sections
5579       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5580     return FALSE;
5581
5582   /* Determine any GNU_STACK segment requirements, after the backend
5583      has had a chance to set a default segment size.  */
5584   if (info->execstack)
5585     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5586   else if (info->noexecstack)
5587     elf_stack_flags (output_bfd) = PF_R | PF_W;
5588   else
5589     {
5590       bfd *inputobj;
5591       asection *notesec = NULL;
5592       int exec = 0;
5593
5594       for (inputobj = info->input_bfds;
5595            inputobj;
5596            inputobj = inputobj->link.next)
5597         {
5598           asection *s;
5599
5600           if (inputobj->flags
5601               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5602             continue;
5603           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5604           if (s)
5605             {
5606               if (s->flags & SEC_CODE)
5607                 exec = PF_X;
5608               notesec = s;
5609             }
5610           else if (bed->default_execstack)
5611             exec = PF_X;
5612         }
5613       if (notesec || info->stacksize > 0)
5614         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5615       if (notesec && exec && info->relocatable
5616           && notesec->output_section != bfd_abs_section_ptr)
5617         notesec->output_section->flags |= SEC_CODE;
5618     }
5619
5620   dynobj = elf_hash_table (info)->dynobj;
5621
5622   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5623     {
5624       struct elf_info_failed eif;
5625       struct elf_link_hash_entry *h;
5626       asection *dynstr;
5627       struct bfd_elf_version_tree *t;
5628       struct bfd_elf_version_expr *d;
5629       asection *s;
5630       bfd_boolean all_defined;
5631
5632       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5633       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5634
5635       if (soname != NULL)
5636         {
5637           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5638                                              soname, TRUE);
5639           if (soname_indx == (bfd_size_type) -1
5640               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5641             return FALSE;
5642         }
5643
5644       if (info->symbolic)
5645         {
5646           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5647             return FALSE;
5648           info->flags |= DF_SYMBOLIC;
5649         }
5650
5651       if (rpath != NULL)
5652         {
5653           bfd_size_type indx;
5654           bfd_vma tag;
5655
5656           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5657                                       TRUE);
5658           if (indx == (bfd_size_type) -1)
5659             return FALSE;
5660
5661           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5662           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5663             return FALSE;
5664         }
5665
5666       if (filter_shlib != NULL)
5667         {
5668           bfd_size_type indx;
5669
5670           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5671                                       filter_shlib, TRUE);
5672           if (indx == (bfd_size_type) -1
5673               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5674             return FALSE;
5675         }
5676
5677       if (auxiliary_filters != NULL)
5678         {
5679           const char * const *p;
5680
5681           for (p = auxiliary_filters; *p != NULL; p++)
5682             {
5683               bfd_size_type indx;
5684
5685               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5686                                           *p, TRUE);
5687               if (indx == (bfd_size_type) -1
5688                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5689                 return FALSE;
5690             }
5691         }
5692
5693       if (audit != NULL)
5694         {
5695           bfd_size_type indx;
5696
5697           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5698                                       TRUE);
5699           if (indx == (bfd_size_type) -1
5700               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5701             return FALSE;
5702         }
5703
5704       if (depaudit != NULL)
5705         {
5706           bfd_size_type indx;
5707
5708           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5709                                       TRUE);
5710           if (indx == (bfd_size_type) -1
5711               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5712             return FALSE;
5713         }
5714
5715       eif.info = info;
5716       eif.failed = FALSE;
5717
5718       /* If we are supposed to export all symbols into the dynamic symbol
5719          table (this is not the normal case), then do so.  */
5720       if (info->export_dynamic
5721           || (info->executable && info->dynamic))
5722         {
5723           elf_link_hash_traverse (elf_hash_table (info),
5724                                   _bfd_elf_export_symbol,
5725                                   &eif);
5726           if (eif.failed)
5727             return FALSE;
5728         }
5729
5730       /* Make all global versions with definition.  */
5731       for (t = info->version_info; t != NULL; t = t->next)
5732         for (d = t->globals.list; d != NULL; d = d->next)
5733           if (!d->symver && d->literal)
5734             {
5735               const char *verstr, *name;
5736               size_t namelen, verlen, newlen;
5737               char *newname, *p, leading_char;
5738               struct elf_link_hash_entry *newh;
5739
5740               leading_char = bfd_get_symbol_leading_char (output_bfd);
5741               name = d->pattern;
5742               namelen = strlen (name) + (leading_char != '\0');
5743               verstr = t->name;
5744               verlen = strlen (verstr);
5745               newlen = namelen + verlen + 3;
5746
5747               newname = (char *) bfd_malloc (newlen);
5748               if (newname == NULL)
5749                 return FALSE;
5750               newname[0] = leading_char;
5751               memcpy (newname + (leading_char != '\0'), name, namelen);
5752
5753               /* Check the hidden versioned definition.  */
5754               p = newname + namelen;
5755               *p++ = ELF_VER_CHR;
5756               memcpy (p, verstr, verlen + 1);
5757               newh = elf_link_hash_lookup (elf_hash_table (info),
5758                                            newname, FALSE, FALSE,
5759                                            FALSE);
5760               if (newh == NULL
5761                   || (newh->root.type != bfd_link_hash_defined
5762                       && newh->root.type != bfd_link_hash_defweak))
5763                 {
5764                   /* Check the default versioned definition.  */
5765                   *p++ = ELF_VER_CHR;
5766                   memcpy (p, verstr, verlen + 1);
5767                   newh = elf_link_hash_lookup (elf_hash_table (info),
5768                                                newname, FALSE, FALSE,
5769                                                FALSE);
5770                 }
5771               free (newname);
5772
5773               /* Mark this version if there is a definition and it is
5774                  not defined in a shared object.  */
5775               if (newh != NULL
5776                   && !newh->def_dynamic
5777                   && (newh->root.type == bfd_link_hash_defined
5778                       || newh->root.type == bfd_link_hash_defweak))
5779                 d->symver = 1;
5780             }
5781
5782       /* Attach all the symbols to their version information.  */
5783       asvinfo.info = info;
5784       asvinfo.failed = FALSE;
5785
5786       elf_link_hash_traverse (elf_hash_table (info),
5787                               _bfd_elf_link_assign_sym_version,
5788                               &asvinfo);
5789       if (asvinfo.failed)
5790         return FALSE;
5791
5792       if (!info->allow_undefined_version)
5793         {
5794           /* Check if all global versions have a definition.  */
5795           all_defined = TRUE;
5796           for (t = info->version_info; t != NULL; t = t->next)
5797             for (d = t->globals.list; d != NULL; d = d->next)
5798               if (d->literal && !d->symver && !d->script)
5799                 {
5800                   (*_bfd_error_handler)
5801                     (_("%s: undefined version: %s"),
5802                      d->pattern, t->name);
5803                   all_defined = FALSE;
5804                 }
5805
5806           if (!all_defined)
5807             {
5808               bfd_set_error (bfd_error_bad_value);
5809               return FALSE;
5810             }
5811         }
5812
5813       /* Find all symbols which were defined in a dynamic object and make
5814          the backend pick a reasonable value for them.  */
5815       elf_link_hash_traverse (elf_hash_table (info),
5816                               _bfd_elf_adjust_dynamic_symbol,
5817                               &eif);
5818       if (eif.failed)
5819         return FALSE;
5820
5821       /* Add some entries to the .dynamic section.  We fill in some of the
5822          values later, in bfd_elf_final_link, but we must add the entries
5823          now so that we know the final size of the .dynamic section.  */
5824
5825       /* If there are initialization and/or finalization functions to
5826          call then add the corresponding DT_INIT/DT_FINI entries.  */
5827       h = (info->init_function
5828            ? elf_link_hash_lookup (elf_hash_table (info),
5829                                    info->init_function, FALSE,
5830                                    FALSE, FALSE)
5831            : NULL);
5832       if (h != NULL
5833           && (h->ref_regular
5834               || h->def_regular))
5835         {
5836           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5837             return FALSE;
5838         }
5839       h = (info->fini_function
5840            ? elf_link_hash_lookup (elf_hash_table (info),
5841                                    info->fini_function, FALSE,
5842                                    FALSE, FALSE)
5843            : NULL);
5844       if (h != NULL
5845           && (h->ref_regular
5846               || h->def_regular))
5847         {
5848           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5849             return FALSE;
5850         }
5851
5852       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5853       if (s != NULL && s->linker_has_input)
5854         {
5855           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5856           if (! info->executable)
5857             {
5858               bfd *sub;
5859               asection *o;
5860
5861               for (sub = info->input_bfds; sub != NULL;
5862                    sub = sub->link.next)
5863                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5864                   for (o = sub->sections; o != NULL; o = o->next)
5865                     if (elf_section_data (o)->this_hdr.sh_type
5866                         == SHT_PREINIT_ARRAY)
5867                       {
5868                         (*_bfd_error_handler)
5869                           (_("%B: .preinit_array section is not allowed in DSO"),
5870                            sub);
5871                         break;
5872                       }
5873
5874               bfd_set_error (bfd_error_nonrepresentable_section);
5875               return FALSE;
5876             }
5877
5878           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5879               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5880             return FALSE;
5881         }
5882       s = bfd_get_section_by_name (output_bfd, ".init_array");
5883       if (s != NULL && s->linker_has_input)
5884         {
5885           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5886               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5887             return FALSE;
5888         }
5889       s = bfd_get_section_by_name (output_bfd, ".fini_array");
5890       if (s != NULL && s->linker_has_input)
5891         {
5892           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5893               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5894             return FALSE;
5895         }
5896
5897       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
5898       /* If .dynstr is excluded from the link, we don't want any of
5899          these tags.  Strictly, we should be checking each section
5900          individually;  This quick check covers for the case where
5901          someone does a /DISCARD/ : { *(*) }.  */
5902       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5903         {
5904           bfd_size_type strsize;
5905
5906           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5907           if ((info->emit_hash
5908                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5909               || (info->emit_gnu_hash
5910                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5911               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5912               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5913               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5914               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5915                                               bed->s->sizeof_sym))
5916             return FALSE;
5917         }
5918     }
5919
5920   /* The backend must work out the sizes of all the other dynamic
5921      sections.  */
5922   if (dynobj != NULL
5923       && bed->elf_backend_size_dynamic_sections != NULL
5924       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5925     return FALSE;
5926
5927   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5928     return FALSE;
5929
5930   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5931     {
5932       unsigned long section_sym_count;
5933       struct bfd_elf_version_tree *verdefs;
5934       asection *s;
5935
5936       /* Set up the version definition section.  */
5937       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
5938       BFD_ASSERT (s != NULL);
5939
5940       /* We may have created additional version definitions if we are
5941          just linking a regular application.  */
5942       verdefs = info->version_info;
5943
5944       /* Skip anonymous version tag.  */
5945       if (verdefs != NULL && verdefs->vernum == 0)
5946         verdefs = verdefs->next;
5947
5948       if (verdefs == NULL && !info->create_default_symver)
5949         s->flags |= SEC_EXCLUDE;
5950       else
5951         {
5952           unsigned int cdefs;
5953           bfd_size_type size;
5954           struct bfd_elf_version_tree *t;
5955           bfd_byte *p;
5956           Elf_Internal_Verdef def;
5957           Elf_Internal_Verdaux defaux;
5958           struct bfd_link_hash_entry *bh;
5959           struct elf_link_hash_entry *h;
5960           const char *name;
5961
5962           cdefs = 0;
5963           size = 0;
5964
5965           /* Make space for the base version.  */
5966           size += sizeof (Elf_External_Verdef);
5967           size += sizeof (Elf_External_Verdaux);
5968           ++cdefs;
5969
5970           /* Make space for the default version.  */
5971           if (info->create_default_symver)
5972             {
5973               size += sizeof (Elf_External_Verdef);
5974               ++cdefs;
5975             }
5976
5977           for (t = verdefs; t != NULL; t = t->next)
5978             {
5979               struct bfd_elf_version_deps *n;
5980
5981               /* Don't emit base version twice.  */
5982               if (t->vernum == 0)
5983                 continue;
5984
5985               size += sizeof (Elf_External_Verdef);
5986               size += sizeof (Elf_External_Verdaux);
5987               ++cdefs;
5988
5989               for (n = t->deps; n != NULL; n = n->next)
5990                 size += sizeof (Elf_External_Verdaux);
5991             }
5992
5993           s->size = size;
5994           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
5995           if (s->contents == NULL && s->size != 0)
5996             return FALSE;
5997
5998           /* Fill in the version definition section.  */
5999
6000           p = s->contents;
6001
6002           def.vd_version = VER_DEF_CURRENT;
6003           def.vd_flags = VER_FLG_BASE;
6004           def.vd_ndx = 1;
6005           def.vd_cnt = 1;
6006           if (info->create_default_symver)
6007             {
6008               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6009               def.vd_next = sizeof (Elf_External_Verdef);
6010             }
6011           else
6012             {
6013               def.vd_aux = sizeof (Elf_External_Verdef);
6014               def.vd_next = (sizeof (Elf_External_Verdef)
6015                              + sizeof (Elf_External_Verdaux));
6016             }
6017
6018           if (soname_indx != (bfd_size_type) -1)
6019             {
6020               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6021                                       soname_indx);
6022               def.vd_hash = bfd_elf_hash (soname);
6023               defaux.vda_name = soname_indx;
6024               name = soname;
6025             }
6026           else
6027             {
6028               bfd_size_type indx;
6029
6030               name = lbasename (output_bfd->filename);
6031               def.vd_hash = bfd_elf_hash (name);
6032               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6033                                           name, FALSE);
6034               if (indx == (bfd_size_type) -1)
6035                 return FALSE;
6036               defaux.vda_name = indx;
6037             }
6038           defaux.vda_next = 0;
6039
6040           _bfd_elf_swap_verdef_out (output_bfd, &def,
6041                                     (Elf_External_Verdef *) p);
6042           p += sizeof (Elf_External_Verdef);
6043           if (info->create_default_symver)
6044             {
6045               /* Add a symbol representing this version.  */
6046               bh = NULL;
6047               if (! (_bfd_generic_link_add_one_symbol
6048                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6049                       0, NULL, FALSE,
6050                       get_elf_backend_data (dynobj)->collect, &bh)))
6051                 return FALSE;
6052               h = (struct elf_link_hash_entry *) bh;
6053               h->non_elf = 0;
6054               h->def_regular = 1;
6055               h->type = STT_OBJECT;
6056               h->verinfo.vertree = NULL;
6057
6058               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6059                 return FALSE;
6060
6061               /* Create a duplicate of the base version with the same
6062                  aux block, but different flags.  */
6063               def.vd_flags = 0;
6064               def.vd_ndx = 2;
6065               def.vd_aux = sizeof (Elf_External_Verdef);
6066               if (verdefs)
6067                 def.vd_next = (sizeof (Elf_External_Verdef)
6068                                + sizeof (Elf_External_Verdaux));
6069               else
6070                 def.vd_next = 0;
6071               _bfd_elf_swap_verdef_out (output_bfd, &def,
6072                                         (Elf_External_Verdef *) p);
6073               p += sizeof (Elf_External_Verdef);
6074             }
6075           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6076                                      (Elf_External_Verdaux *) p);
6077           p += sizeof (Elf_External_Verdaux);
6078
6079           for (t = verdefs; t != NULL; t = t->next)
6080             {
6081               unsigned int cdeps;
6082               struct bfd_elf_version_deps *n;
6083
6084               /* Don't emit the base version twice.  */
6085               if (t->vernum == 0)
6086                 continue;
6087
6088               cdeps = 0;
6089               for (n = t->deps; n != NULL; n = n->next)
6090                 ++cdeps;
6091
6092               /* Add a symbol representing this version.  */
6093               bh = NULL;
6094               if (! (_bfd_generic_link_add_one_symbol
6095                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6096                       0, NULL, FALSE,
6097                       get_elf_backend_data (dynobj)->collect, &bh)))
6098                 return FALSE;
6099               h = (struct elf_link_hash_entry *) bh;
6100               h->non_elf = 0;
6101               h->def_regular = 1;
6102               h->type = STT_OBJECT;
6103               h->verinfo.vertree = t;
6104
6105               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6106                 return FALSE;
6107
6108               def.vd_version = VER_DEF_CURRENT;
6109               def.vd_flags = 0;
6110               if (t->globals.list == NULL
6111                   && t->locals.list == NULL
6112                   && ! t->used)
6113                 def.vd_flags |= VER_FLG_WEAK;
6114               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6115               def.vd_cnt = cdeps + 1;
6116               def.vd_hash = bfd_elf_hash (t->name);
6117               def.vd_aux = sizeof (Elf_External_Verdef);
6118               def.vd_next = 0;
6119
6120               /* If a basever node is next, it *must* be the last node in
6121                  the chain, otherwise Verdef construction breaks.  */
6122               if (t->next != NULL && t->next->vernum == 0)
6123                 BFD_ASSERT (t->next->next == NULL);
6124
6125               if (t->next != NULL && t->next->vernum != 0)
6126                 def.vd_next = (sizeof (Elf_External_Verdef)
6127                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6128
6129               _bfd_elf_swap_verdef_out (output_bfd, &def,
6130                                         (Elf_External_Verdef *) p);
6131               p += sizeof (Elf_External_Verdef);
6132
6133               defaux.vda_name = h->dynstr_index;
6134               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6135                                       h->dynstr_index);
6136               defaux.vda_next = 0;
6137               if (t->deps != NULL)
6138                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6139               t->name_indx = defaux.vda_name;
6140
6141               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6142                                          (Elf_External_Verdaux *) p);
6143               p += sizeof (Elf_External_Verdaux);
6144
6145               for (n = t->deps; n != NULL; n = n->next)
6146                 {
6147                   if (n->version_needed == NULL)
6148                     {
6149                       /* This can happen if there was an error in the
6150                          version script.  */
6151                       defaux.vda_name = 0;
6152                     }
6153                   else
6154                     {
6155                       defaux.vda_name = n->version_needed->name_indx;
6156                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6157                                               defaux.vda_name);
6158                     }
6159                   if (n->next == NULL)
6160                     defaux.vda_next = 0;
6161                   else
6162                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6163
6164                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6165                                              (Elf_External_Verdaux *) p);
6166                   p += sizeof (Elf_External_Verdaux);
6167                 }
6168             }
6169
6170           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6171               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6172             return FALSE;
6173
6174           elf_tdata (output_bfd)->cverdefs = cdefs;
6175         }
6176
6177       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6178         {
6179           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6180             return FALSE;
6181         }
6182       else if (info->flags & DF_BIND_NOW)
6183         {
6184           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6185             return FALSE;
6186         }
6187
6188       if (info->flags_1)
6189         {
6190           if (info->executable)
6191             info->flags_1 &= ~ (DF_1_INITFIRST
6192                                 | DF_1_NODELETE
6193                                 | DF_1_NOOPEN);
6194           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6195             return FALSE;
6196         }
6197
6198       /* Work out the size of the version reference section.  */
6199
6200       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6201       BFD_ASSERT (s != NULL);
6202       {
6203         struct elf_find_verdep_info sinfo;
6204
6205         sinfo.info = info;
6206         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6207         if (sinfo.vers == 0)
6208           sinfo.vers = 1;
6209         sinfo.failed = FALSE;
6210
6211         elf_link_hash_traverse (elf_hash_table (info),
6212                                 _bfd_elf_link_find_version_dependencies,
6213                                 &sinfo);
6214         if (sinfo.failed)
6215           return FALSE;
6216
6217         if (elf_tdata (output_bfd)->verref == NULL)
6218           s->flags |= SEC_EXCLUDE;
6219         else
6220           {
6221             Elf_Internal_Verneed *t;
6222             unsigned int size;
6223             unsigned int crefs;
6224             bfd_byte *p;
6225
6226             /* Build the version dependency section.  */
6227             size = 0;
6228             crefs = 0;
6229             for (t = elf_tdata (output_bfd)->verref;
6230                  t != NULL;
6231                  t = t->vn_nextref)
6232               {
6233                 Elf_Internal_Vernaux *a;
6234
6235                 size += sizeof (Elf_External_Verneed);
6236                 ++crefs;
6237                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6238                   size += sizeof (Elf_External_Vernaux);
6239               }
6240
6241             s->size = size;
6242             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6243             if (s->contents == NULL)
6244               return FALSE;
6245
6246             p = s->contents;
6247             for (t = elf_tdata (output_bfd)->verref;
6248                  t != NULL;
6249                  t = t->vn_nextref)
6250               {
6251                 unsigned int caux;
6252                 Elf_Internal_Vernaux *a;
6253                 bfd_size_type indx;
6254
6255                 caux = 0;
6256                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6257                   ++caux;
6258
6259                 t->vn_version = VER_NEED_CURRENT;
6260                 t->vn_cnt = caux;
6261                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6262                                             elf_dt_name (t->vn_bfd) != NULL
6263                                             ? elf_dt_name (t->vn_bfd)
6264                                             : lbasename (t->vn_bfd->filename),
6265                                             FALSE);
6266                 if (indx == (bfd_size_type) -1)
6267                   return FALSE;
6268                 t->vn_file = indx;
6269                 t->vn_aux = sizeof (Elf_External_Verneed);
6270                 if (t->vn_nextref == NULL)
6271                   t->vn_next = 0;
6272                 else
6273                   t->vn_next = (sizeof (Elf_External_Verneed)
6274                                 + caux * sizeof (Elf_External_Vernaux));
6275
6276                 _bfd_elf_swap_verneed_out (output_bfd, t,
6277                                            (Elf_External_Verneed *) p);
6278                 p += sizeof (Elf_External_Verneed);
6279
6280                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6281                   {
6282                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6283                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6284                                                 a->vna_nodename, FALSE);
6285                     if (indx == (bfd_size_type) -1)
6286                       return FALSE;
6287                     a->vna_name = indx;
6288                     if (a->vna_nextptr == NULL)
6289                       a->vna_next = 0;
6290                     else
6291                       a->vna_next = sizeof (Elf_External_Vernaux);
6292
6293                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6294                                                (Elf_External_Vernaux *) p);
6295                     p += sizeof (Elf_External_Vernaux);
6296                   }
6297               }
6298
6299             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6300                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6301               return FALSE;
6302
6303             elf_tdata (output_bfd)->cverrefs = crefs;
6304           }
6305       }
6306
6307       if ((elf_tdata (output_bfd)->cverrefs == 0
6308            && elf_tdata (output_bfd)->cverdefs == 0)
6309           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6310                                              &section_sym_count) == 0)
6311         {
6312           s = bfd_get_linker_section (dynobj, ".gnu.version");
6313           s->flags |= SEC_EXCLUDE;
6314         }
6315     }
6316   return TRUE;
6317 }
6318
6319 /* Find the first non-excluded output section.  We'll use its
6320    section symbol for some emitted relocs.  */
6321 void
6322 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6323 {
6324   asection *s;
6325
6326   for (s = output_bfd->sections; s != NULL; s = s->next)
6327     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6328         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6329       {
6330         elf_hash_table (info)->text_index_section = s;
6331         break;
6332       }
6333 }
6334
6335 /* Find two non-excluded output sections, one for code, one for data.
6336    We'll use their section symbols for some emitted relocs.  */
6337 void
6338 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6339 {
6340   asection *s;
6341
6342   /* Data first, since setting text_index_section changes
6343      _bfd_elf_link_omit_section_dynsym.  */
6344   for (s = output_bfd->sections; s != NULL; s = s->next)
6345     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6346         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6347       {
6348         elf_hash_table (info)->data_index_section = s;
6349         break;
6350       }
6351
6352   for (s = output_bfd->sections; s != NULL; s = s->next)
6353     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6354          == (SEC_ALLOC | SEC_READONLY))
6355         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6356       {
6357         elf_hash_table (info)->text_index_section = s;
6358         break;
6359       }
6360
6361   if (elf_hash_table (info)->text_index_section == NULL)
6362     elf_hash_table (info)->text_index_section
6363       = elf_hash_table (info)->data_index_section;
6364 }
6365
6366 bfd_boolean
6367 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6368 {
6369   const struct elf_backend_data *bed;
6370
6371   if (!is_elf_hash_table (info->hash))
6372     return TRUE;
6373
6374   bed = get_elf_backend_data (output_bfd);
6375   (*bed->elf_backend_init_index_section) (output_bfd, info);
6376
6377   if (elf_hash_table (info)->dynamic_sections_created)
6378     {
6379       bfd *dynobj;
6380       asection *s;
6381       bfd_size_type dynsymcount;
6382       unsigned long section_sym_count;
6383       unsigned int dtagcount;
6384
6385       dynobj = elf_hash_table (info)->dynobj;
6386
6387       /* Assign dynsym indicies.  In a shared library we generate a
6388          section symbol for each output section, which come first.
6389          Next come all of the back-end allocated local dynamic syms,
6390          followed by the rest of the global symbols.  */
6391
6392       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6393                                                     &section_sym_count);
6394
6395       /* Work out the size of the symbol version section.  */
6396       s = bfd_get_linker_section (dynobj, ".gnu.version");
6397       BFD_ASSERT (s != NULL);
6398       if (dynsymcount != 0
6399           && (s->flags & SEC_EXCLUDE) == 0)
6400         {
6401           s->size = dynsymcount * sizeof (Elf_External_Versym);
6402           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6403           if (s->contents == NULL)
6404             return FALSE;
6405
6406           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6407             return FALSE;
6408         }
6409
6410       /* Set the size of the .dynsym and .hash sections.  We counted
6411          the number of dynamic symbols in elf_link_add_object_symbols.
6412          We will build the contents of .dynsym and .hash when we build
6413          the final symbol table, because until then we do not know the
6414          correct value to give the symbols.  We built the .dynstr
6415          section as we went along in elf_link_add_object_symbols.  */
6416       s = bfd_get_linker_section (dynobj, ".dynsym");
6417       BFD_ASSERT (s != NULL);
6418       s->size = dynsymcount * bed->s->sizeof_sym;
6419
6420       if (dynsymcount != 0)
6421         {
6422           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6423           if (s->contents == NULL)
6424             return FALSE;
6425
6426           /* The first entry in .dynsym is a dummy symbol.
6427              Clear all the section syms, in case we don't output them all.  */
6428           ++section_sym_count;
6429           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6430         }
6431
6432       elf_hash_table (info)->bucketcount = 0;
6433
6434       /* Compute the size of the hashing table.  As a side effect this
6435          computes the hash values for all the names we export.  */
6436       if (info->emit_hash)
6437         {
6438           unsigned long int *hashcodes;
6439           struct hash_codes_info hashinf;
6440           bfd_size_type amt;
6441           unsigned long int nsyms;
6442           size_t bucketcount;
6443           size_t hash_entry_size;
6444
6445           /* Compute the hash values for all exported symbols.  At the same
6446              time store the values in an array so that we could use them for
6447              optimizations.  */
6448           amt = dynsymcount * sizeof (unsigned long int);
6449           hashcodes = (unsigned long int *) bfd_malloc (amt);
6450           if (hashcodes == NULL)
6451             return FALSE;
6452           hashinf.hashcodes = hashcodes;
6453           hashinf.error = FALSE;
6454
6455           /* Put all hash values in HASHCODES.  */
6456           elf_link_hash_traverse (elf_hash_table (info),
6457                                   elf_collect_hash_codes, &hashinf);
6458           if (hashinf.error)
6459             {
6460               free (hashcodes);
6461               return FALSE;
6462             }
6463
6464           nsyms = hashinf.hashcodes - hashcodes;
6465           bucketcount
6466             = compute_bucket_count (info, hashcodes, nsyms, 0);
6467           free (hashcodes);
6468
6469           if (bucketcount == 0)
6470             return FALSE;
6471
6472           elf_hash_table (info)->bucketcount = bucketcount;
6473
6474           s = bfd_get_linker_section (dynobj, ".hash");
6475           BFD_ASSERT (s != NULL);
6476           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6477           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6478           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6479           if (s->contents == NULL)
6480             return FALSE;
6481
6482           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6483           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6484                    s->contents + hash_entry_size);
6485         }
6486
6487       if (info->emit_gnu_hash)
6488         {
6489           size_t i, cnt;
6490           unsigned char *contents;
6491           struct collect_gnu_hash_codes cinfo;
6492           bfd_size_type amt;
6493           size_t bucketcount;
6494
6495           memset (&cinfo, 0, sizeof (cinfo));
6496
6497           /* Compute the hash values for all exported symbols.  At the same
6498              time store the values in an array so that we could use them for
6499              optimizations.  */
6500           amt = dynsymcount * 2 * sizeof (unsigned long int);
6501           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6502           if (cinfo.hashcodes == NULL)
6503             return FALSE;
6504
6505           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6506           cinfo.min_dynindx = -1;
6507           cinfo.output_bfd = output_bfd;
6508           cinfo.bed = bed;
6509
6510           /* Put all hash values in HASHCODES.  */
6511           elf_link_hash_traverse (elf_hash_table (info),
6512                                   elf_collect_gnu_hash_codes, &cinfo);
6513           if (cinfo.error)
6514             {
6515               free (cinfo.hashcodes);
6516               return FALSE;
6517             }
6518
6519           bucketcount
6520             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6521
6522           if (bucketcount == 0)
6523             {
6524               free (cinfo.hashcodes);
6525               return FALSE;
6526             }
6527
6528           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6529           BFD_ASSERT (s != NULL);
6530
6531           if (cinfo.nsyms == 0)
6532             {
6533               /* Empty .gnu.hash section is special.  */
6534               BFD_ASSERT (cinfo.min_dynindx == -1);
6535               free (cinfo.hashcodes);
6536               s->size = 5 * 4 + bed->s->arch_size / 8;
6537               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6538               if (contents == NULL)
6539                 return FALSE;
6540               s->contents = contents;
6541               /* 1 empty bucket.  */
6542               bfd_put_32 (output_bfd, 1, contents);
6543               /* SYMIDX above the special symbol 0.  */
6544               bfd_put_32 (output_bfd, 1, contents + 4);
6545               /* Just one word for bitmask.  */
6546               bfd_put_32 (output_bfd, 1, contents + 8);
6547               /* Only hash fn bloom filter.  */
6548               bfd_put_32 (output_bfd, 0, contents + 12);
6549               /* No hashes are valid - empty bitmask.  */
6550               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6551               /* No hashes in the only bucket.  */
6552               bfd_put_32 (output_bfd, 0,
6553                           contents + 16 + bed->s->arch_size / 8);
6554             }
6555           else
6556             {
6557               unsigned long int maskwords, maskbitslog2, x;
6558               BFD_ASSERT (cinfo.min_dynindx != -1);
6559
6560               x = cinfo.nsyms;
6561               maskbitslog2 = 1;
6562               while ((x >>= 1) != 0)
6563                 ++maskbitslog2;
6564               if (maskbitslog2 < 3)
6565                 maskbitslog2 = 5;
6566               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6567                 maskbitslog2 = maskbitslog2 + 3;
6568               else
6569                 maskbitslog2 = maskbitslog2 + 2;
6570               if (bed->s->arch_size == 64)
6571                 {
6572                   if (maskbitslog2 == 5)
6573                     maskbitslog2 = 6;
6574                   cinfo.shift1 = 6;
6575                 }
6576               else
6577                 cinfo.shift1 = 5;
6578               cinfo.mask = (1 << cinfo.shift1) - 1;
6579               cinfo.shift2 = maskbitslog2;
6580               cinfo.maskbits = 1 << maskbitslog2;
6581               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6582               amt = bucketcount * sizeof (unsigned long int) * 2;
6583               amt += maskwords * sizeof (bfd_vma);
6584               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6585               if (cinfo.bitmask == NULL)
6586                 {
6587                   free (cinfo.hashcodes);
6588                   return FALSE;
6589                 }
6590
6591               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6592               cinfo.indx = cinfo.counts + bucketcount;
6593               cinfo.symindx = dynsymcount - cinfo.nsyms;
6594               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6595
6596               /* Determine how often each hash bucket is used.  */
6597               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6598               for (i = 0; i < cinfo.nsyms; ++i)
6599                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6600
6601               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6602                 if (cinfo.counts[i] != 0)
6603                   {
6604                     cinfo.indx[i] = cnt;
6605                     cnt += cinfo.counts[i];
6606                   }
6607               BFD_ASSERT (cnt == dynsymcount);
6608               cinfo.bucketcount = bucketcount;
6609               cinfo.local_indx = cinfo.min_dynindx;
6610
6611               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6612               s->size += cinfo.maskbits / 8;
6613               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6614               if (contents == NULL)
6615                 {
6616                   free (cinfo.bitmask);
6617                   free (cinfo.hashcodes);
6618                   return FALSE;
6619                 }
6620
6621               s->contents = contents;
6622               bfd_put_32 (output_bfd, bucketcount, contents);
6623               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6624               bfd_put_32 (output_bfd, maskwords, contents + 8);
6625               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6626               contents += 16 + cinfo.maskbits / 8;
6627
6628               for (i = 0; i < bucketcount; ++i)
6629                 {
6630                   if (cinfo.counts[i] == 0)
6631                     bfd_put_32 (output_bfd, 0, contents);
6632                   else
6633                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6634                   contents += 4;
6635                 }
6636
6637               cinfo.contents = contents;
6638
6639               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6640               elf_link_hash_traverse (elf_hash_table (info),
6641                                       elf_renumber_gnu_hash_syms, &cinfo);
6642
6643               contents = s->contents + 16;
6644               for (i = 0; i < maskwords; ++i)
6645                 {
6646                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6647                            contents);
6648                   contents += bed->s->arch_size / 8;
6649                 }
6650
6651               free (cinfo.bitmask);
6652               free (cinfo.hashcodes);
6653             }
6654         }
6655
6656       s = bfd_get_linker_section (dynobj, ".dynstr");
6657       BFD_ASSERT (s != NULL);
6658
6659       elf_finalize_dynstr (output_bfd, info);
6660
6661       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6662
6663       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6664         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6665           return FALSE;
6666     }
6667
6668   return TRUE;
6669 }
6670 \f
6671 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6672
6673 static void
6674 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6675                             asection *sec)
6676 {
6677   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6678   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6679 }
6680
6681 /* Finish SHF_MERGE section merging.  */
6682
6683 bfd_boolean
6684 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6685 {
6686   bfd *ibfd;
6687   asection *sec;
6688
6689   if (!is_elf_hash_table (info->hash))
6690     return FALSE;
6691
6692   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6693     if ((ibfd->flags & DYNAMIC) == 0)
6694       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6695         if ((sec->flags & SEC_MERGE) != 0
6696             && !bfd_is_abs_section (sec->output_section))
6697           {
6698             struct bfd_elf_section_data *secdata;
6699
6700             secdata = elf_section_data (sec);
6701             if (! _bfd_add_merge_section (abfd,
6702                                           &elf_hash_table (info)->merge_info,
6703                                           sec, &secdata->sec_info))
6704               return FALSE;
6705             else if (secdata->sec_info)
6706               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6707           }
6708
6709   if (elf_hash_table (info)->merge_info != NULL)
6710     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6711                          merge_sections_remove_hook);
6712   return TRUE;
6713 }
6714
6715 /* Create an entry in an ELF linker hash table.  */
6716
6717 struct bfd_hash_entry *
6718 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6719                             struct bfd_hash_table *table,
6720                             const char *string)
6721 {
6722   /* Allocate the structure if it has not already been allocated by a
6723      subclass.  */
6724   if (entry == NULL)
6725     {
6726       entry = (struct bfd_hash_entry *)
6727           bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6728       if (entry == NULL)
6729         return entry;
6730     }
6731
6732   /* Call the allocation method of the superclass.  */
6733   entry = _bfd_link_hash_newfunc (entry, table, string);
6734   if (entry != NULL)
6735     {
6736       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6737       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6738
6739       /* Set local fields.  */
6740       ret->indx = -1;
6741       ret->dynindx = -1;
6742       ret->got = htab->init_got_refcount;
6743       ret->plt = htab->init_plt_refcount;
6744       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6745                               - offsetof (struct elf_link_hash_entry, size)));
6746       /* Assume that we have been called by a non-ELF symbol reader.
6747          This flag is then reset by the code which reads an ELF input
6748          file.  This ensures that a symbol created by a non-ELF symbol
6749          reader will have the flag set correctly.  */
6750       ret->non_elf = 1;
6751     }
6752
6753   return entry;
6754 }
6755
6756 /* Copy data from an indirect symbol to its direct symbol, hiding the
6757    old indirect symbol.  Also used for copying flags to a weakdef.  */
6758
6759 void
6760 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6761                                   struct elf_link_hash_entry *dir,
6762                                   struct elf_link_hash_entry *ind)
6763 {
6764   struct elf_link_hash_table *htab;
6765
6766   /* Copy down any references that we may have already seen to the
6767      symbol which just became indirect.  */
6768
6769   dir->ref_dynamic |= ind->ref_dynamic;
6770   dir->ref_regular |= ind->ref_regular;
6771   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6772   dir->non_got_ref |= ind->non_got_ref;
6773   dir->needs_plt |= ind->needs_plt;
6774   dir->pointer_equality_needed |= ind->pointer_equality_needed;
6775
6776   if (ind->root.type != bfd_link_hash_indirect)
6777     return;
6778
6779   /* Copy over the global and procedure linkage table refcount entries.
6780      These may have been already set up by a check_relocs routine.  */
6781   htab = elf_hash_table (info);
6782   if (ind->got.refcount > htab->init_got_refcount.refcount)
6783     {
6784       if (dir->got.refcount < 0)
6785         dir->got.refcount = 0;
6786       dir->got.refcount += ind->got.refcount;
6787       ind->got.refcount = htab->init_got_refcount.refcount;
6788     }
6789
6790   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6791     {
6792       if (dir->plt.refcount < 0)
6793         dir->plt.refcount = 0;
6794       dir->plt.refcount += ind->plt.refcount;
6795       ind->plt.refcount = htab->init_plt_refcount.refcount;
6796     }
6797
6798   if (ind->dynindx != -1)
6799     {
6800       if (dir->dynindx != -1)
6801         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6802       dir->dynindx = ind->dynindx;
6803       dir->dynstr_index = ind->dynstr_index;
6804       ind->dynindx = -1;
6805       ind->dynstr_index = 0;
6806     }
6807 }
6808
6809 void
6810 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6811                                 struct elf_link_hash_entry *h,
6812                                 bfd_boolean force_local)
6813 {
6814   /* STT_GNU_IFUNC symbol must go through PLT.  */
6815   if (h->type != STT_GNU_IFUNC)
6816     {
6817       h->plt = elf_hash_table (info)->init_plt_offset;
6818       h->needs_plt = 0;
6819     }
6820   if (force_local)
6821     {
6822       h->forced_local = 1;
6823       if (h->dynindx != -1)
6824         {
6825           h->dynindx = -1;
6826           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6827                                   h->dynstr_index);
6828         }
6829     }
6830 }
6831
6832 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
6833    caller.  */
6834
6835 bfd_boolean
6836 _bfd_elf_link_hash_table_init
6837   (struct elf_link_hash_table *table,
6838    bfd *abfd,
6839    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6840                                       struct bfd_hash_table *,
6841                                       const char *),
6842    unsigned int entsize,
6843    enum elf_target_id target_id)
6844 {
6845   bfd_boolean ret;
6846   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6847
6848   table->init_got_refcount.refcount = can_refcount - 1;
6849   table->init_plt_refcount.refcount = can_refcount - 1;
6850   table->init_got_offset.offset = -(bfd_vma) 1;
6851   table->init_plt_offset.offset = -(bfd_vma) 1;
6852   /* The first dynamic symbol is a dummy.  */
6853   table->dynsymcount = 1;
6854
6855   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6856
6857   table->root.type = bfd_link_elf_hash_table;
6858   table->hash_table_id = target_id;
6859
6860   return ret;
6861 }
6862
6863 /* Create an ELF linker hash table.  */
6864
6865 struct bfd_link_hash_table *
6866 _bfd_elf_link_hash_table_create (bfd *abfd)
6867 {
6868   struct elf_link_hash_table *ret;
6869   bfd_size_type amt = sizeof (struct elf_link_hash_table);
6870
6871   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
6872   if (ret == NULL)
6873     return NULL;
6874
6875   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
6876                                        sizeof (struct elf_link_hash_entry),
6877                                        GENERIC_ELF_DATA))
6878     {
6879       free (ret);
6880       return NULL;
6881     }
6882   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
6883
6884   return &ret->root;
6885 }
6886
6887 /* Destroy an ELF linker hash table.  */
6888
6889 void
6890 _bfd_elf_link_hash_table_free (bfd *obfd)
6891 {
6892   struct elf_link_hash_table *htab;
6893
6894   htab = (struct elf_link_hash_table *) obfd->link.hash;
6895   if (htab->dynstr != NULL)
6896     _bfd_elf_strtab_free (htab->dynstr);
6897   _bfd_merge_sections_free (htab->merge_info);
6898   _bfd_generic_link_hash_table_free (obfd);
6899 }
6900
6901 /* This is a hook for the ELF emulation code in the generic linker to
6902    tell the backend linker what file name to use for the DT_NEEDED
6903    entry for a dynamic object.  */
6904
6905 void
6906 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
6907 {
6908   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6909       && bfd_get_format (abfd) == bfd_object)
6910     elf_dt_name (abfd) = name;
6911 }
6912
6913 int
6914 bfd_elf_get_dyn_lib_class (bfd *abfd)
6915 {
6916   int lib_class;
6917   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6918       && bfd_get_format (abfd) == bfd_object)
6919     lib_class = elf_dyn_lib_class (abfd);
6920   else
6921     lib_class = 0;
6922   return lib_class;
6923 }
6924
6925 void
6926 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
6927 {
6928   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6929       && bfd_get_format (abfd) == bfd_object)
6930     elf_dyn_lib_class (abfd) = lib_class;
6931 }
6932
6933 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
6934    the linker ELF emulation code.  */
6935
6936 struct bfd_link_needed_list *
6937 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
6938                          struct bfd_link_info *info)
6939 {
6940   if (! is_elf_hash_table (info->hash))
6941     return NULL;
6942   return elf_hash_table (info)->needed;
6943 }
6944
6945 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
6946    hook for the linker ELF emulation code.  */
6947
6948 struct bfd_link_needed_list *
6949 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
6950                           struct bfd_link_info *info)
6951 {
6952   if (! is_elf_hash_table (info->hash))
6953     return NULL;
6954   return elf_hash_table (info)->runpath;
6955 }
6956
6957 /* Get the name actually used for a dynamic object for a link.  This
6958    is the SONAME entry if there is one.  Otherwise, it is the string
6959    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
6960
6961 const char *
6962 bfd_elf_get_dt_soname (bfd *abfd)
6963 {
6964   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6965       && bfd_get_format (abfd) == bfd_object)
6966     return elf_dt_name (abfd);
6967   return NULL;
6968 }
6969
6970 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
6971    the ELF linker emulation code.  */
6972
6973 bfd_boolean
6974 bfd_elf_get_bfd_needed_list (bfd *abfd,
6975                              struct bfd_link_needed_list **pneeded)
6976 {
6977   asection *s;
6978   bfd_byte *dynbuf = NULL;
6979   unsigned int elfsec;
6980   unsigned long shlink;
6981   bfd_byte *extdyn, *extdynend;
6982   size_t extdynsize;
6983   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
6984
6985   *pneeded = NULL;
6986
6987   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
6988       || bfd_get_format (abfd) != bfd_object)
6989     return TRUE;
6990
6991   s = bfd_get_section_by_name (abfd, ".dynamic");
6992   if (s == NULL || s->size == 0)
6993     return TRUE;
6994
6995   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
6996     goto error_return;
6997
6998   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
6999   if (elfsec == SHN_BAD)
7000     goto error_return;
7001
7002   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7003
7004   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7005   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7006
7007   extdyn = dynbuf;
7008   extdynend = extdyn + s->size;
7009   for (; extdyn < extdynend; extdyn += extdynsize)
7010     {
7011       Elf_Internal_Dyn dyn;
7012
7013       (*swap_dyn_in) (abfd, extdyn, &dyn);
7014
7015       if (dyn.d_tag == DT_NULL)
7016         break;
7017
7018       if (dyn.d_tag == DT_NEEDED)
7019         {
7020           const char *string;
7021           struct bfd_link_needed_list *l;
7022           unsigned int tagv = dyn.d_un.d_val;
7023           bfd_size_type amt;
7024
7025           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7026           if (string == NULL)
7027             goto error_return;
7028
7029           amt = sizeof *l;
7030           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7031           if (l == NULL)
7032             goto error_return;
7033
7034           l->by = abfd;
7035           l->name = string;
7036           l->next = *pneeded;
7037           *pneeded = l;
7038         }
7039     }
7040
7041   free (dynbuf);
7042
7043   return TRUE;
7044
7045  error_return:
7046   if (dynbuf != NULL)
7047     free (dynbuf);
7048   return FALSE;
7049 }
7050
7051 struct elf_symbuf_symbol
7052 {
7053   unsigned long st_name;        /* Symbol name, index in string tbl */
7054   unsigned char st_info;        /* Type and binding attributes */
7055   unsigned char st_other;       /* Visibilty, and target specific */
7056 };
7057
7058 struct elf_symbuf_head
7059 {
7060   struct elf_symbuf_symbol *ssym;
7061   bfd_size_type count;
7062   unsigned int st_shndx;
7063 };
7064
7065 struct elf_symbol
7066 {
7067   union
7068     {
7069       Elf_Internal_Sym *isym;
7070       struct elf_symbuf_symbol *ssym;
7071     } u;
7072   const char *name;
7073 };
7074
7075 /* Sort references to symbols by ascending section number.  */
7076
7077 static int
7078 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7079 {
7080   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7081   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7082
7083   return s1->st_shndx - s2->st_shndx;
7084 }
7085
7086 static int
7087 elf_sym_name_compare (const void *arg1, const void *arg2)
7088 {
7089   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7090   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7091   return strcmp (s1->name, s2->name);
7092 }
7093
7094 static struct elf_symbuf_head *
7095 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7096 {
7097   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7098   struct elf_symbuf_symbol *ssym;
7099   struct elf_symbuf_head *ssymbuf, *ssymhead;
7100   bfd_size_type i, shndx_count, total_size;
7101
7102   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7103   if (indbuf == NULL)
7104     return NULL;
7105
7106   for (ind = indbuf, i = 0; i < symcount; i++)
7107     if (isymbuf[i].st_shndx != SHN_UNDEF)
7108       *ind++ = &isymbuf[i];
7109   indbufend = ind;
7110
7111   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7112          elf_sort_elf_symbol);
7113
7114   shndx_count = 0;
7115   if (indbufend > indbuf)
7116     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7117       if (ind[0]->st_shndx != ind[1]->st_shndx)
7118         shndx_count++;
7119
7120   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7121                 + (indbufend - indbuf) * sizeof (*ssym));
7122   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7123   if (ssymbuf == NULL)
7124     {
7125       free (indbuf);
7126       return NULL;
7127     }
7128
7129   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7130   ssymbuf->ssym = NULL;
7131   ssymbuf->count = shndx_count;
7132   ssymbuf->st_shndx = 0;
7133   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7134     {
7135       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7136         {
7137           ssymhead++;
7138           ssymhead->ssym = ssym;
7139           ssymhead->count = 0;
7140           ssymhead->st_shndx = (*ind)->st_shndx;
7141         }
7142       ssym->st_name = (*ind)->st_name;
7143       ssym->st_info = (*ind)->st_info;
7144       ssym->st_other = (*ind)->st_other;
7145       ssymhead->count++;
7146     }
7147   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7148               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7149                   == total_size));
7150
7151   free (indbuf);
7152   return ssymbuf;
7153 }
7154
7155 /* Check if 2 sections define the same set of local and global
7156    symbols.  */
7157
7158 static bfd_boolean
7159 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7160                                    struct bfd_link_info *info)
7161 {
7162   bfd *bfd1, *bfd2;
7163   const struct elf_backend_data *bed1, *bed2;
7164   Elf_Internal_Shdr *hdr1, *hdr2;
7165   bfd_size_type symcount1, symcount2;
7166   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7167   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7168   Elf_Internal_Sym *isym, *isymend;
7169   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7170   bfd_size_type count1, count2, i;
7171   unsigned int shndx1, shndx2;
7172   bfd_boolean result;
7173
7174   bfd1 = sec1->owner;
7175   bfd2 = sec2->owner;
7176
7177   /* Both sections have to be in ELF.  */
7178   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7179       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7180     return FALSE;
7181
7182   if (elf_section_type (sec1) != elf_section_type (sec2))
7183     return FALSE;
7184
7185   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7186   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7187   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7188     return FALSE;
7189
7190   bed1 = get_elf_backend_data (bfd1);
7191   bed2 = get_elf_backend_data (bfd2);
7192   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7193   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7194   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7195   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7196
7197   if (symcount1 == 0 || symcount2 == 0)
7198     return FALSE;
7199
7200   result = FALSE;
7201   isymbuf1 = NULL;
7202   isymbuf2 = NULL;
7203   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7204   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7205
7206   if (ssymbuf1 == NULL)
7207     {
7208       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7209                                        NULL, NULL, NULL);
7210       if (isymbuf1 == NULL)
7211         goto done;
7212
7213       if (!info->reduce_memory_overheads)
7214         elf_tdata (bfd1)->symbuf = ssymbuf1
7215           = elf_create_symbuf (symcount1, isymbuf1);
7216     }
7217
7218   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7219     {
7220       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7221                                        NULL, NULL, NULL);
7222       if (isymbuf2 == NULL)
7223         goto done;
7224
7225       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7226         elf_tdata (bfd2)->symbuf = ssymbuf2
7227           = elf_create_symbuf (symcount2, isymbuf2);
7228     }
7229
7230   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7231     {
7232       /* Optimized faster version.  */
7233       bfd_size_type lo, hi, mid;
7234       struct elf_symbol *symp;
7235       struct elf_symbuf_symbol *ssym, *ssymend;
7236
7237       lo = 0;
7238       hi = ssymbuf1->count;
7239       ssymbuf1++;
7240       count1 = 0;
7241       while (lo < hi)
7242         {
7243           mid = (lo + hi) / 2;
7244           if (shndx1 < ssymbuf1[mid].st_shndx)
7245             hi = mid;
7246           else if (shndx1 > ssymbuf1[mid].st_shndx)
7247             lo = mid + 1;
7248           else
7249             {
7250               count1 = ssymbuf1[mid].count;
7251               ssymbuf1 += mid;
7252               break;
7253             }
7254         }
7255
7256       lo = 0;
7257       hi = ssymbuf2->count;
7258       ssymbuf2++;
7259       count2 = 0;
7260       while (lo < hi)
7261         {
7262           mid = (lo + hi) / 2;
7263           if (shndx2 < ssymbuf2[mid].st_shndx)
7264             hi = mid;
7265           else if (shndx2 > ssymbuf2[mid].st_shndx)
7266             lo = mid + 1;
7267           else
7268             {
7269               count2 = ssymbuf2[mid].count;
7270               ssymbuf2 += mid;
7271               break;
7272             }
7273         }
7274
7275       if (count1 == 0 || count2 == 0 || count1 != count2)
7276         goto done;
7277
7278       symtable1 = (struct elf_symbol *)
7279           bfd_malloc (count1 * sizeof (struct elf_symbol));
7280       symtable2 = (struct elf_symbol *)
7281           bfd_malloc (count2 * sizeof (struct elf_symbol));
7282       if (symtable1 == NULL || symtable2 == NULL)
7283         goto done;
7284
7285       symp = symtable1;
7286       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7287            ssym < ssymend; ssym++, symp++)
7288         {
7289           symp->u.ssym = ssym;
7290           symp->name = bfd_elf_string_from_elf_section (bfd1,
7291                                                         hdr1->sh_link,
7292                                                         ssym->st_name);
7293         }
7294
7295       symp = symtable2;
7296       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7297            ssym < ssymend; ssym++, symp++)
7298         {
7299           symp->u.ssym = ssym;
7300           symp->name = bfd_elf_string_from_elf_section (bfd2,
7301                                                         hdr2->sh_link,
7302                                                         ssym->st_name);
7303         }
7304
7305       /* Sort symbol by name.  */
7306       qsort (symtable1, count1, sizeof (struct elf_symbol),
7307              elf_sym_name_compare);
7308       qsort (symtable2, count1, sizeof (struct elf_symbol),
7309              elf_sym_name_compare);
7310
7311       for (i = 0; i < count1; i++)
7312         /* Two symbols must have the same binding, type and name.  */
7313         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7314             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7315             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7316           goto done;
7317
7318       result = TRUE;
7319       goto done;
7320     }
7321
7322   symtable1 = (struct elf_symbol *)
7323       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7324   symtable2 = (struct elf_symbol *)
7325       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7326   if (symtable1 == NULL || symtable2 == NULL)
7327     goto done;
7328
7329   /* Count definitions in the section.  */
7330   count1 = 0;
7331   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7332     if (isym->st_shndx == shndx1)
7333       symtable1[count1++].u.isym = isym;
7334
7335   count2 = 0;
7336   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7337     if (isym->st_shndx == shndx2)
7338       symtable2[count2++].u.isym = isym;
7339
7340   if (count1 == 0 || count2 == 0 || count1 != count2)
7341     goto done;
7342
7343   for (i = 0; i < count1; i++)
7344     symtable1[i].name
7345       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7346                                          symtable1[i].u.isym->st_name);
7347
7348   for (i = 0; i < count2; i++)
7349     symtable2[i].name
7350       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7351                                          symtable2[i].u.isym->st_name);
7352
7353   /* Sort symbol by name.  */
7354   qsort (symtable1, count1, sizeof (struct elf_symbol),
7355          elf_sym_name_compare);
7356   qsort (symtable2, count1, sizeof (struct elf_symbol),
7357          elf_sym_name_compare);
7358
7359   for (i = 0; i < count1; i++)
7360     /* Two symbols must have the same binding, type and name.  */
7361     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7362         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7363         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7364       goto done;
7365
7366   result = TRUE;
7367
7368 done:
7369   if (symtable1)
7370     free (symtable1);
7371   if (symtable2)
7372     free (symtable2);
7373   if (isymbuf1)
7374     free (isymbuf1);
7375   if (isymbuf2)
7376     free (isymbuf2);
7377
7378   return result;
7379 }
7380
7381 /* Return TRUE if 2 section types are compatible.  */
7382
7383 bfd_boolean
7384 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7385                                  bfd *bbfd, const asection *bsec)
7386 {
7387   if (asec == NULL
7388       || bsec == NULL
7389       || abfd->xvec->flavour != bfd_target_elf_flavour
7390       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7391     return TRUE;
7392
7393   return elf_section_type (asec) == elf_section_type (bsec);
7394 }
7395 \f
7396 /* Final phase of ELF linker.  */
7397
7398 /* A structure we use to avoid passing large numbers of arguments.  */
7399
7400 struct elf_final_link_info
7401 {
7402   /* General link information.  */
7403   struct bfd_link_info *info;
7404   /* Output BFD.  */
7405   bfd *output_bfd;
7406   /* Symbol string table.  */
7407   struct bfd_strtab_hash *symstrtab;
7408   /* .dynsym section.  */
7409   asection *dynsym_sec;
7410   /* .hash section.  */
7411   asection *hash_sec;
7412   /* symbol version section (.gnu.version).  */
7413   asection *symver_sec;
7414   /* Buffer large enough to hold contents of any section.  */
7415   bfd_byte *contents;
7416   /* Buffer large enough to hold external relocs of any section.  */
7417   void *external_relocs;
7418   /* Buffer large enough to hold internal relocs of any section.  */
7419   Elf_Internal_Rela *internal_relocs;
7420   /* Buffer large enough to hold external local symbols of any input
7421      BFD.  */
7422   bfd_byte *external_syms;
7423   /* And a buffer for symbol section indices.  */
7424   Elf_External_Sym_Shndx *locsym_shndx;
7425   /* Buffer large enough to hold internal local symbols of any input
7426      BFD.  */
7427   Elf_Internal_Sym *internal_syms;
7428   /* Array large enough to hold a symbol index for each local symbol
7429      of any input BFD.  */
7430   long *indices;
7431   /* Array large enough to hold a section pointer for each local
7432      symbol of any input BFD.  */
7433   asection **sections;
7434   /* Buffer to hold swapped out symbols.  */
7435   bfd_byte *symbuf;
7436   /* And one for symbol section indices.  */
7437   Elf_External_Sym_Shndx *symshndxbuf;
7438   /* Number of swapped out symbols in buffer.  */
7439   size_t symbuf_count;
7440   /* Number of symbols which fit in symbuf.  */
7441   size_t symbuf_size;
7442   /* And same for symshndxbuf.  */
7443   size_t shndxbuf_size;
7444   /* Number of STT_FILE syms seen.  */
7445   size_t filesym_count;
7446 };
7447
7448 /* This struct is used to pass information to elf_link_output_extsym.  */
7449
7450 struct elf_outext_info
7451 {
7452   bfd_boolean failed;
7453   bfd_boolean localsyms;
7454   bfd_boolean need_second_pass;
7455   bfd_boolean second_pass;
7456   bfd_boolean file_sym_done;
7457   struct elf_final_link_info *flinfo;
7458 };
7459
7460
7461 /* Support for evaluating a complex relocation.
7462
7463    Complex relocations are generalized, self-describing relocations.  The
7464    implementation of them consists of two parts: complex symbols, and the
7465    relocations themselves.
7466
7467    The relocations are use a reserved elf-wide relocation type code (R_RELC
7468    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7469    information (start bit, end bit, word width, etc) into the addend.  This
7470    information is extracted from CGEN-generated operand tables within gas.
7471
7472    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7473    internal) representing prefix-notation expressions, including but not
7474    limited to those sorts of expressions normally encoded as addends in the
7475    addend field.  The symbol mangling format is:
7476
7477    <node> := <literal>
7478           |  <unary-operator> ':' <node>
7479           |  <binary-operator> ':' <node> ':' <node>
7480           ;
7481
7482    <literal> := 's' <digits=N> ':' <N character symbol name>
7483              |  'S' <digits=N> ':' <N character section name>
7484              |  '#' <hexdigits>
7485              ;
7486
7487    <binary-operator> := as in C
7488    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7489
7490 static void
7491 set_symbol_value (bfd *bfd_with_globals,
7492                   Elf_Internal_Sym *isymbuf,
7493                   size_t locsymcount,
7494                   size_t symidx,
7495                   bfd_vma val)
7496 {
7497   struct elf_link_hash_entry **sym_hashes;
7498   struct elf_link_hash_entry *h;
7499   size_t extsymoff = locsymcount;
7500
7501   if (symidx < locsymcount)
7502     {
7503       Elf_Internal_Sym *sym;
7504
7505       sym = isymbuf + symidx;
7506       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7507         {
7508           /* It is a local symbol: move it to the
7509              "absolute" section and give it a value.  */
7510           sym->st_shndx = SHN_ABS;
7511           sym->st_value = val;
7512           return;
7513         }
7514       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7515       extsymoff = 0;
7516     }
7517
7518   /* It is a global symbol: set its link type
7519      to "defined" and give it a value.  */
7520
7521   sym_hashes = elf_sym_hashes (bfd_with_globals);
7522   h = sym_hashes [symidx - extsymoff];
7523   while (h->root.type == bfd_link_hash_indirect
7524          || h->root.type == bfd_link_hash_warning)
7525     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7526   h->root.type = bfd_link_hash_defined;
7527   h->root.u.def.value = val;
7528   h->root.u.def.section = bfd_abs_section_ptr;
7529 }
7530
7531 static bfd_boolean
7532 resolve_symbol (const char *name,
7533                 bfd *input_bfd,
7534                 struct elf_final_link_info *flinfo,
7535                 bfd_vma *result,
7536                 Elf_Internal_Sym *isymbuf,
7537                 size_t locsymcount)
7538 {
7539   Elf_Internal_Sym *sym;
7540   struct bfd_link_hash_entry *global_entry;
7541   const char *candidate = NULL;
7542   Elf_Internal_Shdr *symtab_hdr;
7543   size_t i;
7544
7545   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7546
7547   for (i = 0; i < locsymcount; ++ i)
7548     {
7549       sym = isymbuf + i;
7550
7551       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7552         continue;
7553
7554       candidate = bfd_elf_string_from_elf_section (input_bfd,
7555                                                    symtab_hdr->sh_link,
7556                                                    sym->st_name);
7557 #ifdef DEBUG
7558       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7559               name, candidate, (unsigned long) sym->st_value);
7560 #endif
7561       if (candidate && strcmp (candidate, name) == 0)
7562         {
7563           asection *sec = flinfo->sections [i];
7564
7565           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7566           *result += sec->output_offset + sec->output_section->vma;
7567 #ifdef DEBUG
7568           printf ("Found symbol with value %8.8lx\n",
7569                   (unsigned long) *result);
7570 #endif
7571           return TRUE;
7572         }
7573     }
7574
7575   /* Hmm, haven't found it yet. perhaps it is a global.  */
7576   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7577                                        FALSE, FALSE, TRUE);
7578   if (!global_entry)
7579     return FALSE;
7580
7581   if (global_entry->type == bfd_link_hash_defined
7582       || global_entry->type == bfd_link_hash_defweak)
7583     {
7584       *result = (global_entry->u.def.value
7585                  + global_entry->u.def.section->output_section->vma
7586                  + global_entry->u.def.section->output_offset);
7587 #ifdef DEBUG
7588       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7589               global_entry->root.string, (unsigned long) *result);
7590 #endif
7591       return TRUE;
7592     }
7593
7594   return FALSE;
7595 }
7596
7597 static bfd_boolean
7598 resolve_section (const char *name,
7599                  asection *sections,
7600                  bfd_vma *result)
7601 {
7602   asection *curr;
7603   unsigned int len;
7604
7605   for (curr = sections; curr; curr = curr->next)
7606     if (strcmp (curr->name, name) == 0)
7607       {
7608         *result = curr->vma;
7609         return TRUE;
7610       }
7611
7612   /* Hmm. still haven't found it. try pseudo-section names.  */
7613   for (curr = sections; curr; curr = curr->next)
7614     {
7615       len = strlen (curr->name);
7616       if (len > strlen (name))
7617         continue;
7618
7619       if (strncmp (curr->name, name, len) == 0)
7620         {
7621           if (strncmp (".end", name + len, 4) == 0)
7622             {
7623               *result = curr->vma + curr->size;
7624               return TRUE;
7625             }
7626
7627           /* Insert more pseudo-section names here, if you like.  */
7628         }
7629     }
7630
7631   return FALSE;
7632 }
7633
7634 static void
7635 undefined_reference (const char *reftype, const char *name)
7636 {
7637   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7638                       reftype, name);
7639 }
7640
7641 static bfd_boolean
7642 eval_symbol (bfd_vma *result,
7643              const char **symp,
7644              bfd *input_bfd,
7645              struct elf_final_link_info *flinfo,
7646              bfd_vma dot,
7647              Elf_Internal_Sym *isymbuf,
7648              size_t locsymcount,
7649              int signed_p)
7650 {
7651   size_t len;
7652   size_t symlen;
7653   bfd_vma a;
7654   bfd_vma b;
7655   char symbuf[4096];
7656   const char *sym = *symp;
7657   const char *symend;
7658   bfd_boolean symbol_is_section = FALSE;
7659
7660   len = strlen (sym);
7661   symend = sym + len;
7662
7663   if (len < 1 || len > sizeof (symbuf))
7664     {
7665       bfd_set_error (bfd_error_invalid_operation);
7666       return FALSE;
7667     }
7668
7669   switch (* sym)
7670     {
7671     case '.':
7672       *result = dot;
7673       *symp = sym + 1;
7674       return TRUE;
7675
7676     case '#':
7677       ++sym;
7678       *result = strtoul (sym, (char **) symp, 16);
7679       return TRUE;
7680
7681     case 'S':
7682       symbol_is_section = TRUE;
7683     case 's':
7684       ++sym;
7685       symlen = strtol (sym, (char **) symp, 10);
7686       sym = *symp + 1; /* Skip the trailing ':'.  */
7687
7688       if (symend < sym || symlen + 1 > sizeof (symbuf))
7689         {
7690           bfd_set_error (bfd_error_invalid_operation);
7691           return FALSE;
7692         }
7693
7694       memcpy (symbuf, sym, symlen);
7695       symbuf[symlen] = '\0';
7696       *symp = sym + symlen;
7697
7698       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7699          the symbol as a section, or vice-versa. so we're pretty liberal in our
7700          interpretation here; section means "try section first", not "must be a
7701          section", and likewise with symbol.  */
7702
7703       if (symbol_is_section)
7704         {
7705           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7706               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7707                                   isymbuf, locsymcount))
7708             {
7709               undefined_reference ("section", symbuf);
7710               return FALSE;
7711             }
7712         }
7713       else
7714         {
7715           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7716                                isymbuf, locsymcount)
7717               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7718                                    result))
7719             {
7720               undefined_reference ("symbol", symbuf);
7721               return FALSE;
7722             }
7723         }
7724
7725       return TRUE;
7726
7727       /* All that remains are operators.  */
7728
7729 #define UNARY_OP(op)                                            \
7730   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7731     {                                                           \
7732       sym += strlen (#op);                                      \
7733       if (*sym == ':')                                          \
7734         ++sym;                                                  \
7735       *symp = sym;                                              \
7736       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7737                         isymbuf, locsymcount, signed_p))        \
7738         return FALSE;                                           \
7739       if (signed_p)                                             \
7740         *result = op ((bfd_signed_vma) a);                      \
7741       else                                                      \
7742         *result = op a;                                         \
7743       return TRUE;                                              \
7744     }
7745
7746 #define BINARY_OP(op)                                           \
7747   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7748     {                                                           \
7749       sym += strlen (#op);                                      \
7750       if (*sym == ':')                                          \
7751         ++sym;                                                  \
7752       *symp = sym;                                              \
7753       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7754                         isymbuf, locsymcount, signed_p))        \
7755         return FALSE;                                           \
7756       ++*symp;                                                  \
7757       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7758                         isymbuf, locsymcount, signed_p))        \
7759         return FALSE;                                           \
7760       if (signed_p)                                             \
7761         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7762       else                                                      \
7763         *result = a op b;                                       \
7764       return TRUE;                                              \
7765     }
7766
7767     default:
7768       UNARY_OP  (0-);
7769       BINARY_OP (<<);
7770       BINARY_OP (>>);
7771       BINARY_OP (==);
7772       BINARY_OP (!=);
7773       BINARY_OP (<=);
7774       BINARY_OP (>=);
7775       BINARY_OP (&&);
7776       BINARY_OP (||);
7777       UNARY_OP  (~);
7778       UNARY_OP  (!);
7779       BINARY_OP (*);
7780       BINARY_OP (/);
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 #undef UNARY_OP
7790 #undef BINARY_OP
7791       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7792       bfd_set_error (bfd_error_invalid_operation);
7793       return FALSE;
7794     }
7795 }
7796
7797 static void
7798 put_value (bfd_vma size,
7799            unsigned long chunksz,
7800            bfd *input_bfd,
7801            bfd_vma x,
7802            bfd_byte *location)
7803 {
7804   location += (size - chunksz);
7805
7806   for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
7807     {
7808       switch (chunksz)
7809         {
7810         default:
7811         case 0:
7812           abort ();
7813         case 1:
7814           bfd_put_8 (input_bfd, x, location);
7815           break;
7816         case 2:
7817           bfd_put_16 (input_bfd, x, location);
7818           break;
7819         case 4:
7820           bfd_put_32 (input_bfd, x, location);
7821           break;
7822         case 8:
7823 #ifdef BFD64
7824           bfd_put_64 (input_bfd, x, location);
7825 #else
7826           abort ();
7827 #endif
7828           break;
7829         }
7830     }
7831 }
7832
7833 static bfd_vma
7834 get_value (bfd_vma size,
7835            unsigned long chunksz,
7836            bfd *input_bfd,
7837            bfd_byte *location)
7838 {
7839   int shift;
7840   bfd_vma x = 0;
7841
7842   /* Sanity checks.  */
7843   BFD_ASSERT (chunksz <= sizeof (x)
7844               && size >= chunksz
7845               && chunksz != 0
7846               && (size % chunksz) == 0
7847               && input_bfd != NULL
7848               && location != NULL);
7849
7850   if (chunksz == sizeof (x))
7851     {
7852       BFD_ASSERT (size == chunksz);
7853
7854       /* Make sure that we do not perform an undefined shift operation.
7855          We know that size == chunksz so there will only be one iteration
7856          of the loop below.  */
7857       shift = 0;
7858     }
7859   else
7860     shift = 8 * chunksz;
7861
7862   for (; size; size -= chunksz, location += chunksz)
7863     {
7864       switch (chunksz)
7865         {
7866         case 1:
7867           x = (x << shift) | bfd_get_8 (input_bfd, location);
7868           break;
7869         case 2:
7870           x = (x << shift) | bfd_get_16 (input_bfd, location);
7871           break;
7872         case 4:
7873           x = (x << shift) | bfd_get_32 (input_bfd, location);
7874           break;
7875 #ifdef BFD64
7876         case 8:
7877           x = (x << shift) | bfd_get_64 (input_bfd, location);
7878           break;
7879 #endif
7880         default:
7881           abort ();
7882         }
7883     }
7884   return x;
7885 }
7886
7887 static void
7888 decode_complex_addend (unsigned long *start,   /* in bits */
7889                        unsigned long *oplen,   /* in bits */
7890                        unsigned long *len,     /* in bits */
7891                        unsigned long *wordsz,  /* in bytes */
7892                        unsigned long *chunksz, /* in bytes */
7893                        unsigned long *lsb0_p,
7894                        unsigned long *signed_p,
7895                        unsigned long *trunc_p,
7896                        unsigned long encoded)
7897 {
7898   * start     =  encoded        & 0x3F;
7899   * len       = (encoded >>  6) & 0x3F;
7900   * oplen     = (encoded >> 12) & 0x3F;
7901   * wordsz    = (encoded >> 18) & 0xF;
7902   * chunksz   = (encoded >> 22) & 0xF;
7903   * lsb0_p    = (encoded >> 27) & 1;
7904   * signed_p  = (encoded >> 28) & 1;
7905   * trunc_p   = (encoded >> 29) & 1;
7906 }
7907
7908 bfd_reloc_status_type
7909 bfd_elf_perform_complex_relocation (bfd *input_bfd,
7910                                     asection *input_section ATTRIBUTE_UNUSED,
7911                                     bfd_byte *contents,
7912                                     Elf_Internal_Rela *rel,
7913                                     bfd_vma relocation)
7914 {
7915   bfd_vma shift, x, mask;
7916   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
7917   bfd_reloc_status_type r;
7918
7919   /*  Perform this reloc, since it is complex.
7920       (this is not to say that it necessarily refers to a complex
7921       symbol; merely that it is a self-describing CGEN based reloc.
7922       i.e. the addend has the complete reloc information (bit start, end,
7923       word size, etc) encoded within it.).  */
7924
7925   decode_complex_addend (&start, &oplen, &len, &wordsz,
7926                          &chunksz, &lsb0_p, &signed_p,
7927                          &trunc_p, rel->r_addend);
7928
7929   mask = (((1L << (len - 1)) - 1) << 1) | 1;
7930
7931   if (lsb0_p)
7932     shift = (start + 1) - len;
7933   else
7934     shift = (8 * wordsz) - (start + len);
7935
7936   /* FIXME: octets_per_byte.  */
7937   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7938
7939 #ifdef DEBUG
7940   printf ("Doing complex reloc: "
7941           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7942           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7943           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7944           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7945           oplen, (unsigned long) x, (unsigned long) mask,
7946           (unsigned long) relocation);
7947 #endif
7948
7949   r = bfd_reloc_ok;
7950   if (! trunc_p)
7951     /* Now do an overflow check.  */
7952     r = bfd_check_overflow ((signed_p
7953                              ? complain_overflow_signed
7954                              : complain_overflow_unsigned),
7955                             len, 0, (8 * wordsz),
7956                             relocation);
7957
7958   /* Do the deed.  */
7959   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7960
7961 #ifdef DEBUG
7962   printf ("           relocation: %8.8lx\n"
7963           "         shifted mask: %8.8lx\n"
7964           " shifted/masked reloc: %8.8lx\n"
7965           "               result: %8.8lx\n",
7966           (unsigned long) relocation, (unsigned long) (mask << shift),
7967           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
7968 #endif
7969   /* FIXME: octets_per_byte.  */
7970   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7971   return r;
7972 }
7973
7974 /* qsort comparison functions sorting external relocs by r_offset.  */
7975
7976 static int
7977 cmp_ext32l_r_offset (const void *p, const void *q)
7978 {
7979   union aligned32
7980   {
7981     uint32_t v;
7982     unsigned char c[4];
7983   };
7984   const union aligned32 *a
7985     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
7986   const union aligned32 *b
7987     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
7988
7989   uint32_t aval = (  (uint32_t) a->c[0]
7990                    | (uint32_t) a->c[1] << 8
7991                    | (uint32_t) a->c[2] << 16
7992                    | (uint32_t) a->c[3] << 24);
7993   uint32_t bval = (  (uint32_t) b->c[0]
7994                    | (uint32_t) b->c[1] << 8
7995                    | (uint32_t) b->c[2] << 16
7996                    | (uint32_t) b->c[3] << 24);
7997   if (aval < bval)
7998     return -1;
7999   else if (aval > bval)
8000     return 1;
8001   return 0;
8002 }
8003
8004 static int
8005 cmp_ext32b_r_offset (const void *p, const void *q)
8006 {
8007   union aligned32
8008   {
8009     uint32_t v;
8010     unsigned char c[4];
8011   };
8012   const union aligned32 *a
8013     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8014   const union aligned32 *b
8015     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8016
8017   uint32_t aval = (  (uint32_t) a->c[0] << 24
8018                    | (uint32_t) a->c[1] << 16
8019                    | (uint32_t) a->c[2] << 8
8020                    | (uint32_t) a->c[3]);
8021   uint32_t bval = (  (uint32_t) b->c[0] << 24
8022                    | (uint32_t) b->c[1] << 16
8023                    | (uint32_t) b->c[2] << 8
8024                    | (uint32_t) b->c[3]);
8025   if (aval < bval)
8026     return -1;
8027   else if (aval > bval)
8028     return 1;
8029   return 0;
8030 }
8031
8032 #ifdef BFD_HOST_64_BIT
8033 static int
8034 cmp_ext64l_r_offset (const void *p, const void *q)
8035 {
8036   union aligned64
8037   {
8038     uint64_t v;
8039     unsigned char c[8];
8040   };
8041   const union aligned64 *a
8042     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8043   const union aligned64 *b
8044     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8045
8046   uint64_t aval = (  (uint64_t) a->c[0]
8047                    | (uint64_t) a->c[1] << 8
8048                    | (uint64_t) a->c[2] << 16
8049                    | (uint64_t) a->c[3] << 24
8050                    | (uint64_t) a->c[4] << 32
8051                    | (uint64_t) a->c[5] << 40
8052                    | (uint64_t) a->c[6] << 48
8053                    | (uint64_t) a->c[7] << 56);
8054   uint64_t bval = (  (uint64_t) b->c[0]
8055                    | (uint64_t) b->c[1] << 8
8056                    | (uint64_t) b->c[2] << 16
8057                    | (uint64_t) b->c[3] << 24
8058                    | (uint64_t) b->c[4] << 32
8059                    | (uint64_t) b->c[5] << 40
8060                    | (uint64_t) b->c[6] << 48
8061                    | (uint64_t) b->c[7] << 56);
8062   if (aval < bval)
8063     return -1;
8064   else if (aval > bval)
8065     return 1;
8066   return 0;
8067 }
8068
8069 static int
8070 cmp_ext64b_r_offset (const void *p, const void *q)
8071 {
8072   union aligned64
8073   {
8074     uint64_t v;
8075     unsigned char c[8];
8076   };
8077   const union aligned64 *a
8078     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8079   const union aligned64 *b
8080     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8081
8082   uint64_t aval = (  (uint64_t) a->c[0] << 56
8083                    | (uint64_t) a->c[1] << 48
8084                    | (uint64_t) a->c[2] << 40
8085                    | (uint64_t) a->c[3] << 32
8086                    | (uint64_t) a->c[4] << 24
8087                    | (uint64_t) a->c[5] << 16
8088                    | (uint64_t) a->c[6] << 8
8089                    | (uint64_t) a->c[7]);
8090   uint64_t bval = (  (uint64_t) b->c[0] << 56
8091                    | (uint64_t) b->c[1] << 48
8092                    | (uint64_t) b->c[2] << 40
8093                    | (uint64_t) b->c[3] << 32
8094                    | (uint64_t) b->c[4] << 24
8095                    | (uint64_t) b->c[5] << 16
8096                    | (uint64_t) b->c[6] << 8
8097                    | (uint64_t) b->c[7]);
8098   if (aval < bval)
8099     return -1;
8100   else if (aval > bval)
8101     return 1;
8102   return 0;
8103 }
8104 #endif
8105
8106 /* When performing a relocatable link, the input relocations are
8107    preserved.  But, if they reference global symbols, the indices
8108    referenced must be updated.  Update all the relocations found in
8109    RELDATA.  */
8110
8111 static void
8112 elf_link_adjust_relocs (bfd *abfd,
8113                         struct bfd_elf_section_reloc_data *reldata,
8114                         bfd_boolean sort)
8115 {
8116   unsigned int i;
8117   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8118   bfd_byte *erela;
8119   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8120   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8121   bfd_vma r_type_mask;
8122   int r_sym_shift;
8123   unsigned int count = reldata->count;
8124   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8125
8126   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8127     {
8128       swap_in = bed->s->swap_reloc_in;
8129       swap_out = bed->s->swap_reloc_out;
8130     }
8131   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8132     {
8133       swap_in = bed->s->swap_reloca_in;
8134       swap_out = bed->s->swap_reloca_out;
8135     }
8136   else
8137     abort ();
8138
8139   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8140     abort ();
8141
8142   if (bed->s->arch_size == 32)
8143     {
8144       r_type_mask = 0xff;
8145       r_sym_shift = 8;
8146     }
8147   else
8148     {
8149       r_type_mask = 0xffffffff;
8150       r_sym_shift = 32;
8151     }
8152
8153   erela = reldata->hdr->contents;
8154   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8155     {
8156       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8157       unsigned int j;
8158
8159       if (*rel_hash == NULL)
8160         continue;
8161
8162       BFD_ASSERT ((*rel_hash)->indx >= 0);
8163
8164       (*swap_in) (abfd, erela, irela);
8165       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8166         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8167                            | (irela[j].r_info & r_type_mask));
8168       (*swap_out) (abfd, irela, erela);
8169     }
8170
8171   if (sort)
8172     {
8173       int (*compare) (const void *, const void *);
8174
8175       if (bed->s->arch_size == 32)
8176         {
8177           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8178             compare = cmp_ext32l_r_offset;
8179           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8180             compare = cmp_ext32b_r_offset;
8181           else
8182             abort ();
8183         }
8184       else
8185         {
8186 #ifdef BFD_HOST_64_BIT
8187           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8188             compare = cmp_ext64l_r_offset;
8189           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8190             compare = cmp_ext64b_r_offset;
8191           else
8192 #endif
8193             abort ();
8194         }
8195       qsort (reldata->hdr->contents, count, reldata->hdr->sh_entsize, compare);
8196       free (reldata->hashes);
8197       reldata->hashes = NULL;
8198     }
8199 }
8200
8201 struct elf_link_sort_rela
8202 {
8203   union {
8204     bfd_vma offset;
8205     bfd_vma sym_mask;
8206   } u;
8207   enum elf_reloc_type_class type;
8208   /* We use this as an array of size int_rels_per_ext_rel.  */
8209   Elf_Internal_Rela rela[1];
8210 };
8211
8212 static int
8213 elf_link_sort_cmp1 (const void *A, const void *B)
8214 {
8215   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8216   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8217   int relativea, relativeb;
8218
8219   relativea = a->type == reloc_class_relative;
8220   relativeb = b->type == reloc_class_relative;
8221
8222   if (relativea < relativeb)
8223     return 1;
8224   if (relativea > relativeb)
8225     return -1;
8226   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8227     return -1;
8228   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8229     return 1;
8230   if (a->rela->r_offset < b->rela->r_offset)
8231     return -1;
8232   if (a->rela->r_offset > b->rela->r_offset)
8233     return 1;
8234   return 0;
8235 }
8236
8237 static int
8238 elf_link_sort_cmp2 (const void *A, const void *B)
8239 {
8240   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8241   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8242
8243   if (a->type < b->type)
8244     return -1;
8245   if (a->type > b->type)
8246     return 1;
8247   if (a->u.offset < b->u.offset)
8248     return -1;
8249   if (a->u.offset > b->u.offset)
8250     return 1;
8251   if (a->rela->r_offset < b->rela->r_offset)
8252     return -1;
8253   if (a->rela->r_offset > b->rela->r_offset)
8254     return 1;
8255   return 0;
8256 }
8257
8258 static size_t
8259 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8260 {
8261   asection *dynamic_relocs;
8262   asection *rela_dyn;
8263   asection *rel_dyn;
8264   bfd_size_type count, size;
8265   size_t i, ret, sort_elt, ext_size;
8266   bfd_byte *sort, *s_non_relative, *p;
8267   struct elf_link_sort_rela *sq;
8268   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8269   int i2e = bed->s->int_rels_per_ext_rel;
8270   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8271   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8272   struct bfd_link_order *lo;
8273   bfd_vma r_sym_mask;
8274   bfd_boolean use_rela;
8275
8276   /* Find a dynamic reloc section.  */
8277   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8278   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8279   if (rela_dyn != NULL && rela_dyn->size > 0
8280       && rel_dyn != NULL && rel_dyn->size > 0)
8281     {
8282       bfd_boolean use_rela_initialised = FALSE;
8283
8284       /* This is just here to stop gcc from complaining.
8285          It's initialization checking code is not perfect.  */
8286       use_rela = TRUE;
8287
8288       /* Both sections are present.  Examine the sizes
8289          of the indirect sections to help us choose.  */
8290       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8291         if (lo->type == bfd_indirect_link_order)
8292           {
8293             asection *o = lo->u.indirect.section;
8294
8295             if ((o->size % bed->s->sizeof_rela) == 0)
8296               {
8297                 if ((o->size % bed->s->sizeof_rel) == 0)
8298                   /* Section size is divisible by both rel and rela sizes.
8299                      It is of no help to us.  */
8300                   ;
8301                 else
8302                   {
8303                     /* Section size is only divisible by rela.  */
8304                     if (use_rela_initialised && (use_rela == FALSE))
8305                       {
8306                         _bfd_error_handler
8307                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8308                         bfd_set_error (bfd_error_invalid_operation);
8309                         return 0;
8310                       }
8311                     else
8312                       {
8313                         use_rela = TRUE;
8314                         use_rela_initialised = TRUE;
8315                       }
8316                   }
8317               }
8318             else if ((o->size % bed->s->sizeof_rel) == 0)
8319               {
8320                 /* Section size is only divisible by rel.  */
8321                 if (use_rela_initialised && (use_rela == TRUE))
8322                   {
8323                     _bfd_error_handler
8324                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8325                     bfd_set_error (bfd_error_invalid_operation);
8326                     return 0;
8327                   }
8328                 else
8329                   {
8330                     use_rela = FALSE;
8331                     use_rela_initialised = TRUE;
8332                   }
8333               }
8334             else
8335               {
8336                 /* The section size is not divisible by either - something is wrong.  */
8337                 _bfd_error_handler
8338                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8339                 bfd_set_error (bfd_error_invalid_operation);
8340                 return 0;
8341               }
8342           }
8343
8344       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8345         if (lo->type == bfd_indirect_link_order)
8346           {
8347             asection *o = lo->u.indirect.section;
8348
8349             if ((o->size % bed->s->sizeof_rela) == 0)
8350               {
8351                 if ((o->size % bed->s->sizeof_rel) == 0)
8352                   /* Section size is divisible by both rel and rela sizes.
8353                      It is of no help to us.  */
8354                   ;
8355                 else
8356                   {
8357                     /* Section size is only divisible by rela.  */
8358                     if (use_rela_initialised && (use_rela == FALSE))
8359                       {
8360                         _bfd_error_handler
8361                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8362                         bfd_set_error (bfd_error_invalid_operation);
8363                         return 0;
8364                       }
8365                     else
8366                       {
8367                         use_rela = TRUE;
8368                         use_rela_initialised = TRUE;
8369                       }
8370                   }
8371               }
8372             else if ((o->size % bed->s->sizeof_rel) == 0)
8373               {
8374                 /* Section size is only divisible by rel.  */
8375                 if (use_rela_initialised && (use_rela == TRUE))
8376                   {
8377                     _bfd_error_handler
8378                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8379                     bfd_set_error (bfd_error_invalid_operation);
8380                     return 0;
8381                   }
8382                 else
8383                   {
8384                     use_rela = FALSE;
8385                     use_rela_initialised = TRUE;
8386                   }
8387               }
8388             else
8389               {
8390                 /* The section size is not divisible by either - something is wrong.  */
8391                 _bfd_error_handler
8392                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8393                 bfd_set_error (bfd_error_invalid_operation);
8394                 return 0;
8395               }
8396           }
8397
8398       if (! use_rela_initialised)
8399         /* Make a guess.  */
8400         use_rela = TRUE;
8401     }
8402   else if (rela_dyn != NULL && rela_dyn->size > 0)
8403     use_rela = TRUE;
8404   else if (rel_dyn != NULL && rel_dyn->size > 0)
8405     use_rela = FALSE;
8406   else
8407     return 0;
8408
8409   if (use_rela)
8410     {
8411       dynamic_relocs = rela_dyn;
8412       ext_size = bed->s->sizeof_rela;
8413       swap_in = bed->s->swap_reloca_in;
8414       swap_out = bed->s->swap_reloca_out;
8415     }
8416   else
8417     {
8418       dynamic_relocs = rel_dyn;
8419       ext_size = bed->s->sizeof_rel;
8420       swap_in = bed->s->swap_reloc_in;
8421       swap_out = bed->s->swap_reloc_out;
8422     }
8423
8424   size = 0;
8425   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8426     if (lo->type == bfd_indirect_link_order)
8427       size += lo->u.indirect.section->size;
8428
8429   if (size != dynamic_relocs->size)
8430     return 0;
8431
8432   sort_elt = (sizeof (struct elf_link_sort_rela)
8433               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8434
8435   count = dynamic_relocs->size / ext_size;
8436   if (count == 0)
8437     return 0;
8438   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8439
8440   if (sort == NULL)
8441     {
8442       (*info->callbacks->warning)
8443         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8444       return 0;
8445     }
8446
8447   if (bed->s->arch_size == 32)
8448     r_sym_mask = ~(bfd_vma) 0xff;
8449   else
8450     r_sym_mask = ~(bfd_vma) 0xffffffff;
8451
8452   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8453     if (lo->type == bfd_indirect_link_order)
8454       {
8455         bfd_byte *erel, *erelend;
8456         asection *o = lo->u.indirect.section;
8457
8458         if (o->contents == NULL && o->size != 0)
8459           {
8460             /* This is a reloc section that is being handled as a normal
8461                section.  See bfd_section_from_shdr.  We can't combine
8462                relocs in this case.  */
8463             free (sort);
8464             return 0;
8465           }
8466         erel = o->contents;
8467         erelend = o->contents + o->size;
8468         /* FIXME: octets_per_byte.  */
8469         p = sort + o->output_offset / ext_size * sort_elt;
8470
8471         while (erel < erelend)
8472           {
8473             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8474
8475             (*swap_in) (abfd, erel, s->rela);
8476             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8477             s->u.sym_mask = r_sym_mask;
8478             p += sort_elt;
8479             erel += ext_size;
8480           }
8481       }
8482
8483   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8484
8485   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8486     {
8487       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8488       if (s->type != reloc_class_relative)
8489         break;
8490     }
8491   ret = i;
8492   s_non_relative = p;
8493
8494   sq = (struct elf_link_sort_rela *) s_non_relative;
8495   for (; i < count; i++, p += sort_elt)
8496     {
8497       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8498       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8499         sq = sp;
8500       sp->u.offset = sq->rela->r_offset;
8501     }
8502
8503   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8504
8505   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8506     if (lo->type == bfd_indirect_link_order)
8507       {
8508         bfd_byte *erel, *erelend;
8509         asection *o = lo->u.indirect.section;
8510
8511         erel = o->contents;
8512         erelend = o->contents + o->size;
8513         /* FIXME: octets_per_byte.  */
8514         p = sort + o->output_offset / ext_size * sort_elt;
8515         while (erel < erelend)
8516           {
8517             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8518             (*swap_out) (abfd, s->rela, erel);
8519             p += sort_elt;
8520             erel += ext_size;
8521           }
8522       }
8523
8524   free (sort);
8525   *psec = dynamic_relocs;
8526   return ret;
8527 }
8528
8529 /* Flush the output symbols to the file.  */
8530
8531 static bfd_boolean
8532 elf_link_flush_output_syms (struct elf_final_link_info *flinfo,
8533                             const struct elf_backend_data *bed)
8534 {
8535   if (flinfo->symbuf_count > 0)
8536     {
8537       Elf_Internal_Shdr *hdr;
8538       file_ptr pos;
8539       bfd_size_type amt;
8540
8541       hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8542       pos = hdr->sh_offset + hdr->sh_size;
8543       amt = flinfo->symbuf_count * bed->s->sizeof_sym;
8544       if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) != 0
8545           || bfd_bwrite (flinfo->symbuf, amt, flinfo->output_bfd) != amt)
8546         return FALSE;
8547
8548       hdr->sh_size += amt;
8549       flinfo->symbuf_count = 0;
8550     }
8551
8552   return TRUE;
8553 }
8554
8555 /* Add a symbol to the output symbol table.  */
8556
8557 static int
8558 elf_link_output_sym (struct elf_final_link_info *flinfo,
8559                      const char *name,
8560                      Elf_Internal_Sym *elfsym,
8561                      asection *input_sec,
8562                      struct elf_link_hash_entry *h)
8563 {
8564   bfd_byte *dest;
8565   Elf_External_Sym_Shndx *destshndx;
8566   int (*output_symbol_hook)
8567     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8568      struct elf_link_hash_entry *);
8569   const struct elf_backend_data *bed;
8570
8571   bed = get_elf_backend_data (flinfo->output_bfd);
8572   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8573   if (output_symbol_hook != NULL)
8574     {
8575       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8576       if (ret != 1)
8577         return ret;
8578     }
8579
8580   if (name == NULL || *name == '\0')
8581     elfsym->st_name = 0;
8582   else if (input_sec->flags & SEC_EXCLUDE)
8583     elfsym->st_name = 0;
8584   else
8585     {
8586       elfsym->st_name = (unsigned long) _bfd_stringtab_add (flinfo->symstrtab,
8587                                                             name, TRUE, FALSE);
8588       if (elfsym->st_name == (unsigned long) -1)
8589         return 0;
8590     }
8591
8592   if (flinfo->symbuf_count >= flinfo->symbuf_size)
8593     {
8594       if (! elf_link_flush_output_syms (flinfo, bed))
8595         return 0;
8596     }
8597
8598   dest = flinfo->symbuf + flinfo->symbuf_count * bed->s->sizeof_sym;
8599   destshndx = flinfo->symshndxbuf;
8600   if (destshndx != NULL)
8601     {
8602       if (bfd_get_symcount (flinfo->output_bfd) >= flinfo->shndxbuf_size)
8603         {
8604           bfd_size_type amt;
8605
8606           amt = flinfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
8607           destshndx = (Elf_External_Sym_Shndx *) bfd_realloc (destshndx,
8608                                                               amt * 2);
8609           if (destshndx == NULL)
8610             return 0;
8611           flinfo->symshndxbuf = destshndx;
8612           memset ((char *) destshndx + amt, 0, amt);
8613           flinfo->shndxbuf_size *= 2;
8614         }
8615       destshndx += bfd_get_symcount (flinfo->output_bfd);
8616     }
8617
8618   bed->s->swap_symbol_out (flinfo->output_bfd, elfsym, dest, destshndx);
8619   flinfo->symbuf_count += 1;
8620   bfd_get_symcount (flinfo->output_bfd) += 1;
8621
8622   return 1;
8623 }
8624
8625 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8626
8627 static bfd_boolean
8628 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8629 {
8630   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8631       && sym->st_shndx < SHN_LORESERVE)
8632     {
8633       /* The gABI doesn't support dynamic symbols in output sections
8634          beyond 64k.  */
8635       (*_bfd_error_handler)
8636         (_("%B: Too many sections: %d (>= %d)"),
8637          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8638       bfd_set_error (bfd_error_nonrepresentable_section);
8639       return FALSE;
8640     }
8641   return TRUE;
8642 }
8643
8644 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8645    allowing an unsatisfied unversioned symbol in the DSO to match a
8646    versioned symbol that would normally require an explicit version.
8647    We also handle the case that a DSO references a hidden symbol
8648    which may be satisfied by a versioned symbol in another DSO.  */
8649
8650 static bfd_boolean
8651 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8652                                  const struct elf_backend_data *bed,
8653                                  struct elf_link_hash_entry *h)
8654 {
8655   bfd *abfd;
8656   struct elf_link_loaded_list *loaded;
8657
8658   if (!is_elf_hash_table (info->hash))
8659     return FALSE;
8660
8661   /* Check indirect symbol.  */
8662   while (h->root.type == bfd_link_hash_indirect)
8663     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8664
8665   switch (h->root.type)
8666     {
8667     default:
8668       abfd = NULL;
8669       break;
8670
8671     case bfd_link_hash_undefined:
8672     case bfd_link_hash_undefweak:
8673       abfd = h->root.u.undef.abfd;
8674       if ((abfd->flags & DYNAMIC) == 0
8675           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8676         return FALSE;
8677       break;
8678
8679     case bfd_link_hash_defined:
8680     case bfd_link_hash_defweak:
8681       abfd = h->root.u.def.section->owner;
8682       break;
8683
8684     case bfd_link_hash_common:
8685       abfd = h->root.u.c.p->section->owner;
8686       break;
8687     }
8688   BFD_ASSERT (abfd != NULL);
8689
8690   for (loaded = elf_hash_table (info)->loaded;
8691        loaded != NULL;
8692        loaded = loaded->next)
8693     {
8694       bfd *input;
8695       Elf_Internal_Shdr *hdr;
8696       bfd_size_type symcount;
8697       bfd_size_type extsymcount;
8698       bfd_size_type extsymoff;
8699       Elf_Internal_Shdr *versymhdr;
8700       Elf_Internal_Sym *isym;
8701       Elf_Internal_Sym *isymend;
8702       Elf_Internal_Sym *isymbuf;
8703       Elf_External_Versym *ever;
8704       Elf_External_Versym *extversym;
8705
8706       input = loaded->abfd;
8707
8708       /* We check each DSO for a possible hidden versioned definition.  */
8709       if (input == abfd
8710           || (input->flags & DYNAMIC) == 0
8711           || elf_dynversym (input) == 0)
8712         continue;
8713
8714       hdr = &elf_tdata (input)->dynsymtab_hdr;
8715
8716       symcount = hdr->sh_size / bed->s->sizeof_sym;
8717       if (elf_bad_symtab (input))
8718         {
8719           extsymcount = symcount;
8720           extsymoff = 0;
8721         }
8722       else
8723         {
8724           extsymcount = symcount - hdr->sh_info;
8725           extsymoff = hdr->sh_info;
8726         }
8727
8728       if (extsymcount == 0)
8729         continue;
8730
8731       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8732                                       NULL, NULL, NULL);
8733       if (isymbuf == NULL)
8734         return FALSE;
8735
8736       /* Read in any version definitions.  */
8737       versymhdr = &elf_tdata (input)->dynversym_hdr;
8738       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8739       if (extversym == NULL)
8740         goto error_ret;
8741
8742       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8743           || (bfd_bread (extversym, versymhdr->sh_size, input)
8744               != versymhdr->sh_size))
8745         {
8746           free (extversym);
8747         error_ret:
8748           free (isymbuf);
8749           return FALSE;
8750         }
8751
8752       ever = extversym + extsymoff;
8753       isymend = isymbuf + extsymcount;
8754       for (isym = isymbuf; isym < isymend; isym++, ever++)
8755         {
8756           const char *name;
8757           Elf_Internal_Versym iver;
8758           unsigned short version_index;
8759
8760           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8761               || isym->st_shndx == SHN_UNDEF)
8762             continue;
8763
8764           name = bfd_elf_string_from_elf_section (input,
8765                                                   hdr->sh_link,
8766                                                   isym->st_name);
8767           if (strcmp (name, h->root.root.string) != 0)
8768             continue;
8769
8770           _bfd_elf_swap_versym_in (input, ever, &iver);
8771
8772           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8773               && !(h->def_regular
8774                    && h->forced_local))
8775             {
8776               /* If we have a non-hidden versioned sym, then it should
8777                  have provided a definition for the undefined sym unless
8778                  it is defined in a non-shared object and forced local.
8779                */
8780               abort ();
8781             }
8782
8783           version_index = iver.vs_vers & VERSYM_VERSION;
8784           if (version_index == 1 || version_index == 2)
8785             {
8786               /* This is the base or first version.  We can use it.  */
8787               free (extversym);
8788               free (isymbuf);
8789               return TRUE;
8790             }
8791         }
8792
8793       free (extversym);
8794       free (isymbuf);
8795     }
8796
8797   return FALSE;
8798 }
8799
8800 /* Add an external symbol to the symbol table.  This is called from
8801    the hash table traversal routine.  When generating a shared object,
8802    we go through the symbol table twice.  The first time we output
8803    anything that might have been forced to local scope in a version
8804    script.  The second time we output the symbols that are still
8805    global symbols.  */
8806
8807 static bfd_boolean
8808 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8809 {
8810   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8811   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8812   struct elf_final_link_info *flinfo = eoinfo->flinfo;
8813   bfd_boolean strip;
8814   Elf_Internal_Sym sym;
8815   asection *input_sec;
8816   const struct elf_backend_data *bed;
8817   long indx;
8818   int ret;
8819
8820   if (h->root.type == bfd_link_hash_warning)
8821     {
8822       h = (struct elf_link_hash_entry *) h->root.u.i.link;
8823       if (h->root.type == bfd_link_hash_new)
8824         return TRUE;
8825     }
8826
8827   /* Decide whether to output this symbol in this pass.  */
8828   if (eoinfo->localsyms)
8829     {
8830       if (!h->forced_local)
8831         return TRUE;
8832       if (eoinfo->second_pass
8833           && !((h->root.type == bfd_link_hash_defined
8834                 || h->root.type == bfd_link_hash_defweak)
8835                && h->root.u.def.section->output_section != NULL))
8836         return TRUE;
8837
8838       if (!eoinfo->file_sym_done
8839           && (eoinfo->second_pass ? eoinfo->flinfo->filesym_count == 1
8840                                   : eoinfo->flinfo->filesym_count > 1))
8841         {
8842           /* Output a FILE symbol so that following locals are not associated
8843              with the wrong input file.  */
8844           memset (&sym, 0, sizeof (sym));
8845           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
8846           sym.st_shndx = SHN_ABS;
8847           if (!elf_link_output_sym (eoinfo->flinfo, NULL, &sym,
8848                                     bfd_und_section_ptr, NULL))
8849             return FALSE;
8850
8851           eoinfo->file_sym_done = TRUE;
8852         }
8853     }
8854   else
8855     {
8856       if (h->forced_local)
8857         return TRUE;
8858     }
8859
8860   bed = get_elf_backend_data (flinfo->output_bfd);
8861
8862   if (h->root.type == bfd_link_hash_undefined)
8863     {
8864       /* If we have an undefined symbol reference here then it must have
8865          come from a shared library that is being linked in.  (Undefined
8866          references in regular files have already been handled unless
8867          they are in unreferenced sections which are removed by garbage
8868          collection).  */
8869       bfd_boolean ignore_undef = FALSE;
8870
8871       /* Some symbols may be special in that the fact that they're
8872          undefined can be safely ignored - let backend determine that.  */
8873       if (bed->elf_backend_ignore_undef_symbol)
8874         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
8875
8876       /* If we are reporting errors for this situation then do so now.  */
8877       if (!ignore_undef
8878           && h->ref_dynamic
8879           && (!h->ref_regular || flinfo->info->gc_sections)
8880           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
8881           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
8882         {
8883           if (!(flinfo->info->callbacks->undefined_symbol
8884                 (flinfo->info, h->root.root.string,
8885                  h->ref_regular ? NULL : h->root.u.undef.abfd,
8886                  NULL, 0,
8887                  (flinfo->info->unresolved_syms_in_shared_libs
8888                   == RM_GENERATE_ERROR))))
8889             {
8890               bfd_set_error (bfd_error_bad_value);
8891               eoinfo->failed = TRUE;
8892               return FALSE;
8893             }
8894         }
8895     }
8896
8897   /* We should also warn if a forced local symbol is referenced from
8898      shared libraries.  */
8899   if (!flinfo->info->relocatable
8900       && flinfo->info->executable
8901       && h->forced_local
8902       && h->ref_dynamic
8903       && h->def_regular
8904       && !h->dynamic_def
8905       && h->ref_dynamic_nonweak
8906       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
8907     {
8908       bfd *def_bfd;
8909       const char *msg;
8910       struct elf_link_hash_entry *hi = h;
8911
8912       /* Check indirect symbol.  */
8913       while (hi->root.type == bfd_link_hash_indirect)
8914         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
8915
8916       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
8917         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
8918       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
8919         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
8920       else
8921         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
8922       def_bfd = flinfo->output_bfd;
8923       if (hi->root.u.def.section != bfd_abs_section_ptr)
8924         def_bfd = hi->root.u.def.section->owner;
8925       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
8926                              h->root.root.string);
8927       bfd_set_error (bfd_error_bad_value);
8928       eoinfo->failed = TRUE;
8929       return FALSE;
8930     }
8931
8932   /* We don't want to output symbols that have never been mentioned by
8933      a regular file, or that we have been told to strip.  However, if
8934      h->indx is set to -2, the symbol is used by a reloc and we must
8935      output it.  */
8936   if (h->indx == -2)
8937     strip = FALSE;
8938   else if ((h->def_dynamic
8939             || h->ref_dynamic
8940             || h->root.type == bfd_link_hash_new)
8941            && !h->def_regular
8942            && !h->ref_regular)
8943     strip = TRUE;
8944   else if (flinfo->info->strip == strip_all)
8945     strip = TRUE;
8946   else if (flinfo->info->strip == strip_some
8947            && bfd_hash_lookup (flinfo->info->keep_hash,
8948                                h->root.root.string, FALSE, FALSE) == NULL)
8949     strip = TRUE;
8950   else if ((h->root.type == bfd_link_hash_defined
8951             || h->root.type == bfd_link_hash_defweak)
8952            && ((flinfo->info->strip_discarded
8953                 && discarded_section (h->root.u.def.section))
8954                || (h->root.u.def.section->owner != NULL
8955                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
8956     strip = TRUE;
8957   else if ((h->root.type == bfd_link_hash_undefined
8958             || h->root.type == bfd_link_hash_undefweak)
8959            && h->root.u.undef.abfd != NULL
8960            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
8961     strip = TRUE;
8962   else
8963     strip = FALSE;
8964
8965   /* If we're stripping it, and it's not a dynamic symbol, there's
8966      nothing else to do unless it is a forced local symbol or a
8967      STT_GNU_IFUNC symbol.  */
8968   if (strip
8969       && h->dynindx == -1
8970       && h->type != STT_GNU_IFUNC
8971       && !h->forced_local)
8972     return TRUE;
8973
8974   sym.st_value = 0;
8975   sym.st_size = h->size;
8976   sym.st_other = h->other;
8977   if (h->forced_local)
8978     {
8979       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
8980       /* Turn off visibility on local symbol.  */
8981       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
8982     }
8983   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
8984   else if (h->unique_global && h->def_regular)
8985     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
8986   else if (h->root.type == bfd_link_hash_undefweak
8987            || h->root.type == bfd_link_hash_defweak)
8988     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
8989   else
8990     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
8991   sym.st_target_internal = h->target_internal;
8992
8993   switch (h->root.type)
8994     {
8995     default:
8996     case bfd_link_hash_new:
8997     case bfd_link_hash_warning:
8998       abort ();
8999       return FALSE;
9000
9001     case bfd_link_hash_undefined:
9002     case bfd_link_hash_undefweak:
9003       input_sec = bfd_und_section_ptr;
9004       sym.st_shndx = SHN_UNDEF;
9005       break;
9006
9007     case bfd_link_hash_defined:
9008     case bfd_link_hash_defweak:
9009       {
9010         input_sec = h->root.u.def.section;
9011         if (input_sec->output_section != NULL)
9012           {
9013             if (eoinfo->localsyms && flinfo->filesym_count == 1)
9014               {
9015                 bfd_boolean second_pass_sym
9016                   = (input_sec->owner == flinfo->output_bfd
9017                      || input_sec->owner == NULL
9018                      || (input_sec->flags & SEC_LINKER_CREATED) != 0
9019                      || (input_sec->owner->flags & BFD_LINKER_CREATED) != 0);
9020
9021                 eoinfo->need_second_pass |= second_pass_sym;
9022                 if (eoinfo->second_pass != second_pass_sym)
9023                   return TRUE;
9024               }
9025
9026             sym.st_shndx =
9027               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9028                                                  input_sec->output_section);
9029             if (sym.st_shndx == SHN_BAD)
9030               {
9031                 (*_bfd_error_handler)
9032                   (_("%B: could not find output section %A for input section %A"),
9033                    flinfo->output_bfd, input_sec->output_section, input_sec);
9034                 bfd_set_error (bfd_error_nonrepresentable_section);
9035                 eoinfo->failed = TRUE;
9036                 return FALSE;
9037               }
9038
9039             /* ELF symbols in relocatable files are section relative,
9040                but in nonrelocatable files they are virtual
9041                addresses.  */
9042             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9043             if (!flinfo->info->relocatable)
9044               {
9045                 sym.st_value += input_sec->output_section->vma;
9046                 if (h->type == STT_TLS)
9047                   {
9048                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9049                     if (tls_sec != NULL)
9050                       sym.st_value -= tls_sec->vma;
9051                     else
9052                       {
9053                         /* The TLS section may have been garbage collected.  */
9054                         BFD_ASSERT (flinfo->info->gc_sections
9055                                     && !input_sec->gc_mark);
9056                       }
9057                   }
9058               }
9059           }
9060         else
9061           {
9062             BFD_ASSERT (input_sec->owner == NULL
9063                         || (input_sec->owner->flags & DYNAMIC) != 0);
9064             sym.st_shndx = SHN_UNDEF;
9065             input_sec = bfd_und_section_ptr;
9066           }
9067       }
9068       break;
9069
9070     case bfd_link_hash_common:
9071       input_sec = h->root.u.c.p->section;
9072       sym.st_shndx = bed->common_section_index (input_sec);
9073       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9074       break;
9075
9076     case bfd_link_hash_indirect:
9077       /* These symbols are created by symbol versioning.  They point
9078          to the decorated version of the name.  For example, if the
9079          symbol foo@@GNU_1.2 is the default, which should be used when
9080          foo is used with no version, then we add an indirect symbol
9081          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9082          since the indirected symbol is already in the hash table.  */
9083       return TRUE;
9084     }
9085
9086   /* Give the processor backend a chance to tweak the symbol value,
9087      and also to finish up anything that needs to be done for this
9088      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9089      forced local syms when non-shared is due to a historical quirk.
9090      STT_GNU_IFUNC symbol must go through PLT.  */
9091   if ((h->type == STT_GNU_IFUNC
9092        && h->def_regular
9093        && !flinfo->info->relocatable)
9094       || ((h->dynindx != -1
9095            || h->forced_local)
9096           && ((flinfo->info->shared
9097                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9098                    || h->root.type != bfd_link_hash_undefweak))
9099               || !h->forced_local)
9100           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9101     {
9102       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9103              (flinfo->output_bfd, flinfo->info, h, &sym)))
9104         {
9105           eoinfo->failed = TRUE;
9106           return FALSE;
9107         }
9108     }
9109
9110   /* If we are marking the symbol as undefined, and there are no
9111      non-weak references to this symbol from a regular object, then
9112      mark the symbol as weak undefined; if there are non-weak
9113      references, mark the symbol as strong.  We can't do this earlier,
9114      because it might not be marked as undefined until the
9115      finish_dynamic_symbol routine gets through with it.  */
9116   if (sym.st_shndx == SHN_UNDEF
9117       && h->ref_regular
9118       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9119           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9120     {
9121       int bindtype;
9122       unsigned int type = ELF_ST_TYPE (sym.st_info);
9123
9124       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9125       if (type == STT_GNU_IFUNC)
9126         type = STT_FUNC;
9127
9128       if (h->ref_regular_nonweak)
9129         bindtype = STB_GLOBAL;
9130       else
9131         bindtype = STB_WEAK;
9132       sym.st_info = ELF_ST_INFO (bindtype, type);
9133     }
9134
9135   /* If this is a symbol defined in a dynamic library, don't use the
9136      symbol size from the dynamic library.  Relinking an executable
9137      against a new library may introduce gratuitous changes in the
9138      executable's symbols if we keep the size.  */
9139   if (sym.st_shndx == SHN_UNDEF
9140       && !h->def_regular
9141       && h->def_dynamic)
9142     sym.st_size = 0;
9143
9144   /* If a non-weak symbol with non-default visibility is not defined
9145      locally, it is a fatal error.  */
9146   if (!flinfo->info->relocatable
9147       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9148       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9149       && h->root.type == bfd_link_hash_undefined
9150       && !h->def_regular)
9151     {
9152       const char *msg;
9153
9154       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9155         msg = _("%B: protected symbol `%s' isn't defined");
9156       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9157         msg = _("%B: internal symbol `%s' isn't defined");
9158       else
9159         msg = _("%B: hidden symbol `%s' isn't defined");
9160       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9161       bfd_set_error (bfd_error_bad_value);
9162       eoinfo->failed = TRUE;
9163       return FALSE;
9164     }
9165
9166   /* If this symbol should be put in the .dynsym section, then put it
9167      there now.  We already know the symbol index.  We also fill in
9168      the entry in the .hash section.  */
9169   if (flinfo->dynsym_sec != NULL
9170       && h->dynindx != -1
9171       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9172     {
9173       bfd_byte *esym;
9174
9175       /* Since there is no version information in the dynamic string,
9176          if there is no version info in symbol version section, we will
9177          have a run-time problem.  */
9178       if (h->verinfo.verdef == NULL)
9179         {
9180           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9181
9182           if (p && p [1] != '\0')
9183             {
9184               (*_bfd_error_handler)
9185                 (_("%B: No symbol version section for versioned symbol `%s'"),
9186                  flinfo->output_bfd, h->root.root.string);
9187               eoinfo->failed = TRUE;
9188               return FALSE;
9189             }
9190         }
9191
9192       sym.st_name = h->dynstr_index;
9193       esym = flinfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
9194       if (!check_dynsym (flinfo->output_bfd, &sym))
9195         {
9196           eoinfo->failed = TRUE;
9197           return FALSE;
9198         }
9199       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9200
9201       if (flinfo->hash_sec != NULL)
9202         {
9203           size_t hash_entry_size;
9204           bfd_byte *bucketpos;
9205           bfd_vma chain;
9206           size_t bucketcount;
9207           size_t bucket;
9208
9209           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9210           bucket = h->u.elf_hash_value % bucketcount;
9211
9212           hash_entry_size
9213             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9214           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9215                        + (bucket + 2) * hash_entry_size);
9216           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9217           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9218                    bucketpos);
9219           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9220                    ((bfd_byte *) flinfo->hash_sec->contents
9221                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9222         }
9223
9224       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9225         {
9226           Elf_Internal_Versym iversym;
9227           Elf_External_Versym *eversym;
9228
9229           if (!h->def_regular)
9230             {
9231               if (h->verinfo.verdef == NULL
9232                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9233                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9234                 iversym.vs_vers = 0;
9235               else
9236                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9237             }
9238           else
9239             {
9240               if (h->verinfo.vertree == NULL)
9241                 iversym.vs_vers = 1;
9242               else
9243                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9244               if (flinfo->info->create_default_symver)
9245                 iversym.vs_vers++;
9246             }
9247
9248           if (h->hidden)
9249             iversym.vs_vers |= VERSYM_HIDDEN;
9250
9251           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9252           eversym += h->dynindx;
9253           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9254         }
9255     }
9256
9257   /* If we're stripping it, then it was just a dynamic symbol, and
9258      there's nothing else to do.  */
9259   if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
9260     return TRUE;
9261
9262   indx = bfd_get_symcount (flinfo->output_bfd);
9263   ret = elf_link_output_sym (flinfo, h->root.root.string, &sym, input_sec, h);
9264   if (ret == 0)
9265     {
9266       eoinfo->failed = TRUE;
9267       return FALSE;
9268     }
9269   else if (ret == 1)
9270     h->indx = indx;
9271   else if (h->indx == -2)
9272     abort();
9273
9274   return TRUE;
9275 }
9276
9277 /* Return TRUE if special handling is done for relocs in SEC against
9278    symbols defined in discarded sections.  */
9279
9280 static bfd_boolean
9281 elf_section_ignore_discarded_relocs (asection *sec)
9282 {
9283   const struct elf_backend_data *bed;
9284
9285   switch (sec->sec_info_type)
9286     {
9287     case SEC_INFO_TYPE_STABS:
9288     case SEC_INFO_TYPE_EH_FRAME:
9289       return TRUE;
9290     default:
9291       break;
9292     }
9293
9294   bed = get_elf_backend_data (sec->owner);
9295   if (bed->elf_backend_ignore_discarded_relocs != NULL
9296       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9297     return TRUE;
9298
9299   return FALSE;
9300 }
9301
9302 /* Return a mask saying how ld should treat relocations in SEC against
9303    symbols defined in discarded sections.  If this function returns
9304    COMPLAIN set, ld will issue a warning message.  If this function
9305    returns PRETEND set, and the discarded section was link-once and the
9306    same size as the kept link-once section, ld will pretend that the
9307    symbol was actually defined in the kept section.  Otherwise ld will
9308    zero the reloc (at least that is the intent, but some cooperation by
9309    the target dependent code is needed, particularly for REL targets).  */
9310
9311 unsigned int
9312 _bfd_elf_default_action_discarded (asection *sec)
9313 {
9314   if (sec->flags & SEC_DEBUGGING)
9315     return PRETEND;
9316
9317   if (strcmp (".eh_frame", sec->name) == 0)
9318     return 0;
9319
9320   if (strcmp (".gcc_except_table", sec->name) == 0)
9321     return 0;
9322
9323   return COMPLAIN | PRETEND;
9324 }
9325
9326 /* Find a match between a section and a member of a section group.  */
9327
9328 static asection *
9329 match_group_member (asection *sec, asection *group,
9330                     struct bfd_link_info *info)
9331 {
9332   asection *first = elf_next_in_group (group);
9333   asection *s = first;
9334
9335   while (s != NULL)
9336     {
9337       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9338         return s;
9339
9340       s = elf_next_in_group (s);
9341       if (s == first)
9342         break;
9343     }
9344
9345   return NULL;
9346 }
9347
9348 /* Check if the kept section of a discarded section SEC can be used
9349    to replace it.  Return the replacement if it is OK.  Otherwise return
9350    NULL.  */
9351
9352 asection *
9353 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9354 {
9355   asection *kept;
9356
9357   kept = sec->kept_section;
9358   if (kept != NULL)
9359     {
9360       if ((kept->flags & SEC_GROUP) != 0)
9361         kept = match_group_member (sec, kept, info);
9362       if (kept != NULL
9363           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9364               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9365         kept = NULL;
9366       sec->kept_section = kept;
9367     }
9368   return kept;
9369 }
9370
9371 /* Link an input file into the linker output file.  This function
9372    handles all the sections and relocations of the input file at once.
9373    This is so that we only have to read the local symbols once, and
9374    don't have to keep them in memory.  */
9375
9376 static bfd_boolean
9377 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9378 {
9379   int (*relocate_section)
9380     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9381      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9382   bfd *output_bfd;
9383   Elf_Internal_Shdr *symtab_hdr;
9384   size_t locsymcount;
9385   size_t extsymoff;
9386   Elf_Internal_Sym *isymbuf;
9387   Elf_Internal_Sym *isym;
9388   Elf_Internal_Sym *isymend;
9389   long *pindex;
9390   asection **ppsection;
9391   asection *o;
9392   const struct elf_backend_data *bed;
9393   struct elf_link_hash_entry **sym_hashes;
9394   bfd_size_type address_size;
9395   bfd_vma r_type_mask;
9396   int r_sym_shift;
9397   bfd_boolean have_file_sym = FALSE;
9398
9399   output_bfd = flinfo->output_bfd;
9400   bed = get_elf_backend_data (output_bfd);
9401   relocate_section = bed->elf_backend_relocate_section;
9402
9403   /* If this is a dynamic object, we don't want to do anything here:
9404      we don't want the local symbols, and we don't want the section
9405      contents.  */
9406   if ((input_bfd->flags & DYNAMIC) != 0)
9407     return TRUE;
9408
9409   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9410   if (elf_bad_symtab (input_bfd))
9411     {
9412       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9413       extsymoff = 0;
9414     }
9415   else
9416     {
9417       locsymcount = symtab_hdr->sh_info;
9418       extsymoff = symtab_hdr->sh_info;
9419     }
9420
9421   /* Read the local symbols.  */
9422   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9423   if (isymbuf == NULL && locsymcount != 0)
9424     {
9425       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9426                                       flinfo->internal_syms,
9427                                       flinfo->external_syms,
9428                                       flinfo->locsym_shndx);
9429       if (isymbuf == NULL)
9430         return FALSE;
9431     }
9432
9433   /* Find local symbol sections and adjust values of symbols in
9434      SEC_MERGE sections.  Write out those local symbols we know are
9435      going into the output file.  */
9436   isymend = isymbuf + locsymcount;
9437   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9438        isym < isymend;
9439        isym++, pindex++, ppsection++)
9440     {
9441       asection *isec;
9442       const char *name;
9443       Elf_Internal_Sym osym;
9444       long indx;
9445       int ret;
9446
9447       *pindex = -1;
9448
9449       if (elf_bad_symtab (input_bfd))
9450         {
9451           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9452             {
9453               *ppsection = NULL;
9454               continue;
9455             }
9456         }
9457
9458       if (isym->st_shndx == SHN_UNDEF)
9459         isec = bfd_und_section_ptr;
9460       else if (isym->st_shndx == SHN_ABS)
9461         isec = bfd_abs_section_ptr;
9462       else if (isym->st_shndx == SHN_COMMON)
9463         isec = bfd_com_section_ptr;
9464       else
9465         {
9466           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9467           if (isec == NULL)
9468             {
9469               /* Don't attempt to output symbols with st_shnx in the
9470                  reserved range other than SHN_ABS and SHN_COMMON.  */
9471               *ppsection = NULL;
9472               continue;
9473             }
9474           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9475                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9476             isym->st_value =
9477               _bfd_merged_section_offset (output_bfd, &isec,
9478                                           elf_section_data (isec)->sec_info,
9479                                           isym->st_value);
9480         }
9481
9482       *ppsection = isec;
9483
9484       /* Don't output the first, undefined, symbol.  */
9485       if (ppsection == flinfo->sections)
9486         continue;
9487
9488       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9489         {
9490           /* We never output section symbols.  Instead, we use the
9491              section symbol of the corresponding section in the output
9492              file.  */
9493           continue;
9494         }
9495
9496       /* If we are stripping all symbols, we don't want to output this
9497          one.  */
9498       if (flinfo->info->strip == strip_all)
9499         continue;
9500
9501       /* If we are discarding all local symbols, we don't want to
9502          output this one.  If we are generating a relocatable output
9503          file, then some of the local symbols may be required by
9504          relocs; we output them below as we discover that they are
9505          needed.  */
9506       if (flinfo->info->discard == discard_all)
9507         continue;
9508
9509       /* If this symbol is defined in a section which we are
9510          discarding, we don't need to keep it.  */
9511       if (isym->st_shndx != SHN_UNDEF
9512           && isym->st_shndx < SHN_LORESERVE
9513           && bfd_section_removed_from_list (output_bfd,
9514                                             isec->output_section))
9515         continue;
9516
9517       /* Get the name of the symbol.  */
9518       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9519                                               isym->st_name);
9520       if (name == NULL)
9521         return FALSE;
9522
9523       /* See if we are discarding symbols with this name.  */
9524       if ((flinfo->info->strip == strip_some
9525            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9526                == NULL))
9527           || (((flinfo->info->discard == discard_sec_merge
9528                 && (isec->flags & SEC_MERGE) && !flinfo->info->relocatable)
9529                || flinfo->info->discard == discard_l)
9530               && bfd_is_local_label_name (input_bfd, name)))
9531         continue;
9532
9533       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9534         {
9535           have_file_sym = TRUE;
9536           flinfo->filesym_count += 1;
9537         }
9538       if (!have_file_sym)
9539         {
9540           /* In the absence of debug info, bfd_find_nearest_line uses
9541              FILE symbols to determine the source file for local
9542              function symbols.  Provide a FILE symbol here if input
9543              files lack such, so that their symbols won't be
9544              associated with a previous input file.  It's not the
9545              source file, but the best we can do.  */
9546           have_file_sym = TRUE;
9547           flinfo->filesym_count += 1;
9548           memset (&osym, 0, sizeof (osym));
9549           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9550           osym.st_shndx = SHN_ABS;
9551           if (!elf_link_output_sym (flinfo, input_bfd->filename, &osym,
9552                                     bfd_abs_section_ptr, NULL))
9553             return FALSE;
9554         }
9555
9556       osym = *isym;
9557
9558       /* Adjust the section index for the output file.  */
9559       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9560                                                          isec->output_section);
9561       if (osym.st_shndx == SHN_BAD)
9562         return FALSE;
9563
9564       /* ELF symbols in relocatable files are section relative, but
9565          in executable files they are virtual addresses.  Note that
9566          this code assumes that all ELF sections have an associated
9567          BFD section with a reasonable value for output_offset; below
9568          we assume that they also have a reasonable value for
9569          output_section.  Any special sections must be set up to meet
9570          these requirements.  */
9571       osym.st_value += isec->output_offset;
9572       if (!flinfo->info->relocatable)
9573         {
9574           osym.st_value += isec->output_section->vma;
9575           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9576             {
9577               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9578               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9579               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9580             }
9581         }
9582
9583       indx = bfd_get_symcount (output_bfd);
9584       ret = elf_link_output_sym (flinfo, name, &osym, isec, NULL);
9585       if (ret == 0)
9586         return FALSE;
9587       else if (ret == 1)
9588         *pindex = indx;
9589     }
9590
9591   if (bed->s->arch_size == 32)
9592     {
9593       r_type_mask = 0xff;
9594       r_sym_shift = 8;
9595       address_size = 4;
9596     }
9597   else
9598     {
9599       r_type_mask = 0xffffffff;
9600       r_sym_shift = 32;
9601       address_size = 8;
9602     }
9603
9604   /* Relocate the contents of each section.  */
9605   sym_hashes = elf_sym_hashes (input_bfd);
9606   for (o = input_bfd->sections; o != NULL; o = o->next)
9607     {
9608       bfd_byte *contents;
9609
9610       if (! o->linker_mark)
9611         {
9612           /* This section was omitted from the link.  */
9613           continue;
9614         }
9615
9616       if (flinfo->info->relocatable
9617           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9618         {
9619           /* Deal with the group signature symbol.  */
9620           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9621           unsigned long symndx = sec_data->this_hdr.sh_info;
9622           asection *osec = o->output_section;
9623
9624           if (symndx >= locsymcount
9625               || (elf_bad_symtab (input_bfd)
9626                   && flinfo->sections[symndx] == NULL))
9627             {
9628               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9629               while (h->root.type == bfd_link_hash_indirect
9630                      || h->root.type == bfd_link_hash_warning)
9631                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9632               /* Arrange for symbol to be output.  */
9633               h->indx = -2;
9634               elf_section_data (osec)->this_hdr.sh_info = -2;
9635             }
9636           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9637             {
9638               /* We'll use the output section target_index.  */
9639               asection *sec = flinfo->sections[symndx]->output_section;
9640               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9641             }
9642           else
9643             {
9644               if (flinfo->indices[symndx] == -1)
9645                 {
9646                   /* Otherwise output the local symbol now.  */
9647                   Elf_Internal_Sym sym = isymbuf[symndx];
9648                   asection *sec = flinfo->sections[symndx]->output_section;
9649                   const char *name;
9650                   long indx;
9651                   int ret;
9652
9653                   name = bfd_elf_string_from_elf_section (input_bfd,
9654                                                           symtab_hdr->sh_link,
9655                                                           sym.st_name);
9656                   if (name == NULL)
9657                     return FALSE;
9658
9659                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9660                                                                     sec);
9661                   if (sym.st_shndx == SHN_BAD)
9662                     return FALSE;
9663
9664                   sym.st_value += o->output_offset;
9665
9666                   indx = bfd_get_symcount (output_bfd);
9667                   ret = elf_link_output_sym (flinfo, name, &sym, o, NULL);
9668                   if (ret == 0)
9669                     return FALSE;
9670                   else if (ret == 1)
9671                     flinfo->indices[symndx] = indx;
9672                   else
9673                     abort ();
9674                 }
9675               elf_section_data (osec)->this_hdr.sh_info
9676                 = flinfo->indices[symndx];
9677             }
9678         }
9679
9680       if ((o->flags & SEC_HAS_CONTENTS) == 0
9681           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9682         continue;
9683
9684       if ((o->flags & SEC_LINKER_CREATED) != 0)
9685         {
9686           /* Section was created by _bfd_elf_link_create_dynamic_sections
9687              or somesuch.  */
9688           continue;
9689         }
9690
9691       /* Get the contents of the section.  They have been cached by a
9692          relaxation routine.  Note that o is a section in an input
9693          file, so the contents field will not have been set by any of
9694          the routines which work on output files.  */
9695       if (elf_section_data (o)->this_hdr.contents != NULL)
9696         {
9697           contents = elf_section_data (o)->this_hdr.contents;
9698           if (bed->caches_rawsize
9699               && o->rawsize != 0
9700               && o->rawsize < o->size)
9701             {
9702               memcpy (flinfo->contents, contents, o->rawsize);
9703               contents = flinfo->contents;
9704             }
9705         }
9706       else
9707         {
9708           contents = flinfo->contents;
9709           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9710             return FALSE;
9711         }
9712
9713       if ((o->flags & SEC_RELOC) != 0)
9714         {
9715           Elf_Internal_Rela *internal_relocs;
9716           Elf_Internal_Rela *rel, *relend;
9717           int action_discarded;
9718           int ret;
9719
9720           /* Get the swapped relocs.  */
9721           internal_relocs
9722             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
9723                                          flinfo->internal_relocs, FALSE);
9724           if (internal_relocs == NULL
9725               && o->reloc_count > 0)
9726             return FALSE;
9727
9728           /* We need to reverse-copy input .ctors/.dtors sections if
9729              they are placed in .init_array/.finit_array for output.  */
9730           if (o->size > address_size
9731               && ((strncmp (o->name, ".ctors", 6) == 0
9732                    && strcmp (o->output_section->name,
9733                               ".init_array") == 0)
9734                   || (strncmp (o->name, ".dtors", 6) == 0
9735                       && strcmp (o->output_section->name,
9736                                  ".fini_array") == 0))
9737               && (o->name[6] == 0 || o->name[6] == '.'))
9738             {
9739               if (o->size != o->reloc_count * address_size)
9740                 {
9741                   (*_bfd_error_handler)
9742                     (_("error: %B: size of section %A is not "
9743                        "multiple of address size"),
9744                      input_bfd, o);
9745                   bfd_set_error (bfd_error_on_input);
9746                   return FALSE;
9747                 }
9748               o->flags |= SEC_ELF_REVERSE_COPY;
9749             }
9750
9751           action_discarded = -1;
9752           if (!elf_section_ignore_discarded_relocs (o))
9753             action_discarded = (*bed->action_discarded) (o);
9754
9755           /* Run through the relocs evaluating complex reloc symbols and
9756              looking for relocs against symbols from discarded sections
9757              or section symbols from removed link-once sections.
9758              Complain about relocs against discarded sections.  Zero
9759              relocs against removed link-once sections.  */
9760
9761           rel = internal_relocs;
9762           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9763           for ( ; rel < relend; rel++)
9764             {
9765               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9766               unsigned int s_type;
9767               asection **ps, *sec;
9768               struct elf_link_hash_entry *h = NULL;
9769               const char *sym_name;
9770
9771               if (r_symndx == STN_UNDEF)
9772                 continue;
9773
9774               if (r_symndx >= locsymcount
9775                   || (elf_bad_symtab (input_bfd)
9776                       && flinfo->sections[r_symndx] == NULL))
9777                 {
9778                   h = sym_hashes[r_symndx - extsymoff];
9779
9780                   /* Badly formatted input files can contain relocs that
9781                      reference non-existant symbols.  Check here so that
9782                      we do not seg fault.  */
9783                   if (h == NULL)
9784                     {
9785                       char buffer [32];
9786
9787                       sprintf_vma (buffer, rel->r_info);
9788                       (*_bfd_error_handler)
9789                         (_("error: %B contains a reloc (0x%s) for section %A "
9790                            "that references a non-existent global symbol"),
9791                          input_bfd, o, buffer);
9792                       bfd_set_error (bfd_error_bad_value);
9793                       return FALSE;
9794                     }
9795
9796                   while (h->root.type == bfd_link_hash_indirect
9797                          || h->root.type == bfd_link_hash_warning)
9798                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9799
9800                   s_type = h->type;
9801
9802                   ps = NULL;
9803                   if (h->root.type == bfd_link_hash_defined
9804                       || h->root.type == bfd_link_hash_defweak)
9805                     ps = &h->root.u.def.section;
9806
9807                   sym_name = h->root.root.string;
9808                 }
9809               else
9810                 {
9811                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
9812
9813                   s_type = ELF_ST_TYPE (sym->st_info);
9814                   ps = &flinfo->sections[r_symndx];
9815                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9816                                                sym, *ps);
9817                 }
9818
9819               if ((s_type == STT_RELC || s_type == STT_SRELC)
9820                   && !flinfo->info->relocatable)
9821                 {
9822                   bfd_vma val;
9823                   bfd_vma dot = (rel->r_offset
9824                                  + o->output_offset + o->output_section->vma);
9825 #ifdef DEBUG
9826                   printf ("Encountered a complex symbol!");
9827                   printf (" (input_bfd %s, section %s, reloc %ld\n",
9828                           input_bfd->filename, o->name,
9829                           (long) (rel - internal_relocs));
9830                   printf (" symbol: idx  %8.8lx, name %s\n",
9831                           r_symndx, sym_name);
9832                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
9833                           (unsigned long) rel->r_info,
9834                           (unsigned long) rel->r_offset);
9835 #endif
9836                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
9837                                     isymbuf, locsymcount, s_type == STT_SRELC))
9838                     return FALSE;
9839
9840                   /* Symbol evaluated OK.  Update to absolute value.  */
9841                   set_symbol_value (input_bfd, isymbuf, locsymcount,
9842                                     r_symndx, val);
9843                   continue;
9844                 }
9845
9846               if (action_discarded != -1 && ps != NULL)
9847                 {
9848                   /* Complain if the definition comes from a
9849                      discarded section.  */
9850                   if ((sec = *ps) != NULL && discarded_section (sec))
9851                     {
9852                       BFD_ASSERT (r_symndx != STN_UNDEF);
9853                       if (action_discarded & COMPLAIN)
9854                         (*flinfo->info->callbacks->einfo)
9855                           (_("%X`%s' referenced in section `%A' of %B: "
9856                              "defined in discarded section `%A' of %B\n"),
9857                            sym_name, o, input_bfd, sec, sec->owner);
9858
9859                       /* Try to do the best we can to support buggy old
9860                          versions of gcc.  Pretend that the symbol is
9861                          really defined in the kept linkonce section.
9862                          FIXME: This is quite broken.  Modifying the
9863                          symbol here means we will be changing all later
9864                          uses of the symbol, not just in this section.  */
9865                       if (action_discarded & PRETEND)
9866                         {
9867                           asection *kept;
9868
9869                           kept = _bfd_elf_check_kept_section (sec,
9870                                                               flinfo->info);
9871                           if (kept != NULL)
9872                             {
9873                               *ps = kept;
9874                               continue;
9875                             }
9876                         }
9877                     }
9878                 }
9879             }
9880
9881           /* Relocate the section by invoking a back end routine.
9882
9883              The back end routine is responsible for adjusting the
9884              section contents as necessary, and (if using Rela relocs
9885              and generating a relocatable output file) adjusting the
9886              reloc addend as necessary.
9887
9888              The back end routine does not have to worry about setting
9889              the reloc address or the reloc symbol index.
9890
9891              The back end routine is given a pointer to the swapped in
9892              internal symbols, and can access the hash table entries
9893              for the external symbols via elf_sym_hashes (input_bfd).
9894
9895              When generating relocatable output, the back end routine
9896              must handle STB_LOCAL/STT_SECTION symbols specially.  The
9897              output symbol is going to be a section symbol
9898              corresponding to the output section, which will require
9899              the addend to be adjusted.  */
9900
9901           ret = (*relocate_section) (output_bfd, flinfo->info,
9902                                      input_bfd, o, contents,
9903                                      internal_relocs,
9904                                      isymbuf,
9905                                      flinfo->sections);
9906           if (!ret)
9907             return FALSE;
9908
9909           if (ret == 2
9910               || flinfo->info->relocatable
9911               || flinfo->info->emitrelocations)
9912             {
9913               Elf_Internal_Rela *irela;
9914               Elf_Internal_Rela *irelaend, *irelamid;
9915               bfd_vma last_offset;
9916               struct elf_link_hash_entry **rel_hash;
9917               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
9918               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
9919               unsigned int next_erel;
9920               bfd_boolean rela_normal;
9921               struct bfd_elf_section_data *esdi, *esdo;
9922
9923               esdi = elf_section_data (o);
9924               esdo = elf_section_data (o->output_section);
9925               rela_normal = FALSE;
9926
9927               /* Adjust the reloc addresses and symbol indices.  */
9928
9929               irela = internal_relocs;
9930               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
9931               rel_hash = esdo->rel.hashes + esdo->rel.count;
9932               /* We start processing the REL relocs, if any.  When we reach
9933                  IRELAMID in the loop, we switch to the RELA relocs.  */
9934               irelamid = irela;
9935               if (esdi->rel.hdr != NULL)
9936                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
9937                              * bed->s->int_rels_per_ext_rel);
9938               rel_hash_list = rel_hash;
9939               rela_hash_list = NULL;
9940               last_offset = o->output_offset;
9941               if (!flinfo->info->relocatable)
9942                 last_offset += o->output_section->vma;
9943               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
9944                 {
9945                   unsigned long r_symndx;
9946                   asection *sec;
9947                   Elf_Internal_Sym sym;
9948
9949                   if (next_erel == bed->s->int_rels_per_ext_rel)
9950                     {
9951                       rel_hash++;
9952                       next_erel = 0;
9953                     }
9954
9955                   if (irela == irelamid)
9956                     {
9957                       rel_hash = esdo->rela.hashes + esdo->rela.count;
9958                       rela_hash_list = rel_hash;
9959                       rela_normal = bed->rela_normal;
9960                     }
9961
9962                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
9963                                                              flinfo->info, o,
9964                                                              irela->r_offset);
9965                   if (irela->r_offset >= (bfd_vma) -2)
9966                     {
9967                       /* This is a reloc for a deleted entry or somesuch.
9968                          Turn it into an R_*_NONE reloc, at the same
9969                          offset as the last reloc.  elf_eh_frame.c and
9970                          bfd_elf_discard_info rely on reloc offsets
9971                          being ordered.  */
9972                       irela->r_offset = last_offset;
9973                       irela->r_info = 0;
9974                       irela->r_addend = 0;
9975                       continue;
9976                     }
9977
9978                   irela->r_offset += o->output_offset;
9979
9980                   /* Relocs in an executable have to be virtual addresses.  */
9981                   if (!flinfo->info->relocatable)
9982                     irela->r_offset += o->output_section->vma;
9983
9984                   last_offset = irela->r_offset;
9985
9986                   r_symndx = irela->r_info >> r_sym_shift;
9987                   if (r_symndx == STN_UNDEF)
9988                     continue;
9989
9990                   if (r_symndx >= locsymcount
9991                       || (elf_bad_symtab (input_bfd)
9992                           && flinfo->sections[r_symndx] == NULL))
9993                     {
9994                       struct elf_link_hash_entry *rh;
9995                       unsigned long indx;
9996
9997                       /* This is a reloc against a global symbol.  We
9998                          have not yet output all the local symbols, so
9999                          we do not know the symbol index of any global
10000                          symbol.  We set the rel_hash entry for this
10001                          reloc to point to the global hash table entry
10002                          for this symbol.  The symbol index is then
10003                          set at the end of bfd_elf_final_link.  */
10004                       indx = r_symndx - extsymoff;
10005                       rh = elf_sym_hashes (input_bfd)[indx];
10006                       while (rh->root.type == bfd_link_hash_indirect
10007                              || rh->root.type == bfd_link_hash_warning)
10008                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10009
10010                       /* Setting the index to -2 tells
10011                          elf_link_output_extsym that this symbol is
10012                          used by a reloc.  */
10013                       BFD_ASSERT (rh->indx < 0);
10014                       rh->indx = -2;
10015
10016                       *rel_hash = rh;
10017
10018                       continue;
10019                     }
10020
10021                   /* This is a reloc against a local symbol.  */
10022
10023                   *rel_hash = NULL;
10024                   sym = isymbuf[r_symndx];
10025                   sec = flinfo->sections[r_symndx];
10026                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10027                     {
10028                       /* I suppose the backend ought to fill in the
10029                          section of any STT_SECTION symbol against a
10030                          processor specific section.  */
10031                       r_symndx = STN_UNDEF;
10032                       if (bfd_is_abs_section (sec))
10033                         ;
10034                       else if (sec == NULL || sec->owner == NULL)
10035                         {
10036                           bfd_set_error (bfd_error_bad_value);
10037                           return FALSE;
10038                         }
10039                       else
10040                         {
10041                           asection *osec = sec->output_section;
10042
10043                           /* If we have discarded a section, the output
10044                              section will be the absolute section.  In
10045                              case of discarded SEC_MERGE sections, use
10046                              the kept section.  relocate_section should
10047                              have already handled discarded linkonce
10048                              sections.  */
10049                           if (bfd_is_abs_section (osec)
10050                               && sec->kept_section != NULL
10051                               && sec->kept_section->output_section != NULL)
10052                             {
10053                               osec = sec->kept_section->output_section;
10054                               irela->r_addend -= osec->vma;
10055                             }
10056
10057                           if (!bfd_is_abs_section (osec))
10058                             {
10059                               r_symndx = osec->target_index;
10060                               if (r_symndx == STN_UNDEF)
10061                                 {
10062                                   irela->r_addend += osec->vma;
10063                                   osec = _bfd_nearby_section (output_bfd, osec,
10064                                                               osec->vma);
10065                                   irela->r_addend -= osec->vma;
10066                                   r_symndx = osec->target_index;
10067                                 }
10068                             }
10069                         }
10070
10071                       /* Adjust the addend according to where the
10072                          section winds up in the output section.  */
10073                       if (rela_normal)
10074                         irela->r_addend += sec->output_offset;
10075                     }
10076                   else
10077                     {
10078                       if (flinfo->indices[r_symndx] == -1)
10079                         {
10080                           unsigned long shlink;
10081                           const char *name;
10082                           asection *osec;
10083                           long indx;
10084
10085                           if (flinfo->info->strip == strip_all)
10086                             {
10087                               /* You can't do ld -r -s.  */
10088                               bfd_set_error (bfd_error_invalid_operation);
10089                               return FALSE;
10090                             }
10091
10092                           /* This symbol was skipped earlier, but
10093                              since it is needed by a reloc, we
10094                              must output it now.  */
10095                           shlink = symtab_hdr->sh_link;
10096                           name = (bfd_elf_string_from_elf_section
10097                                   (input_bfd, shlink, sym.st_name));
10098                           if (name == NULL)
10099                             return FALSE;
10100
10101                           osec = sec->output_section;
10102                           sym.st_shndx =
10103                             _bfd_elf_section_from_bfd_section (output_bfd,
10104                                                                osec);
10105                           if (sym.st_shndx == SHN_BAD)
10106                             return FALSE;
10107
10108                           sym.st_value += sec->output_offset;
10109                           if (!flinfo->info->relocatable)
10110                             {
10111                               sym.st_value += osec->vma;
10112                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10113                                 {
10114                                   /* STT_TLS symbols are relative to PT_TLS
10115                                      segment base.  */
10116                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10117                                               ->tls_sec != NULL);
10118                                   sym.st_value -= (elf_hash_table (flinfo->info)
10119                                                    ->tls_sec->vma);
10120                                 }
10121                             }
10122
10123                           indx = bfd_get_symcount (output_bfd);
10124                           ret = elf_link_output_sym (flinfo, name, &sym, sec,
10125                                                      NULL);
10126                           if (ret == 0)
10127                             return FALSE;
10128                           else if (ret == 1)
10129                             flinfo->indices[r_symndx] = indx;
10130                           else
10131                             abort ();
10132                         }
10133
10134                       r_symndx = flinfo->indices[r_symndx];
10135                     }
10136
10137                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10138                                    | (irela->r_info & r_type_mask));
10139                 }
10140
10141               /* Swap out the relocs.  */
10142               input_rel_hdr = esdi->rel.hdr;
10143               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10144                 {
10145                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10146                                                      input_rel_hdr,
10147                                                      internal_relocs,
10148                                                      rel_hash_list))
10149                     return FALSE;
10150                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10151                                       * bed->s->int_rels_per_ext_rel);
10152                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10153                 }
10154
10155               input_rela_hdr = esdi->rela.hdr;
10156               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10157                 {
10158                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10159                                                      input_rela_hdr,
10160                                                      internal_relocs,
10161                                                      rela_hash_list))
10162                     return FALSE;
10163                 }
10164             }
10165         }
10166
10167       /* Write out the modified section contents.  */
10168       if (bed->elf_backend_write_section
10169           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10170                                                 contents))
10171         {
10172           /* Section written out.  */
10173         }
10174       else switch (o->sec_info_type)
10175         {
10176         case SEC_INFO_TYPE_STABS:
10177           if (! (_bfd_write_section_stabs
10178                  (output_bfd,
10179                   &elf_hash_table (flinfo->info)->stab_info,
10180                   o, &elf_section_data (o)->sec_info, contents)))
10181             return FALSE;
10182           break;
10183         case SEC_INFO_TYPE_MERGE:
10184           if (! _bfd_write_merged_section (output_bfd, o,
10185                                            elf_section_data (o)->sec_info))
10186             return FALSE;
10187           break;
10188         case SEC_INFO_TYPE_EH_FRAME:
10189           {
10190             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10191                                                    o, contents))
10192               return FALSE;
10193           }
10194           break;
10195         default:
10196           {
10197             /* FIXME: octets_per_byte.  */
10198             if (! (o->flags & SEC_EXCLUDE))
10199               {
10200                 file_ptr offset = (file_ptr) o->output_offset;
10201                 bfd_size_type todo = o->size;
10202                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10203                   {
10204                     /* Reverse-copy input section to output.  */
10205                     do
10206                       {
10207                         todo -= address_size;
10208                         if (! bfd_set_section_contents (output_bfd,
10209                                                         o->output_section,
10210                                                         contents + todo,
10211                                                         offset,
10212                                                         address_size))
10213                           return FALSE;
10214                         if (todo == 0)
10215                           break;
10216                         offset += address_size;
10217                       }
10218                     while (1);
10219                   }
10220                 else if (! bfd_set_section_contents (output_bfd,
10221                                                      o->output_section,
10222                                                      contents,
10223                                                      offset, todo))
10224                   return FALSE;
10225               }
10226           }
10227           break;
10228         }
10229     }
10230
10231   return TRUE;
10232 }
10233
10234 /* Generate a reloc when linking an ELF file.  This is a reloc
10235    requested by the linker, and does not come from any input file.  This
10236    is used to build constructor and destructor tables when linking
10237    with -Ur.  */
10238
10239 static bfd_boolean
10240 elf_reloc_link_order (bfd *output_bfd,
10241                       struct bfd_link_info *info,
10242                       asection *output_section,
10243                       struct bfd_link_order *link_order)
10244 {
10245   reloc_howto_type *howto;
10246   long indx;
10247   bfd_vma offset;
10248   bfd_vma addend;
10249   struct bfd_elf_section_reloc_data *reldata;
10250   struct elf_link_hash_entry **rel_hash_ptr;
10251   Elf_Internal_Shdr *rel_hdr;
10252   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10253   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10254   bfd_byte *erel;
10255   unsigned int i;
10256   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10257
10258   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10259   if (howto == NULL)
10260     {
10261       bfd_set_error (bfd_error_bad_value);
10262       return FALSE;
10263     }
10264
10265   addend = link_order->u.reloc.p->addend;
10266
10267   if (esdo->rel.hdr)
10268     reldata = &esdo->rel;
10269   else if (esdo->rela.hdr)
10270     reldata = &esdo->rela;
10271   else
10272     {
10273       reldata = NULL;
10274       BFD_ASSERT (0);
10275     }
10276
10277   /* Figure out the symbol index.  */
10278   rel_hash_ptr = reldata->hashes + reldata->count;
10279   if (link_order->type == bfd_section_reloc_link_order)
10280     {
10281       indx = link_order->u.reloc.p->u.section->target_index;
10282       BFD_ASSERT (indx != 0);
10283       *rel_hash_ptr = NULL;
10284     }
10285   else
10286     {
10287       struct elf_link_hash_entry *h;
10288
10289       /* Treat a reloc against a defined symbol as though it were
10290          actually against the section.  */
10291       h = ((struct elf_link_hash_entry *)
10292            bfd_wrapped_link_hash_lookup (output_bfd, info,
10293                                          link_order->u.reloc.p->u.name,
10294                                          FALSE, FALSE, TRUE));
10295       if (h != NULL
10296           && (h->root.type == bfd_link_hash_defined
10297               || h->root.type == bfd_link_hash_defweak))
10298         {
10299           asection *section;
10300
10301           section = h->root.u.def.section;
10302           indx = section->output_section->target_index;
10303           *rel_hash_ptr = NULL;
10304           /* It seems that we ought to add the symbol value to the
10305              addend here, but in practice it has already been added
10306              because it was passed to constructor_callback.  */
10307           addend += section->output_section->vma + section->output_offset;
10308         }
10309       else if (h != NULL)
10310         {
10311           /* Setting the index to -2 tells elf_link_output_extsym that
10312              this symbol is used by a reloc.  */
10313           h->indx = -2;
10314           *rel_hash_ptr = h;
10315           indx = 0;
10316         }
10317       else
10318         {
10319           if (! ((*info->callbacks->unattached_reloc)
10320                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10321             return FALSE;
10322           indx = 0;
10323         }
10324     }
10325
10326   /* If this is an inplace reloc, we must write the addend into the
10327      object file.  */
10328   if (howto->partial_inplace && addend != 0)
10329     {
10330       bfd_size_type size;
10331       bfd_reloc_status_type rstat;
10332       bfd_byte *buf;
10333       bfd_boolean ok;
10334       const char *sym_name;
10335
10336       size = (bfd_size_type) bfd_get_reloc_size (howto);
10337       buf = (bfd_byte *) bfd_zmalloc (size);
10338       if (buf == NULL)
10339         return FALSE;
10340       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10341       switch (rstat)
10342         {
10343         case bfd_reloc_ok:
10344           break;
10345
10346         default:
10347         case bfd_reloc_outofrange:
10348           abort ();
10349
10350         case bfd_reloc_overflow:
10351           if (link_order->type == bfd_section_reloc_link_order)
10352             sym_name = bfd_section_name (output_bfd,
10353                                          link_order->u.reloc.p->u.section);
10354           else
10355             sym_name = link_order->u.reloc.p->u.name;
10356           if (! ((*info->callbacks->reloc_overflow)
10357                  (info, NULL, sym_name, howto->name, addend, NULL,
10358                   NULL, (bfd_vma) 0)))
10359             {
10360               free (buf);
10361               return FALSE;
10362             }
10363           break;
10364         }
10365       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10366                                      link_order->offset, size);
10367       free (buf);
10368       if (! ok)
10369         return FALSE;
10370     }
10371
10372   /* The address of a reloc is relative to the section in a
10373      relocatable file, and is a virtual address in an executable
10374      file.  */
10375   offset = link_order->offset;
10376   if (! info->relocatable)
10377     offset += output_section->vma;
10378
10379   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10380     {
10381       irel[i].r_offset = offset;
10382       irel[i].r_info = 0;
10383       irel[i].r_addend = 0;
10384     }
10385   if (bed->s->arch_size == 32)
10386     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10387   else
10388     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10389
10390   rel_hdr = reldata->hdr;
10391   erel = rel_hdr->contents;
10392   if (rel_hdr->sh_type == SHT_REL)
10393     {
10394       erel += reldata->count * bed->s->sizeof_rel;
10395       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10396     }
10397   else
10398     {
10399       irel[0].r_addend = addend;
10400       erel += reldata->count * bed->s->sizeof_rela;
10401       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10402     }
10403
10404   ++reldata->count;
10405
10406   return TRUE;
10407 }
10408
10409
10410 /* Get the output vma of the section pointed to by the sh_link field.  */
10411
10412 static bfd_vma
10413 elf_get_linked_section_vma (struct bfd_link_order *p)
10414 {
10415   Elf_Internal_Shdr **elf_shdrp;
10416   asection *s;
10417   int elfsec;
10418
10419   s = p->u.indirect.section;
10420   elf_shdrp = elf_elfsections (s->owner);
10421   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10422   elfsec = elf_shdrp[elfsec]->sh_link;
10423   /* PR 290:
10424      The Intel C compiler generates SHT_IA_64_UNWIND with
10425      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10426      sh_info fields.  Hence we could get the situation
10427      where elfsec is 0.  */
10428   if (elfsec == 0)
10429     {
10430       const struct elf_backend_data *bed
10431         = get_elf_backend_data (s->owner);
10432       if (bed->link_order_error_handler)
10433         bed->link_order_error_handler
10434           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10435       return 0;
10436     }
10437   else
10438     {
10439       s = elf_shdrp[elfsec]->bfd_section;
10440       return s->output_section->vma + s->output_offset;
10441     }
10442 }
10443
10444
10445 /* Compare two sections based on the locations of the sections they are
10446    linked to.  Used by elf_fixup_link_order.  */
10447
10448 static int
10449 compare_link_order (const void * a, const void * b)
10450 {
10451   bfd_vma apos;
10452   bfd_vma bpos;
10453
10454   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10455   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10456   if (apos < bpos)
10457     return -1;
10458   return apos > bpos;
10459 }
10460
10461
10462 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10463    order as their linked sections.  Returns false if this could not be done
10464    because an output section includes both ordered and unordered
10465    sections.  Ideally we'd do this in the linker proper.  */
10466
10467 static bfd_boolean
10468 elf_fixup_link_order (bfd *abfd, asection *o)
10469 {
10470   int seen_linkorder;
10471   int seen_other;
10472   int n;
10473   struct bfd_link_order *p;
10474   bfd *sub;
10475   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10476   unsigned elfsec;
10477   struct bfd_link_order **sections;
10478   asection *s, *other_sec, *linkorder_sec;
10479   bfd_vma offset;
10480
10481   other_sec = NULL;
10482   linkorder_sec = NULL;
10483   seen_other = 0;
10484   seen_linkorder = 0;
10485   for (p = o->map_head.link_order; p != NULL; p = p->next)
10486     {
10487       if (p->type == bfd_indirect_link_order)
10488         {
10489           s = p->u.indirect.section;
10490           sub = s->owner;
10491           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10492               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10493               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10494               && elfsec < elf_numsections (sub)
10495               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10496               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10497             {
10498               seen_linkorder++;
10499               linkorder_sec = s;
10500             }
10501           else
10502             {
10503               seen_other++;
10504               other_sec = s;
10505             }
10506         }
10507       else
10508         seen_other++;
10509
10510       if (seen_other && seen_linkorder)
10511         {
10512           if (other_sec && linkorder_sec)
10513             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10514                                    o, linkorder_sec,
10515                                    linkorder_sec->owner, other_sec,
10516                                    other_sec->owner);
10517           else
10518             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10519                                    o);
10520           bfd_set_error (bfd_error_bad_value);
10521           return FALSE;
10522         }
10523     }
10524
10525   if (!seen_linkorder)
10526     return TRUE;
10527
10528   sections = (struct bfd_link_order **)
10529     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10530   if (sections == NULL)
10531     return FALSE;
10532   seen_linkorder = 0;
10533
10534   for (p = o->map_head.link_order; p != NULL; p = p->next)
10535     {
10536       sections[seen_linkorder++] = p;
10537     }
10538   /* Sort the input sections in the order of their linked section.  */
10539   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10540          compare_link_order);
10541
10542   /* Change the offsets of the sections.  */
10543   offset = 0;
10544   for (n = 0; n < seen_linkorder; n++)
10545     {
10546       s = sections[n]->u.indirect.section;
10547       offset &= ~(bfd_vma) 0 << s->alignment_power;
10548       s->output_offset = offset;
10549       sections[n]->offset = offset;
10550       /* FIXME: octets_per_byte.  */
10551       offset += sections[n]->size;
10552     }
10553
10554   free (sections);
10555   return TRUE;
10556 }
10557
10558 static void
10559 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10560 {
10561   asection *o;
10562
10563   if (flinfo->symstrtab != NULL)
10564     _bfd_stringtab_free (flinfo->symstrtab);
10565   if (flinfo->contents != NULL)
10566     free (flinfo->contents);
10567   if (flinfo->external_relocs != NULL)
10568     free (flinfo->external_relocs);
10569   if (flinfo->internal_relocs != NULL)
10570     free (flinfo->internal_relocs);
10571   if (flinfo->external_syms != NULL)
10572     free (flinfo->external_syms);
10573   if (flinfo->locsym_shndx != NULL)
10574     free (flinfo->locsym_shndx);
10575   if (flinfo->internal_syms != NULL)
10576     free (flinfo->internal_syms);
10577   if (flinfo->indices != NULL)
10578     free (flinfo->indices);
10579   if (flinfo->sections != NULL)
10580     free (flinfo->sections);
10581   if (flinfo->symbuf != NULL)
10582     free (flinfo->symbuf);
10583   if (flinfo->symshndxbuf != NULL)
10584     free (flinfo->symshndxbuf);
10585   for (o = obfd->sections; o != NULL; o = o->next)
10586     {
10587       struct bfd_elf_section_data *esdo = elf_section_data (o);
10588       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10589         free (esdo->rel.hashes);
10590       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10591         free (esdo->rela.hashes);
10592     }
10593 }
10594
10595 /* Do the final step of an ELF link.  */
10596
10597 bfd_boolean
10598 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10599 {
10600   bfd_boolean dynamic;
10601   bfd_boolean emit_relocs;
10602   bfd *dynobj;
10603   struct elf_final_link_info flinfo;
10604   asection *o;
10605   struct bfd_link_order *p;
10606   bfd *sub;
10607   bfd_size_type max_contents_size;
10608   bfd_size_type max_external_reloc_size;
10609   bfd_size_type max_internal_reloc_count;
10610   bfd_size_type max_sym_count;
10611   bfd_size_type max_sym_shndx_count;
10612   file_ptr off;
10613   Elf_Internal_Sym elfsym;
10614   unsigned int i;
10615   Elf_Internal_Shdr *symtab_hdr;
10616   Elf_Internal_Shdr *symtab_shndx_hdr;
10617   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10618   struct elf_outext_info eoinfo;
10619   bfd_boolean merged;
10620   size_t relativecount = 0;
10621   asection *reldyn = 0;
10622   bfd_size_type amt;
10623   asection *attr_section = NULL;
10624   bfd_vma attr_size = 0;
10625   const char *std_attrs_section;
10626
10627   if (! is_elf_hash_table (info->hash))
10628     return FALSE;
10629
10630   if (info->shared)
10631     abfd->flags |= DYNAMIC;
10632
10633   dynamic = elf_hash_table (info)->dynamic_sections_created;
10634   dynobj = elf_hash_table (info)->dynobj;
10635
10636   emit_relocs = (info->relocatable
10637                  || info->emitrelocations);
10638
10639   flinfo.info = info;
10640   flinfo.output_bfd = abfd;
10641   flinfo.symstrtab = _bfd_elf_stringtab_init ();
10642   if (flinfo.symstrtab == NULL)
10643     return FALSE;
10644
10645   if (! dynamic)
10646     {
10647       flinfo.dynsym_sec = NULL;
10648       flinfo.hash_sec = NULL;
10649       flinfo.symver_sec = NULL;
10650     }
10651   else
10652     {
10653       flinfo.dynsym_sec = bfd_get_linker_section (dynobj, ".dynsym");
10654       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
10655       /* Note that dynsym_sec can be NULL (on VMS).  */
10656       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
10657       /* Note that it is OK if symver_sec is NULL.  */
10658     }
10659
10660   flinfo.contents = NULL;
10661   flinfo.external_relocs = NULL;
10662   flinfo.internal_relocs = NULL;
10663   flinfo.external_syms = NULL;
10664   flinfo.locsym_shndx = NULL;
10665   flinfo.internal_syms = NULL;
10666   flinfo.indices = NULL;
10667   flinfo.sections = NULL;
10668   flinfo.symbuf = NULL;
10669   flinfo.symshndxbuf = NULL;
10670   flinfo.symbuf_count = 0;
10671   flinfo.shndxbuf_size = 0;
10672   flinfo.filesym_count = 0;
10673
10674   /* The object attributes have been merged.  Remove the input
10675      sections from the link, and set the contents of the output
10676      secton.  */
10677   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10678   for (o = abfd->sections; o != NULL; o = o->next)
10679     {
10680       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10681           || strcmp (o->name, ".gnu.attributes") == 0)
10682         {
10683           for (p = o->map_head.link_order; p != NULL; p = p->next)
10684             {
10685               asection *input_section;
10686
10687               if (p->type != bfd_indirect_link_order)
10688                 continue;
10689               input_section = p->u.indirect.section;
10690               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10691                  elf_link_input_bfd ignores this section.  */
10692               input_section->flags &= ~SEC_HAS_CONTENTS;
10693             }
10694
10695           attr_size = bfd_elf_obj_attr_size (abfd);
10696           if (attr_size)
10697             {
10698               bfd_set_section_size (abfd, o, attr_size);
10699               attr_section = o;
10700               /* Skip this section later on.  */
10701               o->map_head.link_order = NULL;
10702             }
10703           else
10704             o->flags |= SEC_EXCLUDE;
10705         }
10706     }
10707
10708   /* Count up the number of relocations we will output for each output
10709      section, so that we know the sizes of the reloc sections.  We
10710      also figure out some maximum sizes.  */
10711   max_contents_size = 0;
10712   max_external_reloc_size = 0;
10713   max_internal_reloc_count = 0;
10714   max_sym_count = 0;
10715   max_sym_shndx_count = 0;
10716   merged = FALSE;
10717   for (o = abfd->sections; o != NULL; o = o->next)
10718     {
10719       struct bfd_elf_section_data *esdo = elf_section_data (o);
10720       o->reloc_count = 0;
10721
10722       for (p = o->map_head.link_order; p != NULL; p = p->next)
10723         {
10724           unsigned int reloc_count = 0;
10725           struct bfd_elf_section_data *esdi = NULL;
10726
10727           if (p->type == bfd_section_reloc_link_order
10728               || p->type == bfd_symbol_reloc_link_order)
10729             reloc_count = 1;
10730           else if (p->type == bfd_indirect_link_order)
10731             {
10732               asection *sec;
10733
10734               sec = p->u.indirect.section;
10735               esdi = elf_section_data (sec);
10736
10737               /* Mark all sections which are to be included in the
10738                  link.  This will normally be every section.  We need
10739                  to do this so that we can identify any sections which
10740                  the linker has decided to not include.  */
10741               sec->linker_mark = TRUE;
10742
10743               if (sec->flags & SEC_MERGE)
10744                 merged = TRUE;
10745
10746               if (esdo->this_hdr.sh_type == SHT_REL
10747                   || esdo->this_hdr.sh_type == SHT_RELA)
10748                 /* Some backends use reloc_count in relocation sections
10749                    to count particular types of relocs.  Of course,
10750                    reloc sections themselves can't have relocations.  */
10751                 reloc_count = 0;
10752               else if (info->relocatable || info->emitrelocations)
10753                 reloc_count = sec->reloc_count;
10754               else if (bed->elf_backend_count_relocs)
10755                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10756
10757               if (sec->rawsize > max_contents_size)
10758                 max_contents_size = sec->rawsize;
10759               if (sec->size > max_contents_size)
10760                 max_contents_size = sec->size;
10761
10762               /* We are interested in just local symbols, not all
10763                  symbols.  */
10764               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10765                   && (sec->owner->flags & DYNAMIC) == 0)
10766                 {
10767                   size_t sym_count;
10768
10769                   if (elf_bad_symtab (sec->owner))
10770                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10771                                  / bed->s->sizeof_sym);
10772                   else
10773                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10774
10775                   if (sym_count > max_sym_count)
10776                     max_sym_count = sym_count;
10777
10778                   if (sym_count > max_sym_shndx_count
10779                       && elf_symtab_shndx (sec->owner) != 0)
10780                     max_sym_shndx_count = sym_count;
10781
10782                   if ((sec->flags & SEC_RELOC) != 0)
10783                     {
10784                       size_t ext_size = 0;
10785
10786                       if (esdi->rel.hdr != NULL)
10787                         ext_size = esdi->rel.hdr->sh_size;
10788                       if (esdi->rela.hdr != NULL)
10789                         ext_size += esdi->rela.hdr->sh_size;
10790
10791                       if (ext_size > max_external_reloc_size)
10792                         max_external_reloc_size = ext_size;
10793                       if (sec->reloc_count > max_internal_reloc_count)
10794                         max_internal_reloc_count = sec->reloc_count;
10795                     }
10796                 }
10797             }
10798
10799           if (reloc_count == 0)
10800             continue;
10801
10802           o->reloc_count += reloc_count;
10803
10804           if (p->type == bfd_indirect_link_order
10805               && (info->relocatable || info->emitrelocations))
10806             {
10807               if (esdi->rel.hdr)
10808                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
10809               if (esdi->rela.hdr)
10810                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
10811             }
10812           else
10813             {
10814               if (o->use_rela_p)
10815                 esdo->rela.count += reloc_count;
10816               else
10817                 esdo->rel.count += reloc_count;
10818             }
10819         }
10820
10821       if (o->reloc_count > 0)
10822         o->flags |= SEC_RELOC;
10823       else
10824         {
10825           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
10826              set it (this is probably a bug) and if it is set
10827              assign_section_numbers will create a reloc section.  */
10828           o->flags &=~ SEC_RELOC;
10829         }
10830
10831       /* If the SEC_ALLOC flag is not set, force the section VMA to
10832          zero.  This is done in elf_fake_sections as well, but forcing
10833          the VMA to 0 here will ensure that relocs against these
10834          sections are handled correctly.  */
10835       if ((o->flags & SEC_ALLOC) == 0
10836           && ! o->user_set_vma)
10837         o->vma = 0;
10838     }
10839
10840   if (! info->relocatable && merged)
10841     elf_link_hash_traverse (elf_hash_table (info),
10842                             _bfd_elf_link_sec_merge_syms, abfd);
10843
10844   /* Figure out the file positions for everything but the symbol table
10845      and the relocs.  We set symcount to force assign_section_numbers
10846      to create a symbol table.  */
10847   bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
10848   BFD_ASSERT (! abfd->output_has_begun);
10849   if (! _bfd_elf_compute_section_file_positions (abfd, info))
10850     goto error_return;
10851
10852   /* Set sizes, and assign file positions for reloc sections.  */
10853   for (o = abfd->sections; o != NULL; o = o->next)
10854     {
10855       struct bfd_elf_section_data *esdo = elf_section_data (o);
10856       if ((o->flags & SEC_RELOC) != 0)
10857         {
10858           if (esdo->rel.hdr
10859               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
10860             goto error_return;
10861
10862           if (esdo->rela.hdr
10863               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
10864             goto error_return;
10865         }
10866
10867       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
10868          to count upwards while actually outputting the relocations.  */
10869       esdo->rel.count = 0;
10870       esdo->rela.count = 0;
10871     }
10872
10873   /* We have now assigned file positions for all the sections except
10874      .symtab, .strtab, and non-loaded reloc sections.  We start the
10875      .symtab section at the current file position, and write directly
10876      to it.  We build the .strtab section in memory.  */
10877   bfd_get_symcount (abfd) = 0;
10878   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10879   /* sh_name is set in prep_headers.  */
10880   symtab_hdr->sh_type = SHT_SYMTAB;
10881   /* sh_flags, sh_addr and sh_size all start off zero.  */
10882   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
10883   /* sh_link is set in assign_section_numbers.  */
10884   /* sh_info is set below.  */
10885   /* sh_offset is set just below.  */
10886   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
10887
10888   off = elf_next_file_pos (abfd);
10889   off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
10890
10891   /* Note that at this point elf_next_file_pos (abfd) is
10892      incorrect.  We do not yet know the size of the .symtab section.
10893      We correct next_file_pos below, after we do know the size.  */
10894
10895   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
10896      continuously seeking to the right position in the file.  */
10897   if (! info->keep_memory || max_sym_count < 20)
10898     flinfo.symbuf_size = 20;
10899   else
10900     flinfo.symbuf_size = max_sym_count;
10901   amt = flinfo.symbuf_size;
10902   amt *= bed->s->sizeof_sym;
10903   flinfo.symbuf = (bfd_byte *) bfd_malloc (amt);
10904   if (flinfo.symbuf == NULL)
10905     goto error_return;
10906   if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
10907     {
10908       /* Wild guess at number of output symbols.  realloc'd as needed.  */
10909       amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
10910       flinfo.shndxbuf_size = amt;
10911       amt *= sizeof (Elf_External_Sym_Shndx);
10912       flinfo.symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
10913       if (flinfo.symshndxbuf == NULL)
10914         goto error_return;
10915     }
10916
10917   /* Start writing out the symbol table.  The first symbol is always a
10918      dummy symbol.  */
10919   if (info->strip != strip_all
10920       || emit_relocs)
10921     {
10922       elfsym.st_value = 0;
10923       elfsym.st_size = 0;
10924       elfsym.st_info = 0;
10925       elfsym.st_other = 0;
10926       elfsym.st_shndx = SHN_UNDEF;
10927       elfsym.st_target_internal = 0;
10928       if (elf_link_output_sym (&flinfo, NULL, &elfsym, bfd_und_section_ptr,
10929                                NULL) != 1)
10930         goto error_return;
10931     }
10932
10933   /* Output a symbol for each section.  We output these even if we are
10934      discarding local symbols, since they are used for relocs.  These
10935      symbols have no names.  We store the index of each one in the
10936      index field of the section, so that we can find it again when
10937      outputting relocs.  */
10938   if (info->strip != strip_all
10939       || emit_relocs)
10940     {
10941       elfsym.st_size = 0;
10942       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10943       elfsym.st_other = 0;
10944       elfsym.st_value = 0;
10945       elfsym.st_target_internal = 0;
10946       for (i = 1; i < elf_numsections (abfd); i++)
10947         {
10948           o = bfd_section_from_elf_index (abfd, i);
10949           if (o != NULL)
10950             {
10951               o->target_index = bfd_get_symcount (abfd);
10952               elfsym.st_shndx = i;
10953               if (!info->relocatable)
10954                 elfsym.st_value = o->vma;
10955               if (elf_link_output_sym (&flinfo, NULL, &elfsym, o, NULL) != 1)
10956                 goto error_return;
10957             }
10958         }
10959     }
10960
10961   /* Allocate some memory to hold information read in from the input
10962      files.  */
10963   if (max_contents_size != 0)
10964     {
10965       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
10966       if (flinfo.contents == NULL)
10967         goto error_return;
10968     }
10969
10970   if (max_external_reloc_size != 0)
10971     {
10972       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
10973       if (flinfo.external_relocs == NULL)
10974         goto error_return;
10975     }
10976
10977   if (max_internal_reloc_count != 0)
10978     {
10979       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
10980       amt *= sizeof (Elf_Internal_Rela);
10981       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
10982       if (flinfo.internal_relocs == NULL)
10983         goto error_return;
10984     }
10985
10986   if (max_sym_count != 0)
10987     {
10988       amt = max_sym_count * bed->s->sizeof_sym;
10989       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
10990       if (flinfo.external_syms == NULL)
10991         goto error_return;
10992
10993       amt = max_sym_count * sizeof (Elf_Internal_Sym);
10994       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
10995       if (flinfo.internal_syms == NULL)
10996         goto error_return;
10997
10998       amt = max_sym_count * sizeof (long);
10999       flinfo.indices = (long int *) bfd_malloc (amt);
11000       if (flinfo.indices == NULL)
11001         goto error_return;
11002
11003       amt = max_sym_count * sizeof (asection *);
11004       flinfo.sections = (asection **) bfd_malloc (amt);
11005       if (flinfo.sections == NULL)
11006         goto error_return;
11007     }
11008
11009   if (max_sym_shndx_count != 0)
11010     {
11011       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11012       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11013       if (flinfo.locsym_shndx == NULL)
11014         goto error_return;
11015     }
11016
11017   if (elf_hash_table (info)->tls_sec)
11018     {
11019       bfd_vma base, end = 0;
11020       asection *sec;
11021
11022       for (sec = elf_hash_table (info)->tls_sec;
11023            sec && (sec->flags & SEC_THREAD_LOCAL);
11024            sec = sec->next)
11025         {
11026           bfd_size_type size = sec->size;
11027
11028           if (size == 0
11029               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11030             {
11031               struct bfd_link_order *ord = sec->map_tail.link_order;
11032
11033               if (ord != NULL)
11034                 size = ord->offset + ord->size;
11035             }
11036           end = sec->vma + size;
11037         }
11038       base = elf_hash_table (info)->tls_sec->vma;
11039       /* Only align end of TLS section if static TLS doesn't have special
11040          alignment requirements.  */
11041       if (bed->static_tls_alignment == 1)
11042         end = align_power (end,
11043                            elf_hash_table (info)->tls_sec->alignment_power);
11044       elf_hash_table (info)->tls_size = end - base;
11045     }
11046
11047   /* Reorder SHF_LINK_ORDER sections.  */
11048   for (o = abfd->sections; o != NULL; o = o->next)
11049     {
11050       if (!elf_fixup_link_order (abfd, o))
11051         return FALSE;
11052     }
11053
11054   /* Since ELF permits relocations to be against local symbols, we
11055      must have the local symbols available when we do the relocations.
11056      Since we would rather only read the local symbols once, and we
11057      would rather not keep them in memory, we handle all the
11058      relocations for a single input file at the same time.
11059
11060      Unfortunately, there is no way to know the total number of local
11061      symbols until we have seen all of them, and the local symbol
11062      indices precede the global symbol indices.  This means that when
11063      we are generating relocatable output, and we see a reloc against
11064      a global symbol, we can not know the symbol index until we have
11065      finished examining all the local symbols to see which ones we are
11066      going to output.  To deal with this, we keep the relocations in
11067      memory, and don't output them until the end of the link.  This is
11068      an unfortunate waste of memory, but I don't see a good way around
11069      it.  Fortunately, it only happens when performing a relocatable
11070      link, which is not the common case.  FIXME: If keep_memory is set
11071      we could write the relocs out and then read them again; I don't
11072      know how bad the memory loss will be.  */
11073
11074   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11075     sub->output_has_begun = FALSE;
11076   for (o = abfd->sections; o != NULL; o = o->next)
11077     {
11078       for (p = o->map_head.link_order; p != NULL; p = p->next)
11079         {
11080           if (p->type == bfd_indirect_link_order
11081               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11082                   == bfd_target_elf_flavour)
11083               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11084             {
11085               if (! sub->output_has_begun)
11086                 {
11087                   if (! elf_link_input_bfd (&flinfo, sub))
11088                     goto error_return;
11089                   sub->output_has_begun = TRUE;
11090                 }
11091             }
11092           else if (p->type == bfd_section_reloc_link_order
11093                    || p->type == bfd_symbol_reloc_link_order)
11094             {
11095               if (! elf_reloc_link_order (abfd, info, o, p))
11096                 goto error_return;
11097             }
11098           else
11099             {
11100               if (! _bfd_default_link_order (abfd, info, o, p))
11101                 {
11102                   if (p->type == bfd_indirect_link_order
11103                       && (bfd_get_flavour (sub)
11104                           == bfd_target_elf_flavour)
11105                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11106                           != bed->s->elfclass))
11107                     {
11108                       const char *iclass, *oclass;
11109
11110                       if (bed->s->elfclass == ELFCLASS64)
11111                         {
11112                           iclass = "ELFCLASS32";
11113                           oclass = "ELFCLASS64";
11114                         }
11115                       else
11116                         {
11117                           iclass = "ELFCLASS64";
11118                           oclass = "ELFCLASS32";
11119                         }
11120
11121                       bfd_set_error (bfd_error_wrong_format);
11122                       (*_bfd_error_handler)
11123                         (_("%B: file class %s incompatible with %s"),
11124                          sub, iclass, oclass);
11125                     }
11126
11127                   goto error_return;
11128                 }
11129             }
11130         }
11131     }
11132
11133   /* Free symbol buffer if needed.  */
11134   if (!info->reduce_memory_overheads)
11135     {
11136       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11137         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11138             && elf_tdata (sub)->symbuf)
11139           {
11140             free (elf_tdata (sub)->symbuf);
11141             elf_tdata (sub)->symbuf = NULL;
11142           }
11143     }
11144
11145   /* Output any global symbols that got converted to local in a
11146      version script or due to symbol visibility.  We do this in a
11147      separate step since ELF requires all local symbols to appear
11148      prior to any global symbols.  FIXME: We should only do this if
11149      some global symbols were, in fact, converted to become local.
11150      FIXME: Will this work correctly with the Irix 5 linker?  */
11151   eoinfo.failed = FALSE;
11152   eoinfo.flinfo = &flinfo;
11153   eoinfo.localsyms = TRUE;
11154   eoinfo.need_second_pass = FALSE;
11155   eoinfo.second_pass = FALSE;
11156   eoinfo.file_sym_done = FALSE;
11157   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11158   if (eoinfo.failed)
11159     return FALSE;
11160
11161   if (eoinfo.need_second_pass)
11162     {
11163       eoinfo.second_pass = TRUE;
11164       bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11165       if (eoinfo.failed)
11166         return FALSE;
11167     }
11168
11169   /* If backend needs to output some local symbols not present in the hash
11170      table, do it now.  */
11171   if (bed->elf_backend_output_arch_local_syms)
11172     {
11173       typedef int (*out_sym_func)
11174         (void *, const char *, Elf_Internal_Sym *, asection *,
11175          struct elf_link_hash_entry *);
11176
11177       if (! ((*bed->elf_backend_output_arch_local_syms)
11178              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
11179         return FALSE;
11180     }
11181
11182   /* That wrote out all the local symbols.  Finish up the symbol table
11183      with the global symbols. Even if we want to strip everything we
11184      can, we still need to deal with those global symbols that got
11185      converted to local in a version script.  */
11186
11187   /* The sh_info field records the index of the first non local symbol.  */
11188   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11189
11190   if (dynamic
11191       && flinfo.dynsym_sec != NULL
11192       && flinfo.dynsym_sec->output_section != bfd_abs_section_ptr)
11193     {
11194       Elf_Internal_Sym sym;
11195       bfd_byte *dynsym = flinfo.dynsym_sec->contents;
11196       long last_local = 0;
11197
11198       /* Write out the section symbols for the output sections.  */
11199       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
11200         {
11201           asection *s;
11202
11203           sym.st_size = 0;
11204           sym.st_name = 0;
11205           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11206           sym.st_other = 0;
11207           sym.st_target_internal = 0;
11208
11209           for (s = abfd->sections; s != NULL; s = s->next)
11210             {
11211               int indx;
11212               bfd_byte *dest;
11213               long dynindx;
11214
11215               dynindx = elf_section_data (s)->dynindx;
11216               if (dynindx <= 0)
11217                 continue;
11218               indx = elf_section_data (s)->this_idx;
11219               BFD_ASSERT (indx > 0);
11220               sym.st_shndx = indx;
11221               if (! check_dynsym (abfd, &sym))
11222                 return FALSE;
11223               sym.st_value = s->vma;
11224               dest = dynsym + dynindx * bed->s->sizeof_sym;
11225               if (last_local < dynindx)
11226                 last_local = dynindx;
11227               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11228             }
11229         }
11230
11231       /* Write out the local dynsyms.  */
11232       if (elf_hash_table (info)->dynlocal)
11233         {
11234           struct elf_link_local_dynamic_entry *e;
11235           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11236             {
11237               asection *s;
11238               bfd_byte *dest;
11239
11240               /* Copy the internal symbol and turn off visibility.
11241                  Note that we saved a word of storage and overwrote
11242                  the original st_name with the dynstr_index.  */
11243               sym = e->isym;
11244               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11245
11246               s = bfd_section_from_elf_index (e->input_bfd,
11247                                               e->isym.st_shndx);
11248               if (s != NULL)
11249                 {
11250                   sym.st_shndx =
11251                     elf_section_data (s->output_section)->this_idx;
11252                   if (! check_dynsym (abfd, &sym))
11253                     return FALSE;
11254                   sym.st_value = (s->output_section->vma
11255                                   + s->output_offset
11256                                   + e->isym.st_value);
11257                 }
11258
11259               if (last_local < e->dynindx)
11260                 last_local = e->dynindx;
11261
11262               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11263               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11264             }
11265         }
11266
11267       elf_section_data (flinfo.dynsym_sec->output_section)->this_hdr.sh_info =
11268         last_local + 1;
11269     }
11270
11271   /* We get the global symbols from the hash table.  */
11272   eoinfo.failed = FALSE;
11273   eoinfo.localsyms = FALSE;
11274   eoinfo.flinfo = &flinfo;
11275   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11276   if (eoinfo.failed)
11277     return FALSE;
11278
11279   /* If backend needs to output some symbols not present in the hash
11280      table, do it now.  */
11281   if (bed->elf_backend_output_arch_syms)
11282     {
11283       typedef int (*out_sym_func)
11284         (void *, const char *, Elf_Internal_Sym *, asection *,
11285          struct elf_link_hash_entry *);
11286
11287       if (! ((*bed->elf_backend_output_arch_syms)
11288              (abfd, info, &flinfo, (out_sym_func) elf_link_output_sym)))
11289         return FALSE;
11290     }
11291
11292   /* Flush all symbols to the file.  */
11293   if (! elf_link_flush_output_syms (&flinfo, bed))
11294     return FALSE;
11295
11296   /* Now we know the size of the symtab section.  */
11297   off += symtab_hdr->sh_size;
11298
11299   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
11300   if (symtab_shndx_hdr->sh_name != 0)
11301     {
11302       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11303       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11304       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11305       amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11306       symtab_shndx_hdr->sh_size = amt;
11307
11308       off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11309                                                        off, TRUE);
11310
11311       if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11312           || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11313         return FALSE;
11314     }
11315
11316
11317   if (bfd_get_symcount (abfd) > 0)
11318     {
11319       /* Finish up and write out the symbol string table (.strtab)
11320          section.  */
11321       Elf_Internal_Shdr *symstrtab_hdr;
11322
11323       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11324       /* sh_name was set in prep_headers.  */
11325       symstrtab_hdr->sh_type = SHT_STRTAB;
11326       symstrtab_hdr->sh_flags = 0;
11327       symstrtab_hdr->sh_addr = 0;
11328       symstrtab_hdr->sh_size = _bfd_stringtab_size (flinfo.symstrtab);
11329       symstrtab_hdr->sh_entsize = 0;
11330       symstrtab_hdr->sh_link = 0;
11331       symstrtab_hdr->sh_info = 0;
11332       /* sh_offset is set just below.  */
11333       symstrtab_hdr->sh_addralign = 1;
11334
11335       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11336                                                        off, TRUE);
11337       elf_next_file_pos (abfd) = off;
11338
11339       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11340           || ! _bfd_stringtab_emit (abfd, flinfo.symstrtab))
11341         return FALSE;
11342     }
11343
11344   /* Adjust the relocs to have the correct symbol indices.  */
11345   for (o = abfd->sections; o != NULL; o = o->next)
11346     {
11347       struct bfd_elf_section_data *esdo = elf_section_data (o);
11348       bfd_boolean sort;
11349       if ((o->flags & SEC_RELOC) == 0)
11350         continue;
11351
11352       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11353       if (esdo->rel.hdr != NULL)
11354         elf_link_adjust_relocs (abfd, &esdo->rel, sort);
11355       if (esdo->rela.hdr != NULL)
11356         elf_link_adjust_relocs (abfd, &esdo->rela, sort);
11357
11358       /* Set the reloc_count field to 0 to prevent write_relocs from
11359          trying to swap the relocs out itself.  */
11360       o->reloc_count = 0;
11361     }
11362
11363   if (dynamic && info->combreloc && dynobj != NULL)
11364     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11365
11366   /* If we are linking against a dynamic object, or generating a
11367      shared library, finish up the dynamic linking information.  */
11368   if (dynamic)
11369     {
11370       bfd_byte *dyncon, *dynconend;
11371
11372       /* Fix up .dynamic entries.  */
11373       o = bfd_get_linker_section (dynobj, ".dynamic");
11374       BFD_ASSERT (o != NULL);
11375
11376       dyncon = o->contents;
11377       dynconend = o->contents + o->size;
11378       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11379         {
11380           Elf_Internal_Dyn dyn;
11381           const char *name;
11382           unsigned int type;
11383
11384           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11385
11386           switch (dyn.d_tag)
11387             {
11388             default:
11389               continue;
11390             case DT_NULL:
11391               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11392                 {
11393                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11394                     {
11395                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11396                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11397                     default: continue;
11398                     }
11399                   dyn.d_un.d_val = relativecount;
11400                   relativecount = 0;
11401                   break;
11402                 }
11403               continue;
11404
11405             case DT_INIT:
11406               name = info->init_function;
11407               goto get_sym;
11408             case DT_FINI:
11409               name = info->fini_function;
11410             get_sym:
11411               {
11412                 struct elf_link_hash_entry *h;
11413
11414                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11415                                           FALSE, FALSE, TRUE);
11416                 if (h != NULL
11417                     && (h->root.type == bfd_link_hash_defined
11418                         || h->root.type == bfd_link_hash_defweak))
11419                   {
11420                     dyn.d_un.d_ptr = h->root.u.def.value;
11421                     o = h->root.u.def.section;
11422                     if (o->output_section != NULL)
11423                       dyn.d_un.d_ptr += (o->output_section->vma
11424                                          + o->output_offset);
11425                     else
11426                       {
11427                         /* The symbol is imported from another shared
11428                            library and does not apply to this one.  */
11429                         dyn.d_un.d_ptr = 0;
11430                       }
11431                     break;
11432                   }
11433               }
11434               continue;
11435
11436             case DT_PREINIT_ARRAYSZ:
11437               name = ".preinit_array";
11438               goto get_size;
11439             case DT_INIT_ARRAYSZ:
11440               name = ".init_array";
11441               goto get_size;
11442             case DT_FINI_ARRAYSZ:
11443               name = ".fini_array";
11444             get_size:
11445               o = bfd_get_section_by_name (abfd, name);
11446               if (o == NULL)
11447                 {
11448                   (*_bfd_error_handler)
11449                     (_("%B: could not find output section %s"), abfd, name);
11450                   goto error_return;
11451                 }
11452               if (o->size == 0)
11453                 (*_bfd_error_handler)
11454                   (_("warning: %s section has zero size"), name);
11455               dyn.d_un.d_val = o->size;
11456               break;
11457
11458             case DT_PREINIT_ARRAY:
11459               name = ".preinit_array";
11460               goto get_vma;
11461             case DT_INIT_ARRAY:
11462               name = ".init_array";
11463               goto get_vma;
11464             case DT_FINI_ARRAY:
11465               name = ".fini_array";
11466               goto get_vma;
11467
11468             case DT_HASH:
11469               name = ".hash";
11470               goto get_vma;
11471             case DT_GNU_HASH:
11472               name = ".gnu.hash";
11473               goto get_vma;
11474             case DT_STRTAB:
11475               name = ".dynstr";
11476               goto get_vma;
11477             case DT_SYMTAB:
11478               name = ".dynsym";
11479               goto get_vma;
11480             case DT_VERDEF:
11481               name = ".gnu.version_d";
11482               goto get_vma;
11483             case DT_VERNEED:
11484               name = ".gnu.version_r";
11485               goto get_vma;
11486             case DT_VERSYM:
11487               name = ".gnu.version";
11488             get_vma:
11489               o = bfd_get_section_by_name (abfd, name);
11490               if (o == NULL)
11491                 {
11492                   (*_bfd_error_handler)
11493                     (_("%B: could not find output section %s"), abfd, name);
11494                   goto error_return;
11495                 }
11496               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11497                 {
11498                   (*_bfd_error_handler)
11499                     (_("warning: section '%s' is being made into a note"), name);
11500                   bfd_set_error (bfd_error_nonrepresentable_section);
11501                   goto error_return;
11502                 }
11503               dyn.d_un.d_ptr = o->vma;
11504               break;
11505
11506             case DT_REL:
11507             case DT_RELA:
11508             case DT_RELSZ:
11509             case DT_RELASZ:
11510               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11511                 type = SHT_REL;
11512               else
11513                 type = SHT_RELA;
11514               dyn.d_un.d_val = 0;
11515               dyn.d_un.d_ptr = 0;
11516               for (i = 1; i < elf_numsections (abfd); i++)
11517                 {
11518                   Elf_Internal_Shdr *hdr;
11519
11520                   hdr = elf_elfsections (abfd)[i];
11521                   if (hdr->sh_type == type
11522                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11523                     {
11524                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11525                         dyn.d_un.d_val += hdr->sh_size;
11526                       else
11527                         {
11528                           if (dyn.d_un.d_ptr == 0
11529                               || hdr->sh_addr < dyn.d_un.d_ptr)
11530                             dyn.d_un.d_ptr = hdr->sh_addr;
11531                         }
11532                     }
11533                 }
11534               break;
11535             }
11536           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11537         }
11538     }
11539
11540   /* If we have created any dynamic sections, then output them.  */
11541   if (dynobj != NULL)
11542     {
11543       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11544         goto error_return;
11545
11546       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11547       if (((info->warn_shared_textrel && info->shared)
11548            || info->error_textrel)
11549           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11550         {
11551           bfd_byte *dyncon, *dynconend;
11552
11553           dyncon = o->contents;
11554           dynconend = o->contents + o->size;
11555           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11556             {
11557               Elf_Internal_Dyn dyn;
11558
11559               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11560
11561               if (dyn.d_tag == DT_TEXTREL)
11562                 {
11563                   if (info->error_textrel)
11564                     info->callbacks->einfo
11565                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11566                   else
11567                     info->callbacks->einfo
11568                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11569                   break;
11570                 }
11571             }
11572         }
11573
11574       for (o = dynobj->sections; o != NULL; o = o->next)
11575         {
11576           if ((o->flags & SEC_HAS_CONTENTS) == 0
11577               || o->size == 0
11578               || o->output_section == bfd_abs_section_ptr)
11579             continue;
11580           if ((o->flags & SEC_LINKER_CREATED) == 0)
11581             {
11582               /* At this point, we are only interested in sections
11583                  created by _bfd_elf_link_create_dynamic_sections.  */
11584               continue;
11585             }
11586           if (elf_hash_table (info)->stab_info.stabstr == o)
11587             continue;
11588           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11589             continue;
11590           if (strcmp (o->name, ".dynstr") != 0)
11591             {
11592               /* FIXME: octets_per_byte.  */
11593               if (! bfd_set_section_contents (abfd, o->output_section,
11594                                               o->contents,
11595                                               (file_ptr) o->output_offset,
11596                                               o->size))
11597                 goto error_return;
11598             }
11599           else
11600             {
11601               /* The contents of the .dynstr section are actually in a
11602                  stringtab.  */
11603               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11604               if (bfd_seek (abfd, off, SEEK_SET) != 0
11605                   || ! _bfd_elf_strtab_emit (abfd,
11606                                              elf_hash_table (info)->dynstr))
11607                 goto error_return;
11608             }
11609         }
11610     }
11611
11612   if (info->relocatable)
11613     {
11614       bfd_boolean failed = FALSE;
11615
11616       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11617       if (failed)
11618         goto error_return;
11619     }
11620
11621   /* If we have optimized stabs strings, output them.  */
11622   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11623     {
11624       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11625         goto error_return;
11626     }
11627
11628   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11629     goto error_return;
11630
11631   elf_final_link_free (abfd, &flinfo);
11632
11633   elf_linker (abfd) = TRUE;
11634
11635   if (attr_section)
11636     {
11637       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11638       if (contents == NULL)
11639         return FALSE;   /* Bail out and fail.  */
11640       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11641       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11642       free (contents);
11643     }
11644
11645   return TRUE;
11646
11647  error_return:
11648   elf_final_link_free (abfd, &flinfo);
11649   return FALSE;
11650 }
11651 \f
11652 /* Initialize COOKIE for input bfd ABFD.  */
11653
11654 static bfd_boolean
11655 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11656                    struct bfd_link_info *info, bfd *abfd)
11657 {
11658   Elf_Internal_Shdr *symtab_hdr;
11659   const struct elf_backend_data *bed;
11660
11661   bed = get_elf_backend_data (abfd);
11662   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11663
11664   cookie->abfd = abfd;
11665   cookie->sym_hashes = elf_sym_hashes (abfd);
11666   cookie->bad_symtab = elf_bad_symtab (abfd);
11667   if (cookie->bad_symtab)
11668     {
11669       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11670       cookie->extsymoff = 0;
11671     }
11672   else
11673     {
11674       cookie->locsymcount = symtab_hdr->sh_info;
11675       cookie->extsymoff = symtab_hdr->sh_info;
11676     }
11677
11678   if (bed->s->arch_size == 32)
11679     cookie->r_sym_shift = 8;
11680   else
11681     cookie->r_sym_shift = 32;
11682
11683   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11684   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11685     {
11686       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11687                                               cookie->locsymcount, 0,
11688                                               NULL, NULL, NULL);
11689       if (cookie->locsyms == NULL)
11690         {
11691           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11692           return FALSE;
11693         }
11694       if (info->keep_memory)
11695         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11696     }
11697   return TRUE;
11698 }
11699
11700 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11701
11702 static void
11703 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11704 {
11705   Elf_Internal_Shdr *symtab_hdr;
11706
11707   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11708   if (cookie->locsyms != NULL
11709       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11710     free (cookie->locsyms);
11711 }
11712
11713 /* Initialize the relocation information in COOKIE for input section SEC
11714    of input bfd ABFD.  */
11715
11716 static bfd_boolean
11717 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11718                         struct bfd_link_info *info, bfd *abfd,
11719                         asection *sec)
11720 {
11721   const struct elf_backend_data *bed;
11722
11723   if (sec->reloc_count == 0)
11724     {
11725       cookie->rels = NULL;
11726       cookie->relend = NULL;
11727     }
11728   else
11729     {
11730       bed = get_elf_backend_data (abfd);
11731
11732       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11733                                                 info->keep_memory);
11734       if (cookie->rels == NULL)
11735         return FALSE;
11736       cookie->rel = cookie->rels;
11737       cookie->relend = (cookie->rels
11738                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11739     }
11740   cookie->rel = cookie->rels;
11741   return TRUE;
11742 }
11743
11744 /* Free the memory allocated by init_reloc_cookie_rels,
11745    if appropriate.  */
11746
11747 static void
11748 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11749                         asection *sec)
11750 {
11751   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11752     free (cookie->rels);
11753 }
11754
11755 /* Initialize the whole of COOKIE for input section SEC.  */
11756
11757 static bfd_boolean
11758 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11759                                struct bfd_link_info *info,
11760                                asection *sec)
11761 {
11762   if (!init_reloc_cookie (cookie, info, sec->owner))
11763     goto error1;
11764   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11765     goto error2;
11766   return TRUE;
11767
11768  error2:
11769   fini_reloc_cookie (cookie, sec->owner);
11770  error1:
11771   return FALSE;
11772 }
11773
11774 /* Free the memory allocated by init_reloc_cookie_for_section,
11775    if appropriate.  */
11776
11777 static void
11778 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11779                                asection *sec)
11780 {
11781   fini_reloc_cookie_rels (cookie, sec);
11782   fini_reloc_cookie (cookie, sec->owner);
11783 }
11784 \f
11785 /* Garbage collect unused sections.  */
11786
11787 /* Default gc_mark_hook.  */
11788
11789 asection *
11790 _bfd_elf_gc_mark_hook (asection *sec,
11791                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
11792                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
11793                        struct elf_link_hash_entry *h,
11794                        Elf_Internal_Sym *sym)
11795 {
11796   const char *sec_name;
11797
11798   if (h != NULL)
11799     {
11800       switch (h->root.type)
11801         {
11802         case bfd_link_hash_defined:
11803         case bfd_link_hash_defweak:
11804           return h->root.u.def.section;
11805
11806         case bfd_link_hash_common:
11807           return h->root.u.c.p->section;
11808
11809         case bfd_link_hash_undefined:
11810         case bfd_link_hash_undefweak:
11811           /* To work around a glibc bug, keep all XXX input sections
11812              when there is an as yet undefined reference to __start_XXX
11813              or __stop_XXX symbols.  The linker will later define such
11814              symbols for orphan input sections that have a name
11815              representable as a C identifier.  */
11816           if (strncmp (h->root.root.string, "__start_", 8) == 0)
11817             sec_name = h->root.root.string + 8;
11818           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
11819             sec_name = h->root.root.string + 7;
11820           else
11821             sec_name = NULL;
11822
11823           if (sec_name && *sec_name != '\0')
11824             {
11825               bfd *i;
11826
11827               for (i = info->input_bfds; i; i = i->link.next)
11828                 {
11829                   sec = bfd_get_section_by_name (i, sec_name);
11830                   if (sec)
11831                     sec->flags |= SEC_KEEP;
11832                 }
11833             }
11834           break;
11835
11836         default:
11837           break;
11838         }
11839     }
11840   else
11841     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
11842
11843   return NULL;
11844 }
11845
11846 /* COOKIE->rel describes a relocation against section SEC, which is
11847    a section we've decided to keep.  Return the section that contains
11848    the relocation symbol, or NULL if no section contains it.  */
11849
11850 asection *
11851 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
11852                        elf_gc_mark_hook_fn gc_mark_hook,
11853                        struct elf_reloc_cookie *cookie)
11854 {
11855   unsigned long r_symndx;
11856   struct elf_link_hash_entry *h;
11857
11858   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
11859   if (r_symndx == STN_UNDEF)
11860     return NULL;
11861
11862   if (r_symndx >= cookie->locsymcount
11863       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11864     {
11865       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
11866       if (h == NULL)
11867         {
11868           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
11869                                   sec->owner);
11870           return NULL;
11871         }
11872       while (h->root.type == bfd_link_hash_indirect
11873              || h->root.type == bfd_link_hash_warning)
11874         h = (struct elf_link_hash_entry *) h->root.u.i.link;
11875       h->mark = 1;
11876       /* If this symbol is weak and there is a non-weak definition, we
11877          keep the non-weak definition because many backends put
11878          dynamic reloc info on the non-weak definition for code
11879          handling copy relocs.  */
11880       if (h->u.weakdef != NULL)
11881         h->u.weakdef->mark = 1;
11882       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
11883     }
11884
11885   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
11886                           &cookie->locsyms[r_symndx]);
11887 }
11888
11889 /* COOKIE->rel describes a relocation against section SEC, which is
11890    a section we've decided to keep.  Mark the section that contains
11891    the relocation symbol.  */
11892
11893 bfd_boolean
11894 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
11895                         asection *sec,
11896                         elf_gc_mark_hook_fn gc_mark_hook,
11897                         struct elf_reloc_cookie *cookie)
11898 {
11899   asection *rsec;
11900
11901   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
11902   if (rsec && !rsec->gc_mark)
11903     {
11904       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
11905           || (rsec->owner->flags & DYNAMIC) != 0)
11906         rsec->gc_mark = 1;
11907       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
11908         return FALSE;
11909     }
11910   return TRUE;
11911 }
11912
11913 /* The mark phase of garbage collection.  For a given section, mark
11914    it and any sections in this section's group, and all the sections
11915    which define symbols to which it refers.  */
11916
11917 bfd_boolean
11918 _bfd_elf_gc_mark (struct bfd_link_info *info,
11919                   asection *sec,
11920                   elf_gc_mark_hook_fn gc_mark_hook)
11921 {
11922   bfd_boolean ret;
11923   asection *group_sec, *eh_frame;
11924
11925   sec->gc_mark = 1;
11926
11927   /* Mark all the sections in the group.  */
11928   group_sec = elf_section_data (sec)->next_in_group;
11929   if (group_sec && !group_sec->gc_mark)
11930     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
11931       return FALSE;
11932
11933   /* Look through the section relocs.  */
11934   ret = TRUE;
11935   eh_frame = elf_eh_frame_section (sec->owner);
11936   if ((sec->flags & SEC_RELOC) != 0
11937       && sec->reloc_count > 0
11938       && sec != eh_frame)
11939     {
11940       struct elf_reloc_cookie cookie;
11941
11942       if (!init_reloc_cookie_for_section (&cookie, info, sec))
11943         ret = FALSE;
11944       else
11945         {
11946           for (; cookie.rel < cookie.relend; cookie.rel++)
11947             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
11948               {
11949                 ret = FALSE;
11950                 break;
11951               }
11952           fini_reloc_cookie_for_section (&cookie, sec);
11953         }
11954     }
11955
11956   if (ret && eh_frame && elf_fde_list (sec))
11957     {
11958       struct elf_reloc_cookie cookie;
11959
11960       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
11961         ret = FALSE;
11962       else
11963         {
11964           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
11965                                       gc_mark_hook, &cookie))
11966             ret = FALSE;
11967           fini_reloc_cookie_for_section (&cookie, eh_frame);
11968         }
11969     }
11970
11971   return ret;
11972 }
11973
11974 /* Keep debug and special sections.  */
11975
11976 bfd_boolean
11977 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
11978                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
11979 {
11980   bfd *ibfd;
11981
11982   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
11983     {
11984       asection *isec;
11985       bfd_boolean some_kept;
11986       bfd_boolean debug_frag_seen;
11987
11988       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
11989         continue;
11990
11991       /* Ensure all linker created sections are kept,
11992          see if any other section is already marked,
11993          and note if we have any fragmented debug sections.  */
11994       debug_frag_seen = some_kept = FALSE;
11995       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11996         {
11997           if ((isec->flags & SEC_LINKER_CREATED) != 0)
11998             isec->gc_mark = 1;
11999           else if (isec->gc_mark)
12000             some_kept = TRUE;
12001
12002           if (debug_frag_seen == FALSE
12003               && (isec->flags & SEC_DEBUGGING)
12004               && CONST_STRNEQ (isec->name, ".debug_line."))
12005             debug_frag_seen = TRUE;
12006         }
12007
12008       /* If no section in this file will be kept, then we can
12009          toss out the debug and special sections.  */
12010       if (!some_kept)
12011         continue;
12012
12013       /* Keep debug and special sections like .comment when they are
12014          not part of a group, or when we have single-member groups.  */
12015       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12016         if ((elf_next_in_group (isec) == NULL
12017              || elf_next_in_group (isec) == isec)
12018             && ((isec->flags & SEC_DEBUGGING) != 0
12019                 || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0))
12020           isec->gc_mark = 1;
12021
12022       if (! debug_frag_seen)
12023         continue;
12024
12025       /* Look for CODE sections which are going to be discarded,
12026          and find and discard any fragmented debug sections which
12027          are associated with that code section.  */
12028       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12029         if ((isec->flags & SEC_CODE) != 0
12030             && isec->gc_mark == 0)
12031           {
12032             unsigned int ilen;
12033             asection *dsec;
12034
12035             ilen = strlen (isec->name);
12036
12037             /* Association is determined by the name of the debug section
12038                containing the name of the code section as a suffix.  For
12039                example .debug_line.text.foo is a debug section associated
12040                with .text.foo.  */
12041             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12042               {
12043                 unsigned int dlen;
12044
12045                 if (dsec->gc_mark == 0
12046                     || (dsec->flags & SEC_DEBUGGING) == 0)
12047                   continue;
12048
12049                 dlen = strlen (dsec->name);
12050
12051                 if (dlen > ilen
12052                     && strncmp (dsec->name + (dlen - ilen),
12053                                 isec->name, ilen) == 0)
12054                   {
12055                     dsec->gc_mark = 0;
12056                     break;
12057                   }
12058               }
12059           }
12060     }
12061   return TRUE;
12062 }
12063
12064 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12065
12066 struct elf_gc_sweep_symbol_info
12067 {
12068   struct bfd_link_info *info;
12069   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12070                        bfd_boolean);
12071 };
12072
12073 static bfd_boolean
12074 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12075 {
12076   if (!h->mark
12077       && (((h->root.type == bfd_link_hash_defined
12078             || h->root.type == bfd_link_hash_defweak)
12079            && !(h->def_regular
12080                 && h->root.u.def.section->gc_mark))
12081           || h->root.type == bfd_link_hash_undefined
12082           || h->root.type == bfd_link_hash_undefweak))
12083     {
12084       struct elf_gc_sweep_symbol_info *inf;
12085
12086       inf = (struct elf_gc_sweep_symbol_info *) data;
12087       (*inf->hide_symbol) (inf->info, h, TRUE);
12088       h->def_regular = 0;
12089       h->ref_regular = 0;
12090       h->ref_regular_nonweak = 0;
12091     }
12092
12093   return TRUE;
12094 }
12095
12096 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12097
12098 typedef bfd_boolean (*gc_sweep_hook_fn)
12099   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12100
12101 static bfd_boolean
12102 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12103 {
12104   bfd *sub;
12105   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12106   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12107   unsigned long section_sym_count;
12108   struct elf_gc_sweep_symbol_info sweep_info;
12109
12110   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12111     {
12112       asection *o;
12113
12114       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12115         continue;
12116
12117       for (o = sub->sections; o != NULL; o = o->next)
12118         {
12119           /* When any section in a section group is kept, we keep all
12120              sections in the section group.  If the first member of
12121              the section group is excluded, we will also exclude the
12122              group section.  */
12123           if (o->flags & SEC_GROUP)
12124             {
12125               asection *first = elf_next_in_group (o);
12126               o->gc_mark = first->gc_mark;
12127             }
12128
12129           if (o->gc_mark)
12130             continue;
12131
12132           /* Skip sweeping sections already excluded.  */
12133           if (o->flags & SEC_EXCLUDE)
12134             continue;
12135
12136           /* Since this is early in the link process, it is simple
12137              to remove a section from the output.  */
12138           o->flags |= SEC_EXCLUDE;
12139
12140           if (info->print_gc_sections && o->size != 0)
12141             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12142
12143           /* But we also have to update some of the relocation
12144              info we collected before.  */
12145           if (gc_sweep_hook
12146               && (o->flags & SEC_RELOC) != 0
12147               && o->reloc_count != 0
12148               && !((info->strip == strip_all || info->strip == strip_debugger)
12149                    && (o->flags & SEC_DEBUGGING) != 0)
12150               && !bfd_is_abs_section (o->output_section))
12151             {
12152               Elf_Internal_Rela *internal_relocs;
12153               bfd_boolean r;
12154
12155               internal_relocs
12156                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12157                                              info->keep_memory);
12158               if (internal_relocs == NULL)
12159                 return FALSE;
12160
12161               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12162
12163               if (elf_section_data (o)->relocs != internal_relocs)
12164                 free (internal_relocs);
12165
12166               if (!r)
12167                 return FALSE;
12168             }
12169         }
12170     }
12171
12172   /* Remove the symbols that were in the swept sections from the dynamic
12173      symbol table.  GCFIXME: Anyone know how to get them out of the
12174      static symbol table as well?  */
12175   sweep_info.info = info;
12176   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12177   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12178                           &sweep_info);
12179
12180   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12181   return TRUE;
12182 }
12183
12184 /* Propagate collected vtable information.  This is called through
12185    elf_link_hash_traverse.  */
12186
12187 static bfd_boolean
12188 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12189 {
12190   /* Those that are not vtables.  */
12191   if (h->vtable == NULL || h->vtable->parent == NULL)
12192     return TRUE;
12193
12194   /* Those vtables that do not have parents, we cannot merge.  */
12195   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12196     return TRUE;
12197
12198   /* If we've already been done, exit.  */
12199   if (h->vtable->used && h->vtable->used[-1])
12200     return TRUE;
12201
12202   /* Make sure the parent's table is up to date.  */
12203   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12204
12205   if (h->vtable->used == NULL)
12206     {
12207       /* None of this table's entries were referenced.  Re-use the
12208          parent's table.  */
12209       h->vtable->used = h->vtable->parent->vtable->used;
12210       h->vtable->size = h->vtable->parent->vtable->size;
12211     }
12212   else
12213     {
12214       size_t n;
12215       bfd_boolean *cu, *pu;
12216
12217       /* Or the parent's entries into ours.  */
12218       cu = h->vtable->used;
12219       cu[-1] = TRUE;
12220       pu = h->vtable->parent->vtable->used;
12221       if (pu != NULL)
12222         {
12223           const struct elf_backend_data *bed;
12224           unsigned int log_file_align;
12225
12226           bed = get_elf_backend_data (h->root.u.def.section->owner);
12227           log_file_align = bed->s->log_file_align;
12228           n = h->vtable->parent->vtable->size >> log_file_align;
12229           while (n--)
12230             {
12231               if (*pu)
12232                 *cu = TRUE;
12233               pu++;
12234               cu++;
12235             }
12236         }
12237     }
12238
12239   return TRUE;
12240 }
12241
12242 static bfd_boolean
12243 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12244 {
12245   asection *sec;
12246   bfd_vma hstart, hend;
12247   Elf_Internal_Rela *relstart, *relend, *rel;
12248   const struct elf_backend_data *bed;
12249   unsigned int log_file_align;
12250
12251   /* Take care of both those symbols that do not describe vtables as
12252      well as those that are not loaded.  */
12253   if (h->vtable == NULL || h->vtable->parent == NULL)
12254     return TRUE;
12255
12256   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12257               || h->root.type == bfd_link_hash_defweak);
12258
12259   sec = h->root.u.def.section;
12260   hstart = h->root.u.def.value;
12261   hend = hstart + h->size;
12262
12263   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12264   if (!relstart)
12265     return *(bfd_boolean *) okp = FALSE;
12266   bed = get_elf_backend_data (sec->owner);
12267   log_file_align = bed->s->log_file_align;
12268
12269   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12270
12271   for (rel = relstart; rel < relend; ++rel)
12272     if (rel->r_offset >= hstart && rel->r_offset < hend)
12273       {
12274         /* If the entry is in use, do nothing.  */
12275         if (h->vtable->used
12276             && (rel->r_offset - hstart) < h->vtable->size)
12277           {
12278             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12279             if (h->vtable->used[entry])
12280               continue;
12281           }
12282         /* Otherwise, kill it.  */
12283         rel->r_offset = rel->r_info = rel->r_addend = 0;
12284       }
12285
12286   return TRUE;
12287 }
12288
12289 /* Mark sections containing dynamically referenced symbols.  When
12290    building shared libraries, we must assume that any visible symbol is
12291    referenced.  */
12292
12293 bfd_boolean
12294 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12295 {
12296   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12297   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12298
12299   if ((h->root.type == bfd_link_hash_defined
12300        || h->root.type == bfd_link_hash_defweak)
12301       && (h->ref_dynamic
12302           || (h->def_regular
12303               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12304               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12305               && (!info->executable
12306                   || info->export_dynamic
12307                   || (h->dynamic
12308                       && d != NULL
12309                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12310               && (strchr (h->root.root.string, ELF_VER_CHR) != NULL
12311                   || !bfd_hide_sym_by_version (info->version_info,
12312                                                h->root.root.string)))))
12313     h->root.u.def.section->flags |= SEC_KEEP;
12314
12315   return TRUE;
12316 }
12317
12318 /* Keep all sections containing symbols undefined on the command-line,
12319    and the section containing the entry symbol.  */
12320
12321 void
12322 _bfd_elf_gc_keep (struct bfd_link_info *info)
12323 {
12324   struct bfd_sym_chain *sym;
12325
12326   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12327     {
12328       struct elf_link_hash_entry *h;
12329
12330       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12331                                 FALSE, FALSE, FALSE);
12332
12333       if (h != NULL
12334           && (h->root.type == bfd_link_hash_defined
12335               || h->root.type == bfd_link_hash_defweak)
12336           && !bfd_is_abs_section (h->root.u.def.section))
12337         h->root.u.def.section->flags |= SEC_KEEP;
12338     }
12339 }
12340
12341 /* Do mark and sweep of unused sections.  */
12342
12343 bfd_boolean
12344 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12345 {
12346   bfd_boolean ok = TRUE;
12347   bfd *sub;
12348   elf_gc_mark_hook_fn gc_mark_hook;
12349   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12350   struct elf_link_hash_table *htab;
12351
12352   if (!bed->can_gc_sections
12353       || !is_elf_hash_table (info->hash))
12354     {
12355       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12356       return TRUE;
12357     }
12358
12359   bed->gc_keep (info);
12360   htab = elf_hash_table (info);
12361
12362   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12363      at the .eh_frame section if we can mark the FDEs individually.  */
12364   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12365     {
12366       asection *sec;
12367       struct elf_reloc_cookie cookie;
12368
12369       sec = bfd_get_section_by_name (sub, ".eh_frame");
12370       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12371         {
12372           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12373           if (elf_section_data (sec)->sec_info
12374               && (sec->flags & SEC_LINKER_CREATED) == 0)
12375             elf_eh_frame_section (sub) = sec;
12376           fini_reloc_cookie_for_section (&cookie, sec);
12377           sec = bfd_get_next_section_by_name (sec);
12378         }
12379     }
12380
12381   /* Apply transitive closure to the vtable entry usage info.  */
12382   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12383   if (!ok)
12384     return FALSE;
12385
12386   /* Kill the vtable relocations that were not used.  */
12387   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12388   if (!ok)
12389     return FALSE;
12390
12391   /* Mark dynamically referenced symbols.  */
12392   if (htab->dynamic_sections_created)
12393     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12394
12395   /* Grovel through relocs to find out who stays ...  */
12396   gc_mark_hook = bed->gc_mark_hook;
12397   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12398     {
12399       asection *o;
12400
12401       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12402         continue;
12403
12404       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12405          Also treat note sections as a root, if the section is not part
12406          of a group.  */
12407       for (o = sub->sections; o != NULL; o = o->next)
12408         if (!o->gc_mark
12409             && (o->flags & SEC_EXCLUDE) == 0
12410             && ((o->flags & SEC_KEEP) != 0
12411                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12412                     && elf_next_in_group (o) == NULL )))
12413           {
12414             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12415               return FALSE;
12416           }
12417     }
12418
12419   /* Allow the backend to mark additional target specific sections.  */
12420   bed->gc_mark_extra_sections (info, gc_mark_hook);
12421
12422   /* ... and mark SEC_EXCLUDE for those that go.  */
12423   return elf_gc_sweep (abfd, info);
12424 }
12425 \f
12426 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12427
12428 bfd_boolean
12429 bfd_elf_gc_record_vtinherit (bfd *abfd,
12430                              asection *sec,
12431                              struct elf_link_hash_entry *h,
12432                              bfd_vma offset)
12433 {
12434   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12435   struct elf_link_hash_entry **search, *child;
12436   bfd_size_type extsymcount;
12437   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12438
12439   /* The sh_info field of the symtab header tells us where the
12440      external symbols start.  We don't care about the local symbols at
12441      this point.  */
12442   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12443   if (!elf_bad_symtab (abfd))
12444     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12445
12446   sym_hashes = elf_sym_hashes (abfd);
12447   sym_hashes_end = sym_hashes + extsymcount;
12448
12449   /* Hunt down the child symbol, which is in this section at the same
12450      offset as the relocation.  */
12451   for (search = sym_hashes; search != sym_hashes_end; ++search)
12452     {
12453       if ((child = *search) != NULL
12454           && (child->root.type == bfd_link_hash_defined
12455               || child->root.type == bfd_link_hash_defweak)
12456           && child->root.u.def.section == sec
12457           && child->root.u.def.value == offset)
12458         goto win;
12459     }
12460
12461   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12462                          abfd, sec, (unsigned long) offset);
12463   bfd_set_error (bfd_error_invalid_operation);
12464   return FALSE;
12465
12466  win:
12467   if (!child->vtable)
12468     {
12469       child->vtable = (struct elf_link_virtual_table_entry *)
12470           bfd_zalloc (abfd, sizeof (*child->vtable));
12471       if (!child->vtable)
12472         return FALSE;
12473     }
12474   if (!h)
12475     {
12476       /* This *should* only be the absolute section.  It could potentially
12477          be that someone has defined a non-global vtable though, which
12478          would be bad.  It isn't worth paging in the local symbols to be
12479          sure though; that case should simply be handled by the assembler.  */
12480
12481       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12482     }
12483   else
12484     child->vtable->parent = h;
12485
12486   return TRUE;
12487 }
12488
12489 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12490
12491 bfd_boolean
12492 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12493                            asection *sec ATTRIBUTE_UNUSED,
12494                            struct elf_link_hash_entry *h,
12495                            bfd_vma addend)
12496 {
12497   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12498   unsigned int log_file_align = bed->s->log_file_align;
12499
12500   if (!h->vtable)
12501     {
12502       h->vtable = (struct elf_link_virtual_table_entry *)
12503           bfd_zalloc (abfd, sizeof (*h->vtable));
12504       if (!h->vtable)
12505         return FALSE;
12506     }
12507
12508   if (addend >= h->vtable->size)
12509     {
12510       size_t size, bytes, file_align;
12511       bfd_boolean *ptr = h->vtable->used;
12512
12513       /* While the symbol is undefined, we have to be prepared to handle
12514          a zero size.  */
12515       file_align = 1 << log_file_align;
12516       if (h->root.type == bfd_link_hash_undefined)
12517         size = addend + file_align;
12518       else
12519         {
12520           size = h->size;
12521           if (addend >= size)
12522             {
12523               /* Oops!  We've got a reference past the defined end of
12524                  the table.  This is probably a bug -- shall we warn?  */
12525               size = addend + file_align;
12526             }
12527         }
12528       size = (size + file_align - 1) & -file_align;
12529
12530       /* Allocate one extra entry for use as a "done" flag for the
12531          consolidation pass.  */
12532       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12533
12534       if (ptr)
12535         {
12536           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12537
12538           if (ptr != NULL)
12539             {
12540               size_t oldbytes;
12541
12542               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12543                           * sizeof (bfd_boolean));
12544               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12545             }
12546         }
12547       else
12548         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12549
12550       if (ptr == NULL)
12551         return FALSE;
12552
12553       /* And arrange for that done flag to be at index -1.  */
12554       h->vtable->used = ptr + 1;
12555       h->vtable->size = size;
12556     }
12557
12558   h->vtable->used[addend >> log_file_align] = TRUE;
12559
12560   return TRUE;
12561 }
12562
12563 /* Map an ELF section header flag to its corresponding string.  */
12564 typedef struct
12565 {
12566   char *flag_name;
12567   flagword flag_value;
12568 } elf_flags_to_name_table;
12569
12570 static elf_flags_to_name_table elf_flags_to_names [] =
12571 {
12572   { "SHF_WRITE", SHF_WRITE },
12573   { "SHF_ALLOC", SHF_ALLOC },
12574   { "SHF_EXECINSTR", SHF_EXECINSTR },
12575   { "SHF_MERGE", SHF_MERGE },
12576   { "SHF_STRINGS", SHF_STRINGS },
12577   { "SHF_INFO_LINK", SHF_INFO_LINK},
12578   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12579   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12580   { "SHF_GROUP", SHF_GROUP },
12581   { "SHF_TLS", SHF_TLS },
12582   { "SHF_MASKOS", SHF_MASKOS },
12583   { "SHF_EXCLUDE", SHF_EXCLUDE },
12584 };
12585
12586 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
12587 bfd_boolean
12588 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12589                               struct flag_info *flaginfo,
12590                               asection *section)
12591 {
12592   const bfd_vma sh_flags = elf_section_flags (section);
12593
12594   if (!flaginfo->flags_initialized)
12595     {
12596       bfd *obfd = info->output_bfd;
12597       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12598       struct flag_info_list *tf = flaginfo->flag_list;
12599       int with_hex = 0;
12600       int without_hex = 0;
12601
12602       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
12603         {
12604           unsigned i;
12605           flagword (*lookup) (char *);
12606
12607           lookup = bed->elf_backend_lookup_section_flags_hook;
12608           if (lookup != NULL)
12609             {
12610               flagword hexval = (*lookup) ((char *) tf->name);
12611
12612               if (hexval != 0)
12613                 {
12614                   if (tf->with == with_flags)
12615                     with_hex |= hexval;
12616                   else if (tf->with == without_flags)
12617                     without_hex |= hexval;
12618                   tf->valid = TRUE;
12619                   continue;
12620                 }
12621             }
12622           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
12623             {
12624               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
12625                 {
12626                   if (tf->with == with_flags)
12627                     with_hex |= elf_flags_to_names[i].flag_value;
12628                   else if (tf->with == without_flags)
12629                     without_hex |= elf_flags_to_names[i].flag_value;
12630                   tf->valid = TRUE;
12631                   break;
12632                 }
12633             }
12634           if (!tf->valid)
12635             {
12636               info->callbacks->einfo
12637                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12638               return FALSE;
12639             }
12640         }
12641       flaginfo->flags_initialized = TRUE;
12642       flaginfo->only_with_flags |= with_hex;
12643       flaginfo->not_with_flags |= without_hex;
12644     }
12645
12646   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
12647     return FALSE;
12648
12649   if ((flaginfo->not_with_flags & sh_flags) != 0)
12650     return FALSE;
12651
12652   return TRUE;
12653 }
12654
12655 struct alloc_got_off_arg {
12656   bfd_vma gotoff;
12657   struct bfd_link_info *info;
12658 };
12659
12660 /* We need a special top-level link routine to convert got reference counts
12661    to real got offsets.  */
12662
12663 static bfd_boolean
12664 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12665 {
12666   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12667   bfd *obfd = gofarg->info->output_bfd;
12668   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12669
12670   if (h->got.refcount > 0)
12671     {
12672       h->got.offset = gofarg->gotoff;
12673       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12674     }
12675   else
12676     h->got.offset = (bfd_vma) -1;
12677
12678   return TRUE;
12679 }
12680
12681 /* And an accompanying bit to work out final got entry offsets once
12682    we're done.  Should be called from final_link.  */
12683
12684 bfd_boolean
12685 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12686                                         struct bfd_link_info *info)
12687 {
12688   bfd *i;
12689   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12690   bfd_vma gotoff;
12691   struct alloc_got_off_arg gofarg;
12692
12693   BFD_ASSERT (abfd == info->output_bfd);
12694
12695   if (! is_elf_hash_table (info->hash))
12696     return FALSE;
12697
12698   /* The GOT offset is relative to the .got section, but the GOT header is
12699      put into the .got.plt section, if the backend uses it.  */
12700   if (bed->want_got_plt)
12701     gotoff = 0;
12702   else
12703     gotoff = bed->got_header_size;
12704
12705   /* Do the local .got entries first.  */
12706   for (i = info->input_bfds; i; i = i->link.next)
12707     {
12708       bfd_signed_vma *local_got;
12709       bfd_size_type j, locsymcount;
12710       Elf_Internal_Shdr *symtab_hdr;
12711
12712       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
12713         continue;
12714
12715       local_got = elf_local_got_refcounts (i);
12716       if (!local_got)
12717         continue;
12718
12719       symtab_hdr = &elf_tdata (i)->symtab_hdr;
12720       if (elf_bad_symtab (i))
12721         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12722       else
12723         locsymcount = symtab_hdr->sh_info;
12724
12725       for (j = 0; j < locsymcount; ++j)
12726         {
12727           if (local_got[j] > 0)
12728             {
12729               local_got[j] = gotoff;
12730               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
12731             }
12732           else
12733             local_got[j] = (bfd_vma) -1;
12734         }
12735     }
12736
12737   /* Then the global .got entries.  .plt refcounts are handled by
12738      adjust_dynamic_symbol  */
12739   gofarg.gotoff = gotoff;
12740   gofarg.info = info;
12741   elf_link_hash_traverse (elf_hash_table (info),
12742                           elf_gc_allocate_got_offsets,
12743                           &gofarg);
12744   return TRUE;
12745 }
12746
12747 /* Many folk need no more in the way of final link than this, once
12748    got entry reference counting is enabled.  */
12749
12750 bfd_boolean
12751 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
12752 {
12753   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
12754     return FALSE;
12755
12756   /* Invoke the regular ELF backend linker to do all the work.  */
12757   return bfd_elf_final_link (abfd, info);
12758 }
12759
12760 bfd_boolean
12761 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
12762 {
12763   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
12764
12765   if (rcookie->bad_symtab)
12766     rcookie->rel = rcookie->rels;
12767
12768   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
12769     {
12770       unsigned long r_symndx;
12771
12772       if (! rcookie->bad_symtab)
12773         if (rcookie->rel->r_offset > offset)
12774           return FALSE;
12775       if (rcookie->rel->r_offset != offset)
12776         continue;
12777
12778       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
12779       if (r_symndx == STN_UNDEF)
12780         return TRUE;
12781
12782       if (r_symndx >= rcookie->locsymcount
12783           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12784         {
12785           struct elf_link_hash_entry *h;
12786
12787           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
12788
12789           while (h->root.type == bfd_link_hash_indirect
12790                  || h->root.type == bfd_link_hash_warning)
12791             h = (struct elf_link_hash_entry *) h->root.u.i.link;
12792
12793           if ((h->root.type == bfd_link_hash_defined
12794                || h->root.type == bfd_link_hash_defweak)
12795               && (h->root.u.def.section->owner != rcookie->abfd
12796                   || h->root.u.def.section->kept_section != NULL
12797                   || discarded_section (h->root.u.def.section)))
12798             return TRUE;
12799         }
12800       else
12801         {
12802           /* It's not a relocation against a global symbol,
12803              but it could be a relocation against a local
12804              symbol for a discarded section.  */
12805           asection *isec;
12806           Elf_Internal_Sym *isym;
12807
12808           /* Need to: get the symbol; get the section.  */
12809           isym = &rcookie->locsyms[r_symndx];
12810           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
12811           if (isec != NULL
12812               && (isec->kept_section != NULL
12813                   || discarded_section (isec)))
12814             return TRUE;
12815         }
12816       return FALSE;
12817     }
12818   return FALSE;
12819 }
12820
12821 /* Discard unneeded references to discarded sections.
12822    Returns -1 on error, 1 if any section's size was changed, 0 if
12823    nothing changed.  This function assumes that the relocations are in
12824    sorted order, which is true for all known assemblers.  */
12825
12826 int
12827 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
12828 {
12829   struct elf_reloc_cookie cookie;
12830   asection *o;
12831   bfd *abfd;
12832   int changed = 0;
12833
12834   if (info->traditional_format
12835       || !is_elf_hash_table (info->hash))
12836     return 0;
12837
12838   o = bfd_get_section_by_name (output_bfd, ".stab");
12839   if (o != NULL)
12840     {
12841       asection *i;
12842
12843       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
12844         {
12845           if (i->size == 0
12846               || i->reloc_count == 0
12847               || i->sec_info_type != SEC_INFO_TYPE_STABS)
12848             continue;
12849
12850           abfd = i->owner;
12851           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12852             continue;
12853
12854           if (!init_reloc_cookie_for_section (&cookie, info, i))
12855             return -1;
12856
12857           if (_bfd_discard_section_stabs (abfd, i,
12858                                           elf_section_data (i)->sec_info,
12859                                           bfd_elf_reloc_symbol_deleted_p,
12860                                           &cookie))
12861             changed = 1;
12862
12863           fini_reloc_cookie_for_section (&cookie, i);
12864         }
12865     }
12866
12867   o = bfd_get_section_by_name (output_bfd, ".eh_frame");
12868   if (o != NULL)
12869     {
12870       asection *i;
12871
12872       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
12873         {
12874           if (i->size == 0)
12875             continue;
12876
12877           abfd = i->owner;
12878           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12879             continue;
12880
12881           if (!init_reloc_cookie_for_section (&cookie, info, i))
12882             return -1;
12883
12884           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
12885           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
12886                                                  bfd_elf_reloc_symbol_deleted_p,
12887                                                  &cookie))
12888             changed = 1;
12889
12890           fini_reloc_cookie_for_section (&cookie, i);
12891         }
12892     }
12893
12894   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
12895     {
12896       const struct elf_backend_data *bed;
12897
12898       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12899         continue;
12900
12901       bed = get_elf_backend_data (abfd);
12902
12903       if (bed->elf_backend_discard_info != NULL)
12904         {
12905           if (!init_reloc_cookie (&cookie, info, abfd))
12906             return -1;
12907
12908           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
12909             changed = 1;
12910
12911           fini_reloc_cookie (&cookie, abfd);
12912         }
12913     }
12914
12915   if (info->eh_frame_hdr
12916       && !info->relocatable
12917       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
12918     changed = 1;
12919
12920   return changed;
12921 }
12922
12923 bfd_boolean
12924 _bfd_elf_section_already_linked (bfd *abfd,
12925                                  asection *sec,
12926                                  struct bfd_link_info *info)
12927 {
12928   flagword flags;
12929   const char *name, *key;
12930   struct bfd_section_already_linked *l;
12931   struct bfd_section_already_linked_hash_entry *already_linked_list;
12932
12933   if (sec->output_section == bfd_abs_section_ptr)
12934     return FALSE;
12935
12936   flags = sec->flags;
12937
12938   /* Return if it isn't a linkonce section.  A comdat group section
12939      also has SEC_LINK_ONCE set.  */
12940   if ((flags & SEC_LINK_ONCE) == 0)
12941     return FALSE;
12942
12943   /* Don't put group member sections on our list of already linked
12944      sections.  They are handled as a group via their group section.  */
12945   if (elf_sec_group (sec) != NULL)
12946     return FALSE;
12947
12948   /* For a SHT_GROUP section, use the group signature as the key.  */
12949   name = sec->name;
12950   if ((flags & SEC_GROUP) != 0
12951       && elf_next_in_group (sec) != NULL
12952       && elf_group_name (elf_next_in_group (sec)) != NULL)
12953     key = elf_group_name (elf_next_in_group (sec));
12954   else
12955     {
12956       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
12957       if (CONST_STRNEQ (name, ".gnu.linkonce.")
12958           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
12959         key++;
12960       else
12961         /* Must be a user linkonce section that doesn't follow gcc's
12962            naming convention.  In this case we won't be matching
12963            single member groups.  */
12964         key = name;
12965     }
12966
12967   already_linked_list = bfd_section_already_linked_table_lookup (key);
12968
12969   for (l = already_linked_list->entry; l != NULL; l = l->next)
12970     {
12971       /* We may have 2 different types of sections on the list: group
12972          sections with a signature of <key> (<key> is some string),
12973          and linkonce sections named .gnu.linkonce.<type>.<key>.
12974          Match like sections.  LTO plugin sections are an exception.
12975          They are always named .gnu.linkonce.t.<key> and match either
12976          type of section.  */
12977       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
12978            && ((flags & SEC_GROUP) != 0
12979                || strcmp (name, l->sec->name) == 0))
12980           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
12981         {
12982           /* The section has already been linked.  See if we should
12983              issue a warning.  */
12984           if (!_bfd_handle_already_linked (sec, l, info))
12985             return FALSE;
12986
12987           if (flags & SEC_GROUP)
12988             {
12989               asection *first = elf_next_in_group (sec);
12990               asection *s = first;
12991
12992               while (s != NULL)
12993                 {
12994                   s->output_section = bfd_abs_section_ptr;
12995                   /* Record which group discards it.  */
12996                   s->kept_section = l->sec;
12997                   s = elf_next_in_group (s);
12998                   /* These lists are circular.  */
12999                   if (s == first)
13000                     break;
13001                 }
13002             }
13003
13004           return TRUE;
13005         }
13006     }
13007
13008   /* A single member comdat group section may be discarded by a
13009      linkonce section and vice versa.  */
13010   if ((flags & SEC_GROUP) != 0)
13011     {
13012       asection *first = elf_next_in_group (sec);
13013
13014       if (first != NULL && elf_next_in_group (first) == first)
13015         /* Check this single member group against linkonce sections.  */
13016         for (l = already_linked_list->entry; l != NULL; l = l->next)
13017           if ((l->sec->flags & SEC_GROUP) == 0
13018               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13019             {
13020               first->output_section = bfd_abs_section_ptr;
13021               first->kept_section = l->sec;
13022               sec->output_section = bfd_abs_section_ptr;
13023               break;
13024             }
13025     }
13026   else
13027     /* Check this linkonce section against single member groups.  */
13028     for (l = already_linked_list->entry; l != NULL; l = l->next)
13029       if (l->sec->flags & SEC_GROUP)
13030         {
13031           asection *first = elf_next_in_group (l->sec);
13032
13033           if (first != NULL
13034               && elf_next_in_group (first) == first
13035               && bfd_elf_match_symbols_in_sections (first, sec, info))
13036             {
13037               sec->output_section = bfd_abs_section_ptr;
13038               sec->kept_section = first;
13039               break;
13040             }
13041         }
13042
13043   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13044      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13045      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13046      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13047      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13048      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13049      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13050      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13051      The reverse order cannot happen as there is never a bfd with only the
13052      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13053      matter as here were are looking only for cross-bfd sections.  */
13054
13055   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13056     for (l = already_linked_list->entry; l != NULL; l = l->next)
13057       if ((l->sec->flags & SEC_GROUP) == 0
13058           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13059         {
13060           if (abfd != l->sec->owner)
13061             sec->output_section = bfd_abs_section_ptr;
13062           break;
13063         }
13064
13065   /* This is the first section with this name.  Record it.  */
13066   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13067     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13068   return sec->output_section == bfd_abs_section_ptr;
13069 }
13070
13071 bfd_boolean
13072 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13073 {
13074   return sym->st_shndx == SHN_COMMON;
13075 }
13076
13077 unsigned int
13078 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13079 {
13080   return SHN_COMMON;
13081 }
13082
13083 asection *
13084 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13085 {
13086   return bfd_com_section_ptr;
13087 }
13088
13089 bfd_vma
13090 _bfd_elf_default_got_elt_size (bfd *abfd,
13091                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13092                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13093                                bfd *ibfd ATTRIBUTE_UNUSED,
13094                                unsigned long symndx ATTRIBUTE_UNUSED)
13095 {
13096   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13097   return bed->s->arch_size / 8;
13098 }
13099
13100 /* Routines to support the creation of dynamic relocs.  */
13101
13102 /* Returns the name of the dynamic reloc section associated with SEC.  */
13103
13104 static const char *
13105 get_dynamic_reloc_section_name (bfd *       abfd,
13106                                 asection *  sec,
13107                                 bfd_boolean is_rela)
13108 {
13109   char *name;
13110   const char *old_name = bfd_get_section_name (NULL, sec);
13111   const char *prefix = is_rela ? ".rela" : ".rel";
13112
13113   if (old_name == NULL)
13114     return NULL;
13115
13116   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13117   sprintf (name, "%s%s", prefix, old_name);
13118
13119   return name;
13120 }
13121
13122 /* Returns the dynamic reloc section associated with SEC.
13123    If necessary compute the name of the dynamic reloc section based
13124    on SEC's name (looked up in ABFD's string table) and the setting
13125    of IS_RELA.  */
13126
13127 asection *
13128 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13129                                     asection *  sec,
13130                                     bfd_boolean is_rela)
13131 {
13132   asection * reloc_sec = elf_section_data (sec)->sreloc;
13133
13134   if (reloc_sec == NULL)
13135     {
13136       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13137
13138       if (name != NULL)
13139         {
13140           reloc_sec = bfd_get_linker_section (abfd, name);
13141
13142           if (reloc_sec != NULL)
13143             elf_section_data (sec)->sreloc = reloc_sec;
13144         }
13145     }
13146
13147   return reloc_sec;
13148 }
13149
13150 /* Returns the dynamic reloc section associated with SEC.  If the
13151    section does not exist it is created and attached to the DYNOBJ
13152    bfd and stored in the SRELOC field of SEC's elf_section_data
13153    structure.
13154
13155    ALIGNMENT is the alignment for the newly created section and
13156    IS_RELA defines whether the name should be .rela.<SEC's name>
13157    or .rel.<SEC's name>.  The section name is looked up in the
13158    string table associated with ABFD.  */
13159
13160 asection *
13161 _bfd_elf_make_dynamic_reloc_section (asection *         sec,
13162                                      bfd *              dynobj,
13163                                      unsigned int       alignment,
13164                                      bfd *              abfd,
13165                                      bfd_boolean        is_rela)
13166 {
13167   asection * reloc_sec = elf_section_data (sec)->sreloc;
13168
13169   if (reloc_sec == NULL)
13170     {
13171       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13172
13173       if (name == NULL)
13174         return NULL;
13175
13176       reloc_sec = bfd_get_linker_section (dynobj, name);
13177
13178       if (reloc_sec == NULL)
13179         {
13180           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13181                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13182           if ((sec->flags & SEC_ALLOC) != 0)
13183             flags |= SEC_ALLOC | SEC_LOAD;
13184
13185           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13186           if (reloc_sec != NULL)
13187             {
13188               /* _bfd_elf_get_sec_type_attr chooses a section type by
13189                  name.  Override as it may be wrong, eg. for a user
13190                  section named "auto" we'll get ".relauto" which is
13191                  seen to be a .rela section.  */
13192               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13193               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13194                 reloc_sec = NULL;
13195             }
13196         }
13197
13198       elf_section_data (sec)->sreloc = reloc_sec;
13199     }
13200
13201   return reloc_sec;
13202 }
13203
13204 /* Copy the ELF symbol type and other attributes for a linker script
13205    assignment from HSRC to HDEST.  Generally this should be treated as
13206    if we found a strong non-dynamic definition for HDEST (except that
13207    ld ignores multiple definition errors).  */
13208 void
13209 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13210                                      struct bfd_link_hash_entry *hdest,
13211                                      struct bfd_link_hash_entry *hsrc)
13212 {
13213   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13214   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13215   Elf_Internal_Sym isym;
13216
13217   ehdest->type = ehsrc->type;
13218   ehdest->target_internal = ehsrc->target_internal;
13219
13220   isym.st_other = ehsrc->other;
13221   elf_merge_st_other (abfd, ehdest, &isym, TRUE, FALSE);
13222 }
13223
13224 /* Append a RELA relocation REL to section S in BFD.  */
13225
13226 void
13227 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13228 {
13229   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13230   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13231   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13232   bed->s->swap_reloca_out (abfd, rel, loc);
13233 }
13234
13235 /* Append a REL relocation REL to section S in BFD.  */
13236
13237 void
13238 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13239 {
13240   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13241   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13242   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13243   bed->s->swap_reloc_out (abfd, rel, loc);
13244 }