Properly merge hidden versioned symbol
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2015 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 asection *
58 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
59                              unsigned long r_symndx,
60                              bfd_boolean discard)
61 {
62   if (r_symndx >= cookie->locsymcount
63       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
64     {
65       struct elf_link_hash_entry *h;
66
67       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
68
69       while (h->root.type == bfd_link_hash_indirect
70              || h->root.type == bfd_link_hash_warning)
71         h = (struct elf_link_hash_entry *) h->root.u.i.link;
72
73       if ((h->root.type == bfd_link_hash_defined
74            || h->root.type == bfd_link_hash_defweak)
75            && discarded_section (h->root.u.def.section))
76         return h->root.u.def.section;
77       else
78         return NULL;
79     }
80   else
81     {
82       /* It's not a relocation against a global symbol,
83          but it could be a relocation against a local
84          symbol for a discarded section.  */
85       asection *isec;
86       Elf_Internal_Sym *isym;
87
88       /* Need to: get the symbol; get the section.  */
89       isym = &cookie->locsyms[r_symndx];
90       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
91       if (isec != NULL
92           && discard ? discarded_section (isec) : 1)
93         return isec;
94      }
95   return NULL;
96 }
97
98 /* Define a symbol in a dynamic linkage section.  */
99
100 struct elf_link_hash_entry *
101 _bfd_elf_define_linkage_sym (bfd *abfd,
102                              struct bfd_link_info *info,
103                              asection *sec,
104                              const char *name)
105 {
106   struct elf_link_hash_entry *h;
107   struct bfd_link_hash_entry *bh;
108   const struct elf_backend_data *bed;
109
110   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
111   if (h != NULL)
112     {
113       /* Zap symbol defined in an as-needed lib that wasn't linked.
114          This is a symptom of a larger problem:  Absolute symbols
115          defined in shared libraries can't be overridden, because we
116          lose the link to the bfd which is via the symbol section.  */
117       h->root.type = bfd_link_hash_new;
118     }
119
120   bh = &h->root;
121   bed = get_elf_backend_data (abfd);
122   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
123                                          sec, 0, NULL, FALSE, bed->collect,
124                                          &bh))
125     return NULL;
126   h = (struct elf_link_hash_entry *) bh;
127   h->def_regular = 1;
128   h->non_elf = 0;
129   h->root.linker_def = 1;
130   h->type = STT_OBJECT;
131   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
132     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
133
134   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
135   return h;
136 }
137
138 bfd_boolean
139 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
140 {
141   flagword flags;
142   asection *s;
143   struct elf_link_hash_entry *h;
144   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
145   struct elf_link_hash_table *htab = elf_hash_table (info);
146
147   /* This function may be called more than once.  */
148   s = bfd_get_linker_section (abfd, ".got");
149   if (s != NULL)
150     return TRUE;
151
152   flags = bed->dynamic_sec_flags;
153
154   s = bfd_make_section_anyway_with_flags (abfd,
155                                           (bed->rela_plts_and_copies_p
156                                            ? ".rela.got" : ".rel.got"),
157                                           (bed->dynamic_sec_flags
158                                            | SEC_READONLY));
159   if (s == NULL
160       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
161     return FALSE;
162   htab->srelgot = s;
163
164   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
165   if (s == NULL
166       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->sgot = s;
169
170   if (bed->want_got_plt)
171     {
172       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
173       if (s == NULL
174           || !bfd_set_section_alignment (abfd, s,
175                                          bed->s->log_file_align))
176         return FALSE;
177       htab->sgotplt = s;
178     }
179
180   /* The first bit of the global offset table is the header.  */
181   s->size += bed->got_header_size;
182
183   if (bed->want_got_sym)
184     {
185       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
186          (or .got.plt) section.  We don't do this in the linker script
187          because we don't want to define the symbol if we are not creating
188          a global offset table.  */
189       h = _bfd_elf_define_linkage_sym (abfd, info, s,
190                                        "_GLOBAL_OFFSET_TABLE_");
191       elf_hash_table (info)->hgot = h;
192       if (h == NULL)
193         return FALSE;
194     }
195
196   return TRUE;
197 }
198 \f
199 /* Create a strtab to hold the dynamic symbol names.  */
200 static bfd_boolean
201 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
202 {
203   struct elf_link_hash_table *hash_table;
204
205   hash_table = elf_hash_table (info);
206   if (hash_table->dynobj == NULL)
207     hash_table->dynobj = abfd;
208
209   if (hash_table->dynstr == NULL)
210     {
211       hash_table->dynstr = _bfd_elf_strtab_init ();
212       if (hash_table->dynstr == NULL)
213         return FALSE;
214     }
215   return TRUE;
216 }
217
218 /* Create some sections which will be filled in with dynamic linking
219    information.  ABFD is an input file which requires dynamic sections
220    to be created.  The dynamic sections take up virtual memory space
221    when the final executable is run, so we need to create them before
222    addresses are assigned to the output sections.  We work out the
223    actual contents and size of these sections later.  */
224
225 bfd_boolean
226 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
227 {
228   flagword flags;
229   asection *s;
230   const struct elf_backend_data *bed;
231   struct elf_link_hash_entry *h;
232
233   if (! is_elf_hash_table (info->hash))
234     return FALSE;
235
236   if (elf_hash_table (info)->dynamic_sections_created)
237     return TRUE;
238
239   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
240     return FALSE;
241
242   abfd = elf_hash_table (info)->dynobj;
243   bed = get_elf_backend_data (abfd);
244
245   flags = bed->dynamic_sec_flags;
246
247   /* A dynamically linked executable has a .interp section, but a
248      shared library does not.  */
249   if (info->executable)
250     {
251       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
252                                               flags | SEC_READONLY);
253       if (s == NULL)
254         return FALSE;
255     }
256
257   /* Create sections to hold version informations.  These are removed
258      if they are not needed.  */
259   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
260                                           flags | SEC_READONLY);
261   if (s == NULL
262       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
263     return FALSE;
264
265   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
266                                           flags | SEC_READONLY);
267   if (s == NULL
268       || ! bfd_set_section_alignment (abfd, s, 1))
269     return FALSE;
270
271   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
272                                           flags | SEC_READONLY);
273   if (s == NULL
274       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
275     return FALSE;
276
277   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
278                                           flags | SEC_READONLY);
279   if (s == NULL
280       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
281     return FALSE;
282
283   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
284                                           flags | SEC_READONLY);
285   if (s == NULL)
286     return FALSE;
287
288   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
289   if (s == NULL
290       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
291     return FALSE;
292
293   /* The special symbol _DYNAMIC is always set to the start of the
294      .dynamic section.  We could set _DYNAMIC in a linker script, but we
295      only want to define it if we are, in fact, creating a .dynamic
296      section.  We don't want to define it if there is no .dynamic
297      section, since on some ELF platforms the start up code examines it
298      to decide how to initialize the process.  */
299   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
300   elf_hash_table (info)->hdynamic = h;
301   if (h == NULL)
302     return FALSE;
303
304   if (info->emit_hash)
305     {
306       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
307                                               flags | SEC_READONLY);
308       if (s == NULL
309           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
310         return FALSE;
311       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
312     }
313
314   if (info->emit_gnu_hash)
315     {
316       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
317                                               flags | SEC_READONLY);
318       if (s == NULL
319           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
320         return FALSE;
321       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
322          4 32-bit words followed by variable count of 64-bit words, then
323          variable count of 32-bit words.  */
324       if (bed->s->arch_size == 64)
325         elf_section_data (s)->this_hdr.sh_entsize = 0;
326       else
327         elf_section_data (s)->this_hdr.sh_entsize = 4;
328     }
329
330   /* Let the backend create the rest of the sections.  This lets the
331      backend set the right flags.  The backend will normally create
332      the .got and .plt sections.  */
333   if (bed->elf_backend_create_dynamic_sections == NULL
334       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
335     return FALSE;
336
337   elf_hash_table (info)->dynamic_sections_created = TRUE;
338
339   return TRUE;
340 }
341
342 /* Create dynamic sections when linking against a dynamic object.  */
343
344 bfd_boolean
345 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
346 {
347   flagword flags, pltflags;
348   struct elf_link_hash_entry *h;
349   asection *s;
350   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
351   struct elf_link_hash_table *htab = elf_hash_table (info);
352
353   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
354      .rel[a].bss sections.  */
355   flags = bed->dynamic_sec_flags;
356
357   pltflags = flags;
358   if (bed->plt_not_loaded)
359     /* We do not clear SEC_ALLOC here because we still want the OS to
360        allocate space for the section; it's just that there's nothing
361        to read in from the object file.  */
362     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
363   else
364     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
365   if (bed->plt_readonly)
366     pltflags |= SEC_READONLY;
367
368   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
369   if (s == NULL
370       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
371     return FALSE;
372   htab->splt = s;
373
374   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
375      .plt section.  */
376   if (bed->want_plt_sym)
377     {
378       h = _bfd_elf_define_linkage_sym (abfd, info, s,
379                                        "_PROCEDURE_LINKAGE_TABLE_");
380       elf_hash_table (info)->hplt = h;
381       if (h == NULL)
382         return FALSE;
383     }
384
385   s = bfd_make_section_anyway_with_flags (abfd,
386                                           (bed->rela_plts_and_copies_p
387                                            ? ".rela.plt" : ".rel.plt"),
388                                           flags | SEC_READONLY);
389   if (s == NULL
390       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
391     return FALSE;
392   htab->srelplt = s;
393
394   if (! _bfd_elf_create_got_section (abfd, info))
395     return FALSE;
396
397   if (bed->want_dynbss)
398     {
399       /* The .dynbss section is a place to put symbols which are defined
400          by dynamic objects, are referenced by regular objects, and are
401          not functions.  We must allocate space for them in the process
402          image and use a R_*_COPY reloc to tell the dynamic linker to
403          initialize them at run time.  The linker script puts the .dynbss
404          section into the .bss section of the final image.  */
405       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
406                                               (SEC_ALLOC | SEC_LINKER_CREATED));
407       if (s == NULL)
408         return FALSE;
409
410       /* The .rel[a].bss section holds copy relocs.  This section is not
411          normally needed.  We need to create it here, though, so that the
412          linker will map it to an output section.  We can't just create it
413          only if we need it, because we will not know whether we need it
414          until we have seen all the input files, and the first time the
415          main linker code calls BFD after examining all the input files
416          (size_dynamic_sections) the input sections have already been
417          mapped to the output sections.  If the section turns out not to
418          be needed, we can discard it later.  We will never need this
419          section when generating a shared object, since they do not use
420          copy relocs.  */
421       if (! info->shared)
422         {
423           s = bfd_make_section_anyway_with_flags (abfd,
424                                                   (bed->rela_plts_and_copies_p
425                                                    ? ".rela.bss" : ".rel.bss"),
426                                                   flags | SEC_READONLY);
427           if (s == NULL
428               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
429             return FALSE;
430         }
431     }
432
433   return TRUE;
434 }
435 \f
436 /* Record a new dynamic symbol.  We record the dynamic symbols as we
437    read the input files, since we need to have a list of all of them
438    before we can determine the final sizes of the output sections.
439    Note that we may actually call this function even though we are not
440    going to output any dynamic symbols; in some cases we know that a
441    symbol should be in the dynamic symbol table, but only if there is
442    one.  */
443
444 bfd_boolean
445 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
446                                     struct elf_link_hash_entry *h)
447 {
448   if (h->dynindx == -1)
449     {
450       struct elf_strtab_hash *dynstr;
451       char *p;
452       const char *name;
453       bfd_size_type indx;
454
455       /* XXX: The ABI draft says the linker must turn hidden and
456          internal symbols into STB_LOCAL symbols when producing the
457          DSO. However, if ld.so honors st_other in the dynamic table,
458          this would not be necessary.  */
459       switch (ELF_ST_VISIBILITY (h->other))
460         {
461         case STV_INTERNAL:
462         case STV_HIDDEN:
463           if (h->root.type != bfd_link_hash_undefined
464               && h->root.type != bfd_link_hash_undefweak)
465             {
466               h->forced_local = 1;
467               if (!elf_hash_table (info)->is_relocatable_executable)
468                 return TRUE;
469             }
470
471         default:
472           break;
473         }
474
475       h->dynindx = elf_hash_table (info)->dynsymcount;
476       ++elf_hash_table (info)->dynsymcount;
477
478       dynstr = elf_hash_table (info)->dynstr;
479       if (dynstr == NULL)
480         {
481           /* Create a strtab to hold the dynamic symbol names.  */
482           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
483           if (dynstr == NULL)
484             return FALSE;
485         }
486
487       /* We don't put any version information in the dynamic string
488          table.  */
489       name = h->root.root.string;
490       p = strchr (name, ELF_VER_CHR);
491       if (p != NULL)
492         /* We know that the p points into writable memory.  In fact,
493            there are only a few symbols that have read-only names, being
494            those like _GLOBAL_OFFSET_TABLE_ that are created specially
495            by the backends.  Most symbols will have names pointing into
496            an ELF string table read from a file, or to objalloc memory.  */
497         *p = 0;
498
499       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
500
501       if (p != NULL)
502         *p = ELF_VER_CHR;
503
504       if (indx == (bfd_size_type) -1)
505         return FALSE;
506       h->dynstr_index = indx;
507     }
508
509   return TRUE;
510 }
511 \f
512 /* Mark a symbol dynamic.  */
513
514 static void
515 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
516                                   struct elf_link_hash_entry *h,
517                                   Elf_Internal_Sym *sym)
518 {
519   struct bfd_elf_dynamic_list *d = info->dynamic_list;
520
521   /* It may be called more than once on the same H.  */
522   if(h->dynamic || info->relocatable)
523     return;
524
525   if ((info->dynamic_data
526        && (h->type == STT_OBJECT
527            || (sym != NULL
528                && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
529       || (d != NULL
530           && h->root.type == bfd_link_hash_new
531           && (*d->match) (&d->head, NULL, h->root.root.string)))
532     h->dynamic = 1;
533 }
534
535 /* Record an assignment to a symbol made by a linker script.  We need
536    this in case some dynamic object refers to this symbol.  */
537
538 bfd_boolean
539 bfd_elf_record_link_assignment (bfd *output_bfd,
540                                 struct bfd_link_info *info,
541                                 const char *name,
542                                 bfd_boolean provide,
543                                 bfd_boolean hidden)
544 {
545   struct elf_link_hash_entry *h, *hv;
546   struct elf_link_hash_table *htab;
547   const struct elf_backend_data *bed;
548
549   if (!is_elf_hash_table (info->hash))
550     return TRUE;
551
552   htab = elf_hash_table (info);
553   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
554   if (h == NULL)
555     return provide;
556
557   switch (h->root.type)
558     {
559     case bfd_link_hash_defined:
560     case bfd_link_hash_defweak:
561     case bfd_link_hash_common:
562       break;
563     case bfd_link_hash_undefweak:
564     case bfd_link_hash_undefined:
565       /* Since we're defining the symbol, don't let it seem to have not
566          been defined.  record_dynamic_symbol and size_dynamic_sections
567          may depend on this.  */
568       h->root.type = bfd_link_hash_new;
569       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
570         bfd_link_repair_undef_list (&htab->root);
571       break;
572     case bfd_link_hash_new:
573       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
574       h->non_elf = 0;
575       break;
576     case bfd_link_hash_indirect:
577       /* We had a versioned symbol in a dynamic library.  We make the
578          the versioned symbol point to this one.  */
579       bed = get_elf_backend_data (output_bfd);
580       hv = h;
581       while (hv->root.type == bfd_link_hash_indirect
582              || hv->root.type == bfd_link_hash_warning)
583         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
584       /* We don't need to update h->root.u since linker will set them
585          later.  */
586       h->root.type = bfd_link_hash_undefined;
587       hv->root.type = bfd_link_hash_indirect;
588       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
589       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
590       break;
591     case bfd_link_hash_warning:
592       abort ();
593       break;
594     }
595
596   /* If this symbol is being provided by the linker script, and it is
597      currently defined by a dynamic object, but not by a regular
598      object, then mark it as undefined so that the generic linker will
599      force the correct value.  */
600   if (provide
601       && h->def_dynamic
602       && !h->def_regular)
603     h->root.type = bfd_link_hash_undefined;
604
605   /* If this symbol is not being provided by the linker script, and it is
606      currently defined by a dynamic object, but not by a regular object,
607      then clear out any version information because the symbol will not be
608      associated with the dynamic object any more.  */
609   if (!provide
610       && h->def_dynamic
611       && !h->def_regular)
612     h->verinfo.verdef = NULL;
613
614   h->def_regular = 1;
615
616   if (hidden)
617     {
618       bed = get_elf_backend_data (output_bfd);
619       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
620         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
621       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
622     }
623
624   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
625      and executables.  */
626   if (!info->relocatable
627       && h->dynindx != -1
628       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
629           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
630     h->forced_local = 1;
631
632   if ((h->def_dynamic
633        || h->ref_dynamic
634        || info->shared
635        || (info->executable && elf_hash_table (info)->is_relocatable_executable))
636       && h->dynindx == -1)
637     {
638       if (! bfd_elf_link_record_dynamic_symbol (info, h))
639         return FALSE;
640
641       /* If this is a weak defined symbol, and we know a corresponding
642          real symbol from the same dynamic object, make sure the real
643          symbol is also made into a dynamic symbol.  */
644       if (h->u.weakdef != NULL
645           && h->u.weakdef->dynindx == -1)
646         {
647           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
648             return FALSE;
649         }
650     }
651
652   return TRUE;
653 }
654
655 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
656    success, and 2 on a failure caused by attempting to record a symbol
657    in a discarded section, eg. a discarded link-once section symbol.  */
658
659 int
660 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
661                                           bfd *input_bfd,
662                                           long input_indx)
663 {
664   bfd_size_type amt;
665   struct elf_link_local_dynamic_entry *entry;
666   struct elf_link_hash_table *eht;
667   struct elf_strtab_hash *dynstr;
668   unsigned long dynstr_index;
669   char *name;
670   Elf_External_Sym_Shndx eshndx;
671   char esym[sizeof (Elf64_External_Sym)];
672
673   if (! is_elf_hash_table (info->hash))
674     return 0;
675
676   /* See if the entry exists already.  */
677   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
678     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
679       return 1;
680
681   amt = sizeof (*entry);
682   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
683   if (entry == NULL)
684     return 0;
685
686   /* Go find the symbol, so that we can find it's name.  */
687   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
688                              1, input_indx, &entry->isym, esym, &eshndx))
689     {
690       bfd_release (input_bfd, entry);
691       return 0;
692     }
693
694   if (entry->isym.st_shndx != SHN_UNDEF
695       && entry->isym.st_shndx < SHN_LORESERVE)
696     {
697       asection *s;
698
699       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
700       if (s == NULL || bfd_is_abs_section (s->output_section))
701         {
702           /* We can still bfd_release here as nothing has done another
703              bfd_alloc.  We can't do this later in this function.  */
704           bfd_release (input_bfd, entry);
705           return 2;
706         }
707     }
708
709   name = (bfd_elf_string_from_elf_section
710           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
711            entry->isym.st_name));
712
713   dynstr = elf_hash_table (info)->dynstr;
714   if (dynstr == NULL)
715     {
716       /* Create a strtab to hold the dynamic symbol names.  */
717       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
718       if (dynstr == NULL)
719         return 0;
720     }
721
722   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
723   if (dynstr_index == (unsigned long) -1)
724     return 0;
725   entry->isym.st_name = dynstr_index;
726
727   eht = elf_hash_table (info);
728
729   entry->next = eht->dynlocal;
730   eht->dynlocal = entry;
731   entry->input_bfd = input_bfd;
732   entry->input_indx = input_indx;
733   eht->dynsymcount++;
734
735   /* Whatever binding the symbol had before, it's now local.  */
736   entry->isym.st_info
737     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
738
739   /* The dynindx will be set at the end of size_dynamic_sections.  */
740
741   return 1;
742 }
743
744 /* Return the dynindex of a local dynamic symbol.  */
745
746 long
747 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
748                                     bfd *input_bfd,
749                                     long input_indx)
750 {
751   struct elf_link_local_dynamic_entry *e;
752
753   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
754     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
755       return e->dynindx;
756   return -1;
757 }
758
759 /* This function is used to renumber the dynamic symbols, if some of
760    them are removed because they are marked as local.  This is called
761    via elf_link_hash_traverse.  */
762
763 static bfd_boolean
764 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
765                                       void *data)
766 {
767   size_t *count = (size_t *) data;
768
769   if (h->forced_local)
770     return TRUE;
771
772   if (h->dynindx != -1)
773     h->dynindx = ++(*count);
774
775   return TRUE;
776 }
777
778
779 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
780    STB_LOCAL binding.  */
781
782 static bfd_boolean
783 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
784                                             void *data)
785 {
786   size_t *count = (size_t *) data;
787
788   if (!h->forced_local)
789     return TRUE;
790
791   if (h->dynindx != -1)
792     h->dynindx = ++(*count);
793
794   return TRUE;
795 }
796
797 /* Return true if the dynamic symbol for a given section should be
798    omitted when creating a shared library.  */
799 bfd_boolean
800 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
801                                    struct bfd_link_info *info,
802                                    asection *p)
803 {
804   struct elf_link_hash_table *htab;
805   asection *ip;
806
807   switch (elf_section_data (p)->this_hdr.sh_type)
808     {
809     case SHT_PROGBITS:
810     case SHT_NOBITS:
811       /* If sh_type is yet undecided, assume it could be
812          SHT_PROGBITS/SHT_NOBITS.  */
813     case SHT_NULL:
814       htab = elf_hash_table (info);
815       if (p == htab->tls_sec)
816         return FALSE;
817
818       if (htab->text_index_section != NULL)
819         return p != htab->text_index_section && p != htab->data_index_section;
820
821       return (htab->dynobj != NULL
822               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
823               && ip->output_section == p);
824
825       /* There shouldn't be section relative relocations
826          against any other section.  */
827     default:
828       return TRUE;
829     }
830 }
831
832 /* Assign dynsym indices.  In a shared library we generate a section
833    symbol for each output section, which come first.  Next come symbols
834    which have been forced to local binding.  Then all of the back-end
835    allocated local dynamic syms, followed by the rest of the global
836    symbols.  */
837
838 static unsigned long
839 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
840                                 struct bfd_link_info *info,
841                                 unsigned long *section_sym_count)
842 {
843   unsigned long dynsymcount = 0;
844
845   if (info->shared || elf_hash_table (info)->is_relocatable_executable)
846     {
847       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
848       asection *p;
849       for (p = output_bfd->sections; p ; p = p->next)
850         if ((p->flags & SEC_EXCLUDE) == 0
851             && (p->flags & SEC_ALLOC) != 0
852             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
853           elf_section_data (p)->dynindx = ++dynsymcount;
854         else
855           elf_section_data (p)->dynindx = 0;
856     }
857   *section_sym_count = dynsymcount;
858
859   elf_link_hash_traverse (elf_hash_table (info),
860                           elf_link_renumber_local_hash_table_dynsyms,
861                           &dynsymcount);
862
863   if (elf_hash_table (info)->dynlocal)
864     {
865       struct elf_link_local_dynamic_entry *p;
866       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
867         p->dynindx = ++dynsymcount;
868     }
869
870   elf_link_hash_traverse (elf_hash_table (info),
871                           elf_link_renumber_hash_table_dynsyms,
872                           &dynsymcount);
873
874   /* There is an unused NULL entry at the head of the table which
875      we must account for in our count.  Unless there weren't any
876      symbols, which means we'll have no table at all.  */
877   if (dynsymcount != 0)
878     ++dynsymcount;
879
880   elf_hash_table (info)->dynsymcount = dynsymcount;
881   return dynsymcount;
882 }
883
884 /* Merge st_other field.  */
885
886 static void
887 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
888                     const Elf_Internal_Sym *isym, asection *sec,
889                     bfd_boolean definition, bfd_boolean dynamic)
890 {
891   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
892
893   /* If st_other has a processor-specific meaning, specific
894      code might be needed here.  */
895   if (bed->elf_backend_merge_symbol_attribute)
896     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
897                                                 dynamic);
898
899   if (!dynamic)
900     {
901       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
902       unsigned hvis = ELF_ST_VISIBILITY (h->other);
903
904       /* Keep the most constraining visibility.  Leave the remainder
905          of the st_other field to elf_backend_merge_symbol_attribute.  */
906       if (symvis - 1 < hvis - 1)
907         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
908     }
909   else if (definition
910            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
911            && (sec->flags & SEC_READONLY) == 0)
912     h->protected_def = 1;
913 }
914
915 /* This function is called when we want to merge a new symbol with an
916    existing symbol.  It handles the various cases which arise when we
917    find a definition in a dynamic object, or when there is already a
918    definition in a dynamic object.  The new symbol is described by
919    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
920    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
921    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
922    of an old common symbol.  We set OVERRIDE if the old symbol is
923    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
924    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
925    to change.  By OK to change, we mean that we shouldn't warn if the
926    type or size does change.  */
927
928 static bfd_boolean
929 _bfd_elf_merge_symbol (bfd *abfd,
930                        struct bfd_link_info *info,
931                        const char *name,
932                        Elf_Internal_Sym *sym,
933                        asection **psec,
934                        bfd_vma *pvalue,
935                        struct elf_link_hash_entry **sym_hash,
936                        bfd **poldbfd,
937                        bfd_boolean *pold_weak,
938                        unsigned int *pold_alignment,
939                        bfd_boolean *skip,
940                        bfd_boolean *override,
941                        bfd_boolean *type_change_ok,
942                        bfd_boolean *size_change_ok,
943                        bfd_boolean *matched)
944 {
945   asection *sec, *oldsec;
946   struct elf_link_hash_entry *h;
947   struct elf_link_hash_entry *hi;
948   struct elf_link_hash_entry *flip;
949   int bind;
950   bfd *oldbfd;
951   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
952   bfd_boolean newweak, oldweak, newfunc, oldfunc;
953   const struct elf_backend_data *bed;
954   char *new_version;
955
956   *skip = FALSE;
957   *override = FALSE;
958
959   sec = *psec;
960   bind = ELF_ST_BIND (sym->st_info);
961
962   if (! bfd_is_und_section (sec))
963     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
964   else
965     h = ((struct elf_link_hash_entry *)
966          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
967   if (h == NULL)
968     return FALSE;
969   *sym_hash = h;
970
971   bed = get_elf_backend_data (abfd);
972
973   /* NEW_VERSION is the symbol version of the new symbol.  */
974   new_version = strrchr (name, ELF_VER_CHR);
975   if (new_version)
976     {
977       if (new_version > name && new_version[-1] != ELF_VER_CHR)
978         h->hidden = 1;
979       new_version += 1;
980       if (new_version[0] == '\0')
981         new_version = NULL;
982     }
983
984   /* For merging, we only care about real symbols.  But we need to make
985      sure that indirect symbol dynamic flags are updated.  */
986   hi = h;
987   while (h->root.type == bfd_link_hash_indirect
988          || h->root.type == bfd_link_hash_warning)
989     h = (struct elf_link_hash_entry *) h->root.u.i.link;
990
991   if (!*matched)
992     {
993       if (hi == h || h->root.type == bfd_link_hash_new)
994         *matched = TRUE;
995       else
996         {
997           /* OLD_HIDDEN is true if the existing symbol is only visibile
998              to the symbol with the same symbol version.  NEW_HIDDEN is
999              true if the new symbol is only visibile to the symbol with
1000              the same symbol version.  */
1001           bfd_boolean old_hidden = h->hidden;
1002           bfd_boolean new_hidden = hi->hidden;
1003           if (!old_hidden && !new_hidden)
1004             /* The new symbol matches the existing symbol if both
1005                aren't hidden.  */
1006             *matched = TRUE;
1007           else
1008             {
1009               /* OLD_VERSION is the symbol version of the existing
1010                  symbol. */
1011               char *old_version = strrchr (h->root.root.string,
1012                                            ELF_VER_CHR);
1013               if (old_version)
1014                 {
1015                   old_version += 1;
1016                   if (old_version[0] == '\0')
1017                     old_version = NULL;
1018                 }
1019
1020               /* The new symbol matches the existing symbol if they
1021                  have the same symbol version.  */
1022               *matched = (old_version == new_version
1023                           || (old_version != NULL
1024                               && new_version != NULL
1025                               && strcmp (old_version, new_version) == 0));
1026             }
1027         }
1028     }
1029
1030   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1031      existing symbol.  */
1032
1033   oldbfd = NULL;
1034   oldsec = NULL;
1035   switch (h->root.type)
1036     {
1037     default:
1038       break;
1039
1040     case bfd_link_hash_undefined:
1041     case bfd_link_hash_undefweak:
1042       oldbfd = h->root.u.undef.abfd;
1043       break;
1044
1045     case bfd_link_hash_defined:
1046     case bfd_link_hash_defweak:
1047       oldbfd = h->root.u.def.section->owner;
1048       oldsec = h->root.u.def.section;
1049       break;
1050
1051     case bfd_link_hash_common:
1052       oldbfd = h->root.u.c.p->section->owner;
1053       oldsec = h->root.u.c.p->section;
1054       if (pold_alignment)
1055         *pold_alignment = h->root.u.c.p->alignment_power;
1056       break;
1057     }
1058   if (poldbfd && *poldbfd == NULL)
1059     *poldbfd = oldbfd;
1060
1061   /* Differentiate strong and weak symbols.  */
1062   newweak = bind == STB_WEAK;
1063   oldweak = (h->root.type == bfd_link_hash_defweak
1064              || h->root.type == bfd_link_hash_undefweak);
1065   if (pold_weak)
1066     *pold_weak = oldweak;
1067
1068   /* This code is for coping with dynamic objects, and is only useful
1069      if we are doing an ELF link.  */
1070   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1071     return TRUE;
1072
1073   /* We have to check it for every instance since the first few may be
1074      references and not all compilers emit symbol type for undefined
1075      symbols.  */
1076   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1077
1078   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1079      respectively, is from a dynamic object.  */
1080
1081   newdyn = (abfd->flags & DYNAMIC) != 0;
1082
1083   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1084      syms and defined syms in dynamic libraries respectively.
1085      ref_dynamic on the other hand can be set for a symbol defined in
1086      a dynamic library, and def_dynamic may not be set;  When the
1087      definition in a dynamic lib is overridden by a definition in the
1088      executable use of the symbol in the dynamic lib becomes a
1089      reference to the executable symbol.  */
1090   if (newdyn)
1091     {
1092       if (bfd_is_und_section (sec))
1093         {
1094           if (bind != STB_WEAK)
1095             {
1096               h->ref_dynamic_nonweak = 1;
1097               hi->ref_dynamic_nonweak = 1;
1098             }
1099         }
1100       else
1101         {
1102           /* Update the existing symbol only if they match. */
1103           if (*matched)
1104             h->dynamic_def = 1;
1105           hi->dynamic_def = 1;
1106         }
1107     }
1108
1109   /* If we just created the symbol, mark it as being an ELF symbol.
1110      Other than that, there is nothing to do--there is no merge issue
1111      with a newly defined symbol--so we just return.  */
1112
1113   if (h->root.type == bfd_link_hash_new)
1114     {
1115       h->non_elf = 0;
1116       return TRUE;
1117     }
1118
1119   /* In cases involving weak versioned symbols, we may wind up trying
1120      to merge a symbol with itself.  Catch that here, to avoid the
1121      confusion that results if we try to override a symbol with
1122      itself.  The additional tests catch cases like
1123      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1124      dynamic object, which we do want to handle here.  */
1125   if (abfd == oldbfd
1126       && (newweak || oldweak)
1127       && ((abfd->flags & DYNAMIC) == 0
1128           || !h->def_regular))
1129     return TRUE;
1130
1131   olddyn = FALSE;
1132   if (oldbfd != NULL)
1133     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1134   else if (oldsec != NULL)
1135     {
1136       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1137          indices used by MIPS ELF.  */
1138       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1139     }
1140
1141   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1142      respectively, appear to be a definition rather than reference.  */
1143
1144   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1145
1146   olddef = (h->root.type != bfd_link_hash_undefined
1147             && h->root.type != bfd_link_hash_undefweak
1148             && h->root.type != bfd_link_hash_common);
1149
1150   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1151      respectively, appear to be a function.  */
1152
1153   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1154              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1155
1156   oldfunc = (h->type != STT_NOTYPE
1157              && bed->is_function_type (h->type));
1158
1159   /* When we try to create a default indirect symbol from the dynamic
1160      definition with the default version, we skip it if its type and
1161      the type of existing regular definition mismatch.  */
1162   if (pold_alignment == NULL
1163       && newdyn
1164       && newdef
1165       && !olddyn
1166       && (((olddef || h->root.type == bfd_link_hash_common)
1167            && ELF_ST_TYPE (sym->st_info) != h->type
1168            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1169            && h->type != STT_NOTYPE
1170            && !(newfunc && oldfunc))
1171           || (olddef
1172               && ((h->type == STT_GNU_IFUNC)
1173                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1174     {
1175       *skip = TRUE;
1176       return TRUE;
1177     }
1178
1179   /* Check TLS symbols.  We don't check undefined symbols introduced
1180      by "ld -u" which have no type (and oldbfd NULL), and we don't
1181      check symbols from plugins because they also have no type.  */
1182   if (oldbfd != NULL
1183       && (oldbfd->flags & BFD_PLUGIN) == 0
1184       && (abfd->flags & BFD_PLUGIN) == 0
1185       && ELF_ST_TYPE (sym->st_info) != h->type
1186       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1187     {
1188       bfd *ntbfd, *tbfd;
1189       bfd_boolean ntdef, tdef;
1190       asection *ntsec, *tsec;
1191
1192       if (h->type == STT_TLS)
1193         {
1194           ntbfd = abfd;
1195           ntsec = sec;
1196           ntdef = newdef;
1197           tbfd = oldbfd;
1198           tsec = oldsec;
1199           tdef = olddef;
1200         }
1201       else
1202         {
1203           ntbfd = oldbfd;
1204           ntsec = oldsec;
1205           ntdef = olddef;
1206           tbfd = abfd;
1207           tsec = sec;
1208           tdef = newdef;
1209         }
1210
1211       if (tdef && ntdef)
1212         (*_bfd_error_handler)
1213           (_("%s: TLS definition in %B section %A "
1214              "mismatches non-TLS definition in %B section %A"),
1215            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1216       else if (!tdef && !ntdef)
1217         (*_bfd_error_handler)
1218           (_("%s: TLS reference in %B "
1219              "mismatches non-TLS reference in %B"),
1220            tbfd, ntbfd, h->root.root.string);
1221       else if (tdef)
1222         (*_bfd_error_handler)
1223           (_("%s: TLS definition in %B section %A "
1224              "mismatches non-TLS reference in %B"),
1225            tbfd, tsec, ntbfd, h->root.root.string);
1226       else
1227         (*_bfd_error_handler)
1228           (_("%s: TLS reference in %B "
1229              "mismatches non-TLS definition in %B section %A"),
1230            tbfd, ntbfd, ntsec, h->root.root.string);
1231
1232       bfd_set_error (bfd_error_bad_value);
1233       return FALSE;
1234     }
1235
1236   /* If the old symbol has non-default visibility, we ignore the new
1237      definition from a dynamic object.  */
1238   if (newdyn
1239       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1240       && !bfd_is_und_section (sec))
1241     {
1242       *skip = TRUE;
1243       /* Make sure this symbol is dynamic.  */
1244       h->ref_dynamic = 1;
1245       hi->ref_dynamic = 1;
1246       /* A protected symbol has external availability. Make sure it is
1247          recorded as dynamic.
1248
1249          FIXME: Should we check type and size for protected symbol?  */
1250       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1251         return bfd_elf_link_record_dynamic_symbol (info, h);
1252       else
1253         return TRUE;
1254     }
1255   else if (!newdyn
1256            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1257            && h->def_dynamic)
1258     {
1259       /* If the new symbol with non-default visibility comes from a
1260          relocatable file and the old definition comes from a dynamic
1261          object, we remove the old definition.  */
1262       if (hi->root.type == bfd_link_hash_indirect)
1263         {
1264           /* Handle the case where the old dynamic definition is
1265              default versioned.  We need to copy the symbol info from
1266              the symbol with default version to the normal one if it
1267              was referenced before.  */
1268           if (h->ref_regular)
1269             {
1270               hi->root.type = h->root.type;
1271               h->root.type = bfd_link_hash_indirect;
1272               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1273
1274               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1275               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1276                 {
1277                   /* If the new symbol is hidden or internal, completely undo
1278                      any dynamic link state.  */
1279                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1280                   h->forced_local = 0;
1281                   h->ref_dynamic = 0;
1282                 }
1283               else
1284                 h->ref_dynamic = 1;
1285
1286               h->def_dynamic = 0;
1287               /* FIXME: Should we check type and size for protected symbol?  */
1288               h->size = 0;
1289               h->type = 0;
1290
1291               h = hi;
1292             }
1293           else
1294             h = hi;
1295         }
1296
1297       /* If the old symbol was undefined before, then it will still be
1298          on the undefs list.  If the new symbol is undefined or
1299          common, we can't make it bfd_link_hash_new here, because new
1300          undefined or common symbols will be added to the undefs list
1301          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1302          added twice to the undefs list.  Also, if the new symbol is
1303          undefweak then we don't want to lose the strong undef.  */
1304       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1305         {
1306           h->root.type = bfd_link_hash_undefined;
1307           h->root.u.undef.abfd = abfd;
1308         }
1309       else
1310         {
1311           h->root.type = bfd_link_hash_new;
1312           h->root.u.undef.abfd = NULL;
1313         }
1314
1315       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1316         {
1317           /* If the new symbol is hidden or internal, completely undo
1318              any dynamic link state.  */
1319           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1320           h->forced_local = 0;
1321           h->ref_dynamic = 0;
1322         }
1323       else
1324         h->ref_dynamic = 1;
1325       h->def_dynamic = 0;
1326       /* FIXME: Should we check type and size for protected symbol?  */
1327       h->size = 0;
1328       h->type = 0;
1329       return TRUE;
1330     }
1331
1332   /* If a new weak symbol definition comes from a regular file and the
1333      old symbol comes from a dynamic library, we treat the new one as
1334      strong.  Similarly, an old weak symbol definition from a regular
1335      file is treated as strong when the new symbol comes from a dynamic
1336      library.  Further, an old weak symbol from a dynamic library is
1337      treated as strong if the new symbol is from a dynamic library.
1338      This reflects the way glibc's ld.so works.
1339
1340      Do this before setting *type_change_ok or *size_change_ok so that
1341      we warn properly when dynamic library symbols are overridden.  */
1342
1343   if (newdef && !newdyn && olddyn)
1344     newweak = FALSE;
1345   if (olddef && newdyn)
1346     oldweak = FALSE;
1347
1348   /* Allow changes between different types of function symbol.  */
1349   if (newfunc && oldfunc)
1350     *type_change_ok = TRUE;
1351
1352   /* It's OK to change the type if either the existing symbol or the
1353      new symbol is weak.  A type change is also OK if the old symbol
1354      is undefined and the new symbol is defined.  */
1355
1356   if (oldweak
1357       || newweak
1358       || (newdef
1359           && h->root.type == bfd_link_hash_undefined))
1360     *type_change_ok = TRUE;
1361
1362   /* It's OK to change the size if either the existing symbol or the
1363      new symbol is weak, or if the old symbol is undefined.  */
1364
1365   if (*type_change_ok
1366       || h->root.type == bfd_link_hash_undefined)
1367     *size_change_ok = TRUE;
1368
1369   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1370      symbol, respectively, appears to be a common symbol in a dynamic
1371      object.  If a symbol appears in an uninitialized section, and is
1372      not weak, and is not a function, then it may be a common symbol
1373      which was resolved when the dynamic object was created.  We want
1374      to treat such symbols specially, because they raise special
1375      considerations when setting the symbol size: if the symbol
1376      appears as a common symbol in a regular object, and the size in
1377      the regular object is larger, we must make sure that we use the
1378      larger size.  This problematic case can always be avoided in C,
1379      but it must be handled correctly when using Fortran shared
1380      libraries.
1381
1382      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1383      likewise for OLDDYNCOMMON and OLDDEF.
1384
1385      Note that this test is just a heuristic, and that it is quite
1386      possible to have an uninitialized symbol in a shared object which
1387      is really a definition, rather than a common symbol.  This could
1388      lead to some minor confusion when the symbol really is a common
1389      symbol in some regular object.  However, I think it will be
1390      harmless.  */
1391
1392   if (newdyn
1393       && newdef
1394       && !newweak
1395       && (sec->flags & SEC_ALLOC) != 0
1396       && (sec->flags & SEC_LOAD) == 0
1397       && sym->st_size > 0
1398       && !newfunc)
1399     newdyncommon = TRUE;
1400   else
1401     newdyncommon = FALSE;
1402
1403   if (olddyn
1404       && olddef
1405       && h->root.type == bfd_link_hash_defined
1406       && h->def_dynamic
1407       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1408       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1409       && h->size > 0
1410       && !oldfunc)
1411     olddyncommon = TRUE;
1412   else
1413     olddyncommon = FALSE;
1414
1415   /* We now know everything about the old and new symbols.  We ask the
1416      backend to check if we can merge them.  */
1417   if (bed->merge_symbol != NULL)
1418     {
1419       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1420         return FALSE;
1421       sec = *psec;
1422     }
1423
1424   /* If both the old and the new symbols look like common symbols in a
1425      dynamic object, set the size of the symbol to the larger of the
1426      two.  */
1427
1428   if (olddyncommon
1429       && newdyncommon
1430       && sym->st_size != h->size)
1431     {
1432       /* Since we think we have two common symbols, issue a multiple
1433          common warning if desired.  Note that we only warn if the
1434          size is different.  If the size is the same, we simply let
1435          the old symbol override the new one as normally happens with
1436          symbols defined in dynamic objects.  */
1437
1438       if (! ((*info->callbacks->multiple_common)
1439              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1440         return FALSE;
1441
1442       if (sym->st_size > h->size)
1443         h->size = sym->st_size;
1444
1445       *size_change_ok = TRUE;
1446     }
1447
1448   /* If we are looking at a dynamic object, and we have found a
1449      definition, we need to see if the symbol was already defined by
1450      some other object.  If so, we want to use the existing
1451      definition, and we do not want to report a multiple symbol
1452      definition error; we do this by clobbering *PSEC to be
1453      bfd_und_section_ptr.
1454
1455      We treat a common symbol as a definition if the symbol in the
1456      shared library is a function, since common symbols always
1457      represent variables; this can cause confusion in principle, but
1458      any such confusion would seem to indicate an erroneous program or
1459      shared library.  We also permit a common symbol in a regular
1460      object to override a weak symbol in a shared object.  */
1461
1462   if (newdyn
1463       && newdef
1464       && (olddef
1465           || (h->root.type == bfd_link_hash_common
1466               && (newweak || newfunc))))
1467     {
1468       *override = TRUE;
1469       newdef = FALSE;
1470       newdyncommon = FALSE;
1471
1472       *psec = sec = bfd_und_section_ptr;
1473       *size_change_ok = TRUE;
1474
1475       /* If we get here when the old symbol is a common symbol, then
1476          we are explicitly letting it override a weak symbol or
1477          function in a dynamic object, and we don't want to warn about
1478          a type change.  If the old symbol is a defined symbol, a type
1479          change warning may still be appropriate.  */
1480
1481       if (h->root.type == bfd_link_hash_common)
1482         *type_change_ok = TRUE;
1483     }
1484
1485   /* Handle the special case of an old common symbol merging with a
1486      new symbol which looks like a common symbol in a shared object.
1487      We change *PSEC and *PVALUE to make the new symbol look like a
1488      common symbol, and let _bfd_generic_link_add_one_symbol do the
1489      right thing.  */
1490
1491   if (newdyncommon
1492       && h->root.type == bfd_link_hash_common)
1493     {
1494       *override = TRUE;
1495       newdef = FALSE;
1496       newdyncommon = FALSE;
1497       *pvalue = sym->st_size;
1498       *psec = sec = bed->common_section (oldsec);
1499       *size_change_ok = TRUE;
1500     }
1501
1502   /* Skip weak definitions of symbols that are already defined.  */
1503   if (newdef && olddef && newweak)
1504     {
1505       /* Don't skip new non-IR weak syms.  */
1506       if (!(oldbfd != NULL
1507             && (oldbfd->flags & BFD_PLUGIN) != 0
1508             && (abfd->flags & BFD_PLUGIN) == 0))
1509         {
1510           newdef = FALSE;
1511           *skip = TRUE;
1512         }
1513
1514       /* Merge st_other.  If the symbol already has a dynamic index,
1515          but visibility says it should not be visible, turn it into a
1516          local symbol.  */
1517       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1518       if (h->dynindx != -1)
1519         switch (ELF_ST_VISIBILITY (h->other))
1520           {
1521           case STV_INTERNAL:
1522           case STV_HIDDEN:
1523             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1524             break;
1525           }
1526     }
1527
1528   /* If the old symbol is from a dynamic object, and the new symbol is
1529      a definition which is not from a dynamic object, then the new
1530      symbol overrides the old symbol.  Symbols from regular files
1531      always take precedence over symbols from dynamic objects, even if
1532      they are defined after the dynamic object in the link.
1533
1534      As above, we again permit a common symbol in a regular object to
1535      override a definition in a shared object if the shared object
1536      symbol is a function or is weak.  */
1537
1538   flip = NULL;
1539   if (!newdyn
1540       && (newdef
1541           || (bfd_is_com_section (sec)
1542               && (oldweak || oldfunc)))
1543       && olddyn
1544       && olddef
1545       && h->def_dynamic)
1546     {
1547       /* Change the hash table entry to undefined, and let
1548          _bfd_generic_link_add_one_symbol do the right thing with the
1549          new definition.  */
1550
1551       h->root.type = bfd_link_hash_undefined;
1552       h->root.u.undef.abfd = h->root.u.def.section->owner;
1553       *size_change_ok = TRUE;
1554
1555       olddef = FALSE;
1556       olddyncommon = FALSE;
1557
1558       /* We again permit a type change when a common symbol may be
1559          overriding a function.  */
1560
1561       if (bfd_is_com_section (sec))
1562         {
1563           if (oldfunc)
1564             {
1565               /* If a common symbol overrides a function, make sure
1566                  that it isn't defined dynamically nor has type
1567                  function.  */
1568               h->def_dynamic = 0;
1569               h->type = STT_NOTYPE;
1570             }
1571           *type_change_ok = TRUE;
1572         }
1573
1574       if (hi->root.type == bfd_link_hash_indirect)
1575         flip = hi;
1576       else
1577         /* This union may have been set to be non-NULL when this symbol
1578            was seen in a dynamic object.  We must force the union to be
1579            NULL, so that it is correct for a regular symbol.  */
1580         h->verinfo.vertree = NULL;
1581     }
1582
1583   /* Handle the special case of a new common symbol merging with an
1584      old symbol that looks like it might be a common symbol defined in
1585      a shared object.  Note that we have already handled the case in
1586      which a new common symbol should simply override the definition
1587      in the shared library.  */
1588
1589   if (! newdyn
1590       && bfd_is_com_section (sec)
1591       && olddyncommon)
1592     {
1593       /* It would be best if we could set the hash table entry to a
1594          common symbol, but we don't know what to use for the section
1595          or the alignment.  */
1596       if (! ((*info->callbacks->multiple_common)
1597              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1598         return FALSE;
1599
1600       /* If the presumed common symbol in the dynamic object is
1601          larger, pretend that the new symbol has its size.  */
1602
1603       if (h->size > *pvalue)
1604         *pvalue = h->size;
1605
1606       /* We need to remember the alignment required by the symbol
1607          in the dynamic object.  */
1608       BFD_ASSERT (pold_alignment);
1609       *pold_alignment = h->root.u.def.section->alignment_power;
1610
1611       olddef = FALSE;
1612       olddyncommon = FALSE;
1613
1614       h->root.type = bfd_link_hash_undefined;
1615       h->root.u.undef.abfd = h->root.u.def.section->owner;
1616
1617       *size_change_ok = TRUE;
1618       *type_change_ok = TRUE;
1619
1620       if (hi->root.type == bfd_link_hash_indirect)
1621         flip = hi;
1622       else
1623         h->verinfo.vertree = NULL;
1624     }
1625
1626   if (flip != NULL)
1627     {
1628       /* Handle the case where we had a versioned symbol in a dynamic
1629          library and now find a definition in a normal object.  In this
1630          case, we make the versioned symbol point to the normal one.  */
1631       flip->root.type = h->root.type;
1632       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1633       h->root.type = bfd_link_hash_indirect;
1634       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1635       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1636       if (h->def_dynamic)
1637         {
1638           h->def_dynamic = 0;
1639           flip->ref_dynamic = 1;
1640         }
1641     }
1642
1643   return TRUE;
1644 }
1645
1646 /* This function is called to create an indirect symbol from the
1647    default for the symbol with the default version if needed. The
1648    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1649    set DYNSYM if the new indirect symbol is dynamic.  */
1650
1651 static bfd_boolean
1652 _bfd_elf_add_default_symbol (bfd *abfd,
1653                              struct bfd_link_info *info,
1654                              struct elf_link_hash_entry *h,
1655                              const char *name,
1656                              Elf_Internal_Sym *sym,
1657                              asection *sec,
1658                              bfd_vma value,
1659                              bfd **poldbfd,
1660                              bfd_boolean *dynsym)
1661 {
1662   bfd_boolean type_change_ok;
1663   bfd_boolean size_change_ok;
1664   bfd_boolean skip;
1665   char *shortname;
1666   struct elf_link_hash_entry *hi;
1667   struct bfd_link_hash_entry *bh;
1668   const struct elf_backend_data *bed;
1669   bfd_boolean collect;
1670   bfd_boolean dynamic;
1671   bfd_boolean override;
1672   char *p;
1673   size_t len, shortlen;
1674   asection *tmp_sec;
1675   bfd_boolean matched;
1676
1677   /* If this symbol has a version, and it is the default version, we
1678      create an indirect symbol from the default name to the fully
1679      decorated name.  This will cause external references which do not
1680      specify a version to be bound to this version of the symbol.  */
1681   p = strchr (name, ELF_VER_CHR);
1682   if (p == NULL || p[1] != ELF_VER_CHR)
1683     return TRUE;
1684
1685   bed = get_elf_backend_data (abfd);
1686   collect = bed->collect;
1687   dynamic = (abfd->flags & DYNAMIC) != 0;
1688
1689   shortlen = p - name;
1690   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1691   if (shortname == NULL)
1692     return FALSE;
1693   memcpy (shortname, name, shortlen);
1694   shortname[shortlen] = '\0';
1695
1696   /* We are going to create a new symbol.  Merge it with any existing
1697      symbol with this name.  For the purposes of the merge, act as
1698      though we were defining the symbol we just defined, although we
1699      actually going to define an indirect symbol.  */
1700   type_change_ok = FALSE;
1701   size_change_ok = FALSE;
1702   matched = TRUE;
1703   tmp_sec = sec;
1704   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1705                               &hi, poldbfd, NULL, NULL, &skip, &override,
1706                               &type_change_ok, &size_change_ok, &matched))
1707     return FALSE;
1708
1709   if (skip)
1710     goto nondefault;
1711
1712   if (! override)
1713     {
1714       /* Add the default symbol if not performing a relocatable link.  */
1715       if (! info->relocatable)
1716         {
1717           bh = &hi->root;
1718           if (! (_bfd_generic_link_add_one_symbol
1719                  (info, abfd, shortname, BSF_INDIRECT,
1720                   bfd_ind_section_ptr,
1721                   0, name, FALSE, collect, &bh)))
1722             return FALSE;
1723           hi = (struct elf_link_hash_entry *) bh;
1724         }
1725     }
1726   else
1727     {
1728       /* In this case the symbol named SHORTNAME is overriding the
1729          indirect symbol we want to add.  We were planning on making
1730          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1731          is the name without a version.  NAME is the fully versioned
1732          name, and it is the default version.
1733
1734          Overriding means that we already saw a definition for the
1735          symbol SHORTNAME in a regular object, and it is overriding
1736          the symbol defined in the dynamic object.
1737
1738          When this happens, we actually want to change NAME, the
1739          symbol we just added, to refer to SHORTNAME.  This will cause
1740          references to NAME in the shared object to become references
1741          to SHORTNAME in the regular object.  This is what we expect
1742          when we override a function in a shared object: that the
1743          references in the shared object will be mapped to the
1744          definition in the regular object.  */
1745
1746       while (hi->root.type == bfd_link_hash_indirect
1747              || hi->root.type == bfd_link_hash_warning)
1748         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1749
1750       h->root.type = bfd_link_hash_indirect;
1751       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1752       if (h->def_dynamic)
1753         {
1754           h->def_dynamic = 0;
1755           hi->ref_dynamic = 1;
1756           if (hi->ref_regular
1757               || hi->def_regular)
1758             {
1759               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1760                 return FALSE;
1761             }
1762         }
1763
1764       /* Now set HI to H, so that the following code will set the
1765          other fields correctly.  */
1766       hi = h;
1767     }
1768
1769   /* Check if HI is a warning symbol.  */
1770   if (hi->root.type == bfd_link_hash_warning)
1771     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1772
1773   /* If there is a duplicate definition somewhere, then HI may not
1774      point to an indirect symbol.  We will have reported an error to
1775      the user in that case.  */
1776
1777   if (hi->root.type == bfd_link_hash_indirect)
1778     {
1779       struct elf_link_hash_entry *ht;
1780
1781       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1782       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1783
1784       /* A reference to the SHORTNAME symbol from a dynamic library
1785          will be satisfied by the versioned symbol at runtime.  In
1786          effect, we have a reference to the versioned symbol.  */
1787       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1788       hi->dynamic_def |= ht->dynamic_def;
1789
1790       /* See if the new flags lead us to realize that the symbol must
1791          be dynamic.  */
1792       if (! *dynsym)
1793         {
1794           if (! dynamic)
1795             {
1796               if (! info->executable
1797                   || hi->def_dynamic
1798                   || hi->ref_dynamic)
1799                 *dynsym = TRUE;
1800             }
1801           else
1802             {
1803               if (hi->ref_regular)
1804                 *dynsym = TRUE;
1805             }
1806         }
1807     }
1808
1809   /* We also need to define an indirection from the nondefault version
1810      of the symbol.  */
1811
1812 nondefault:
1813   len = strlen (name);
1814   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1815   if (shortname == NULL)
1816     return FALSE;
1817   memcpy (shortname, name, shortlen);
1818   memcpy (shortname + shortlen, p + 1, len - shortlen);
1819
1820   /* Once again, merge with any existing symbol.  */
1821   type_change_ok = FALSE;
1822   size_change_ok = FALSE;
1823   tmp_sec = sec;
1824   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1825                               &hi, poldbfd, NULL, NULL, &skip, &override,
1826                               &type_change_ok, &size_change_ok, &matched))
1827     return FALSE;
1828
1829   if (skip)
1830     return TRUE;
1831
1832   if (override)
1833     {
1834       /* Here SHORTNAME is a versioned name, so we don't expect to see
1835          the type of override we do in the case above unless it is
1836          overridden by a versioned definition.  */
1837       if (hi->root.type != bfd_link_hash_defined
1838           && hi->root.type != bfd_link_hash_defweak)
1839         (*_bfd_error_handler)
1840           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1841            abfd, shortname);
1842     }
1843   else
1844     {
1845       bh = &hi->root;
1846       if (! (_bfd_generic_link_add_one_symbol
1847              (info, abfd, shortname, BSF_INDIRECT,
1848               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1849         return FALSE;
1850       hi = (struct elf_link_hash_entry *) bh;
1851
1852       /* If there is a duplicate definition somewhere, then HI may not
1853          point to an indirect symbol.  We will have reported an error
1854          to the user in that case.  */
1855
1856       if (hi->root.type == bfd_link_hash_indirect)
1857         {
1858           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1859           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1860           hi->dynamic_def |= h->dynamic_def;
1861
1862           /* See if the new flags lead us to realize that the symbol
1863              must be dynamic.  */
1864           if (! *dynsym)
1865             {
1866               if (! dynamic)
1867                 {
1868                   if (! info->executable
1869                       || hi->ref_dynamic)
1870                     *dynsym = TRUE;
1871                 }
1872               else
1873                 {
1874                   if (hi->ref_regular)
1875                     *dynsym = TRUE;
1876                 }
1877             }
1878         }
1879     }
1880
1881   return TRUE;
1882 }
1883 \f
1884 /* This routine is used to export all defined symbols into the dynamic
1885    symbol table.  It is called via elf_link_hash_traverse.  */
1886
1887 static bfd_boolean
1888 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1889 {
1890   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1891
1892   /* Ignore indirect symbols.  These are added by the versioning code.  */
1893   if (h->root.type == bfd_link_hash_indirect)
1894     return TRUE;
1895
1896   /* Ignore this if we won't export it.  */
1897   if (!eif->info->export_dynamic && !h->dynamic)
1898     return TRUE;
1899
1900   if (h->dynindx == -1
1901       && (h->def_regular || h->ref_regular)
1902       && ! bfd_hide_sym_by_version (eif->info->version_info,
1903                                     h->root.root.string))
1904     {
1905       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1906         {
1907           eif->failed = TRUE;
1908           return FALSE;
1909         }
1910     }
1911
1912   return TRUE;
1913 }
1914 \f
1915 /* Look through the symbols which are defined in other shared
1916    libraries and referenced here.  Update the list of version
1917    dependencies.  This will be put into the .gnu.version_r section.
1918    This function is called via elf_link_hash_traverse.  */
1919
1920 static bfd_boolean
1921 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1922                                          void *data)
1923 {
1924   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1925   Elf_Internal_Verneed *t;
1926   Elf_Internal_Vernaux *a;
1927   bfd_size_type amt;
1928
1929   /* We only care about symbols defined in shared objects with version
1930      information.  */
1931   if (!h->def_dynamic
1932       || h->def_regular
1933       || h->dynindx == -1
1934       || h->verinfo.verdef == NULL
1935       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
1936           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
1937     return TRUE;
1938
1939   /* See if we already know about this version.  */
1940   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
1941        t != NULL;
1942        t = t->vn_nextref)
1943     {
1944       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1945         continue;
1946
1947       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1948         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1949           return TRUE;
1950
1951       break;
1952     }
1953
1954   /* This is a new version.  Add it to tree we are building.  */
1955
1956   if (t == NULL)
1957     {
1958       amt = sizeof *t;
1959       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
1960       if (t == NULL)
1961         {
1962           rinfo->failed = TRUE;
1963           return FALSE;
1964         }
1965
1966       t->vn_bfd = h->verinfo.verdef->vd_bfd;
1967       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
1968       elf_tdata (rinfo->info->output_bfd)->verref = t;
1969     }
1970
1971   amt = sizeof *a;
1972   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
1973   if (a == NULL)
1974     {
1975       rinfo->failed = TRUE;
1976       return FALSE;
1977     }
1978
1979   /* Note that we are copying a string pointer here, and testing it
1980      above.  If bfd_elf_string_from_elf_section is ever changed to
1981      discard the string data when low in memory, this will have to be
1982      fixed.  */
1983   a->vna_nodename = h->verinfo.verdef->vd_nodename;
1984
1985   a->vna_flags = h->verinfo.verdef->vd_flags;
1986   a->vna_nextptr = t->vn_auxptr;
1987
1988   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1989   ++rinfo->vers;
1990
1991   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1992
1993   t->vn_auxptr = a;
1994
1995   return TRUE;
1996 }
1997
1998 /* Figure out appropriate versions for all the symbols.  We may not
1999    have the version number script until we have read all of the input
2000    files, so until that point we don't know which symbols should be
2001    local.  This function is called via elf_link_hash_traverse.  */
2002
2003 static bfd_boolean
2004 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2005 {
2006   struct elf_info_failed *sinfo;
2007   struct bfd_link_info *info;
2008   const struct elf_backend_data *bed;
2009   struct elf_info_failed eif;
2010   char *p;
2011   bfd_size_type amt;
2012
2013   sinfo = (struct elf_info_failed *) data;
2014   info = sinfo->info;
2015
2016   /* Fix the symbol flags.  */
2017   eif.failed = FALSE;
2018   eif.info = info;
2019   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2020     {
2021       if (eif.failed)
2022         sinfo->failed = TRUE;
2023       return FALSE;
2024     }
2025
2026   /* We only need version numbers for symbols defined in regular
2027      objects.  */
2028   if (!h->def_regular)
2029     return TRUE;
2030
2031   bed = get_elf_backend_data (info->output_bfd);
2032   p = strchr (h->root.root.string, ELF_VER_CHR);
2033   if (p != NULL && h->verinfo.vertree == NULL)
2034     {
2035       struct bfd_elf_version_tree *t;
2036
2037       ++p;
2038       if (*p == ELF_VER_CHR)
2039         ++p;
2040
2041       /* If there is no version string, we can just return out.  */
2042       if (*p == '\0')
2043         return TRUE;
2044
2045       /* Look for the version.  If we find it, it is no longer weak.  */
2046       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2047         {
2048           if (strcmp (t->name, p) == 0)
2049             {
2050               size_t len;
2051               char *alc;
2052               struct bfd_elf_version_expr *d;
2053
2054               len = p - h->root.root.string;
2055               alc = (char *) bfd_malloc (len);
2056               if (alc == NULL)
2057                 {
2058                   sinfo->failed = TRUE;
2059                   return FALSE;
2060                 }
2061               memcpy (alc, h->root.root.string, len - 1);
2062               alc[len - 1] = '\0';
2063               if (alc[len - 2] == ELF_VER_CHR)
2064                 alc[len - 2] = '\0';
2065
2066               h->verinfo.vertree = t;
2067               t->used = TRUE;
2068               d = NULL;
2069
2070               if (t->globals.list != NULL)
2071                 d = (*t->match) (&t->globals, NULL, alc);
2072
2073               /* See if there is anything to force this symbol to
2074                  local scope.  */
2075               if (d == NULL && t->locals.list != NULL)
2076                 {
2077                   d = (*t->match) (&t->locals, NULL, alc);
2078                   if (d != NULL
2079                       && h->dynindx != -1
2080                       && ! info->export_dynamic)
2081                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2082                 }
2083
2084               free (alc);
2085               break;
2086             }
2087         }
2088
2089       /* If we are building an application, we need to create a
2090          version node for this version.  */
2091       if (t == NULL && info->executable)
2092         {
2093           struct bfd_elf_version_tree **pp;
2094           int version_index;
2095
2096           /* If we aren't going to export this symbol, we don't need
2097              to worry about it.  */
2098           if (h->dynindx == -1)
2099             return TRUE;
2100
2101           amt = sizeof *t;
2102           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2103           if (t == NULL)
2104             {
2105               sinfo->failed = TRUE;
2106               return FALSE;
2107             }
2108
2109           t->name = p;
2110           t->name_indx = (unsigned int) -1;
2111           t->used = TRUE;
2112
2113           version_index = 1;
2114           /* Don't count anonymous version tag.  */
2115           if (sinfo->info->version_info != NULL
2116               && sinfo->info->version_info->vernum == 0)
2117             version_index = 0;
2118           for (pp = &sinfo->info->version_info;
2119                *pp != NULL;
2120                pp = &(*pp)->next)
2121             ++version_index;
2122           t->vernum = version_index;
2123
2124           *pp = t;
2125
2126           h->verinfo.vertree = t;
2127         }
2128       else if (t == NULL)
2129         {
2130           /* We could not find the version for a symbol when
2131              generating a shared archive.  Return an error.  */
2132           (*_bfd_error_handler)
2133             (_("%B: version node not found for symbol %s"),
2134              info->output_bfd, h->root.root.string);
2135           bfd_set_error (bfd_error_bad_value);
2136           sinfo->failed = TRUE;
2137           return FALSE;
2138         }
2139     }
2140
2141   /* If we don't have a version for this symbol, see if we can find
2142      something.  */
2143   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2144     {
2145       bfd_boolean hide;
2146
2147       h->verinfo.vertree
2148         = bfd_find_version_for_sym (sinfo->info->version_info,
2149                                     h->root.root.string, &hide);
2150       if (h->verinfo.vertree != NULL && hide)
2151         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2152     }
2153
2154   return TRUE;
2155 }
2156 \f
2157 /* Read and swap the relocs from the section indicated by SHDR.  This
2158    may be either a REL or a RELA section.  The relocations are
2159    translated into RELA relocations and stored in INTERNAL_RELOCS,
2160    which should have already been allocated to contain enough space.
2161    The EXTERNAL_RELOCS are a buffer where the external form of the
2162    relocations should be stored.
2163
2164    Returns FALSE if something goes wrong.  */
2165
2166 static bfd_boolean
2167 elf_link_read_relocs_from_section (bfd *abfd,
2168                                    asection *sec,
2169                                    Elf_Internal_Shdr *shdr,
2170                                    void *external_relocs,
2171                                    Elf_Internal_Rela *internal_relocs)
2172 {
2173   const struct elf_backend_data *bed;
2174   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2175   const bfd_byte *erela;
2176   const bfd_byte *erelaend;
2177   Elf_Internal_Rela *irela;
2178   Elf_Internal_Shdr *symtab_hdr;
2179   size_t nsyms;
2180
2181   /* Position ourselves at the start of the section.  */
2182   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2183     return FALSE;
2184
2185   /* Read the relocations.  */
2186   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2187     return FALSE;
2188
2189   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2190   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2191
2192   bed = get_elf_backend_data (abfd);
2193
2194   /* Convert the external relocations to the internal format.  */
2195   if (shdr->sh_entsize == bed->s->sizeof_rel)
2196     swap_in = bed->s->swap_reloc_in;
2197   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2198     swap_in = bed->s->swap_reloca_in;
2199   else
2200     {
2201       bfd_set_error (bfd_error_wrong_format);
2202       return FALSE;
2203     }
2204
2205   erela = (const bfd_byte *) external_relocs;
2206   erelaend = erela + shdr->sh_size;
2207   irela = internal_relocs;
2208   while (erela < erelaend)
2209     {
2210       bfd_vma r_symndx;
2211
2212       (*swap_in) (abfd, erela, irela);
2213       r_symndx = ELF32_R_SYM (irela->r_info);
2214       if (bed->s->arch_size == 64)
2215         r_symndx >>= 24;
2216       if (nsyms > 0)
2217         {
2218           if ((size_t) r_symndx >= nsyms)
2219             {
2220               (*_bfd_error_handler)
2221                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2222                    " for offset 0x%lx in section `%A'"),
2223                  abfd, sec,
2224                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2225               bfd_set_error (bfd_error_bad_value);
2226               return FALSE;
2227             }
2228         }
2229       else if (r_symndx != STN_UNDEF)
2230         {
2231           (*_bfd_error_handler)
2232             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2233                " when the object file has no symbol table"),
2234              abfd, sec,
2235              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2236           bfd_set_error (bfd_error_bad_value);
2237           return FALSE;
2238         }
2239       irela += bed->s->int_rels_per_ext_rel;
2240       erela += shdr->sh_entsize;
2241     }
2242
2243   return TRUE;
2244 }
2245
2246 /* Read and swap the relocs for a section O.  They may have been
2247    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2248    not NULL, they are used as buffers to read into.  They are known to
2249    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2250    the return value is allocated using either malloc or bfd_alloc,
2251    according to the KEEP_MEMORY argument.  If O has two relocation
2252    sections (both REL and RELA relocations), then the REL_HDR
2253    relocations will appear first in INTERNAL_RELOCS, followed by the
2254    RELA_HDR relocations.  */
2255
2256 Elf_Internal_Rela *
2257 _bfd_elf_link_read_relocs (bfd *abfd,
2258                            asection *o,
2259                            void *external_relocs,
2260                            Elf_Internal_Rela *internal_relocs,
2261                            bfd_boolean keep_memory)
2262 {
2263   void *alloc1 = NULL;
2264   Elf_Internal_Rela *alloc2 = NULL;
2265   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2266   struct bfd_elf_section_data *esdo = elf_section_data (o);
2267   Elf_Internal_Rela *internal_rela_relocs;
2268
2269   if (esdo->relocs != NULL)
2270     return esdo->relocs;
2271
2272   if (o->reloc_count == 0)
2273     return NULL;
2274
2275   if (internal_relocs == NULL)
2276     {
2277       bfd_size_type size;
2278
2279       size = o->reloc_count;
2280       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2281       if (keep_memory)
2282         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2283       else
2284         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2285       if (internal_relocs == NULL)
2286         goto error_return;
2287     }
2288
2289   if (external_relocs == NULL)
2290     {
2291       bfd_size_type size = 0;
2292
2293       if (esdo->rel.hdr)
2294         size += esdo->rel.hdr->sh_size;
2295       if (esdo->rela.hdr)
2296         size += esdo->rela.hdr->sh_size;
2297
2298       alloc1 = bfd_malloc (size);
2299       if (alloc1 == NULL)
2300         goto error_return;
2301       external_relocs = alloc1;
2302     }
2303
2304   internal_rela_relocs = internal_relocs;
2305   if (esdo->rel.hdr)
2306     {
2307       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2308                                               external_relocs,
2309                                               internal_relocs))
2310         goto error_return;
2311       external_relocs = (((bfd_byte *) external_relocs)
2312                          + esdo->rel.hdr->sh_size);
2313       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2314                                * bed->s->int_rels_per_ext_rel);
2315     }
2316
2317   if (esdo->rela.hdr
2318       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2319                                               external_relocs,
2320                                               internal_rela_relocs)))
2321     goto error_return;
2322
2323   /* Cache the results for next time, if we can.  */
2324   if (keep_memory)
2325     esdo->relocs = internal_relocs;
2326
2327   if (alloc1 != NULL)
2328     free (alloc1);
2329
2330   /* Don't free alloc2, since if it was allocated we are passing it
2331      back (under the name of internal_relocs).  */
2332
2333   return internal_relocs;
2334
2335  error_return:
2336   if (alloc1 != NULL)
2337     free (alloc1);
2338   if (alloc2 != NULL)
2339     {
2340       if (keep_memory)
2341         bfd_release (abfd, alloc2);
2342       else
2343         free (alloc2);
2344     }
2345   return NULL;
2346 }
2347
2348 /* Compute the size of, and allocate space for, REL_HDR which is the
2349    section header for a section containing relocations for O.  */
2350
2351 static bfd_boolean
2352 _bfd_elf_link_size_reloc_section (bfd *abfd,
2353                                   struct bfd_elf_section_reloc_data *reldata)
2354 {
2355   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2356
2357   /* That allows us to calculate the size of the section.  */
2358   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2359
2360   /* The contents field must last into write_object_contents, so we
2361      allocate it with bfd_alloc rather than malloc.  Also since we
2362      cannot be sure that the contents will actually be filled in,
2363      we zero the allocated space.  */
2364   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2365   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2366     return FALSE;
2367
2368   if (reldata->hashes == NULL && reldata->count)
2369     {
2370       struct elf_link_hash_entry **p;
2371
2372       p = ((struct elf_link_hash_entry **)
2373            bfd_zmalloc (reldata->count * sizeof (*p)));
2374       if (p == NULL)
2375         return FALSE;
2376
2377       reldata->hashes = p;
2378     }
2379
2380   return TRUE;
2381 }
2382
2383 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2384    originated from the section given by INPUT_REL_HDR) to the
2385    OUTPUT_BFD.  */
2386
2387 bfd_boolean
2388 _bfd_elf_link_output_relocs (bfd *output_bfd,
2389                              asection *input_section,
2390                              Elf_Internal_Shdr *input_rel_hdr,
2391                              Elf_Internal_Rela *internal_relocs,
2392                              struct elf_link_hash_entry **rel_hash
2393                                ATTRIBUTE_UNUSED)
2394 {
2395   Elf_Internal_Rela *irela;
2396   Elf_Internal_Rela *irelaend;
2397   bfd_byte *erel;
2398   struct bfd_elf_section_reloc_data *output_reldata;
2399   asection *output_section;
2400   const struct elf_backend_data *bed;
2401   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2402   struct bfd_elf_section_data *esdo;
2403
2404   output_section = input_section->output_section;
2405
2406   bed = get_elf_backend_data (output_bfd);
2407   esdo = elf_section_data (output_section);
2408   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2409     {
2410       output_reldata = &esdo->rel;
2411       swap_out = bed->s->swap_reloc_out;
2412     }
2413   else if (esdo->rela.hdr
2414            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2415     {
2416       output_reldata = &esdo->rela;
2417       swap_out = bed->s->swap_reloca_out;
2418     }
2419   else
2420     {
2421       (*_bfd_error_handler)
2422         (_("%B: relocation size mismatch in %B section %A"),
2423          output_bfd, input_section->owner, input_section);
2424       bfd_set_error (bfd_error_wrong_format);
2425       return FALSE;
2426     }
2427
2428   erel = output_reldata->hdr->contents;
2429   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2430   irela = internal_relocs;
2431   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2432                       * bed->s->int_rels_per_ext_rel);
2433   while (irela < irelaend)
2434     {
2435       (*swap_out) (output_bfd, irela, erel);
2436       irela += bed->s->int_rels_per_ext_rel;
2437       erel += input_rel_hdr->sh_entsize;
2438     }
2439
2440   /* Bump the counter, so that we know where to add the next set of
2441      relocations.  */
2442   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2443
2444   return TRUE;
2445 }
2446 \f
2447 /* Make weak undefined symbols in PIE dynamic.  */
2448
2449 bfd_boolean
2450 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2451                                  struct elf_link_hash_entry *h)
2452 {
2453   if (info->pie
2454       && h->dynindx == -1
2455       && h->root.type == bfd_link_hash_undefweak)
2456     return bfd_elf_link_record_dynamic_symbol (info, h);
2457
2458   return TRUE;
2459 }
2460
2461 /* Fix up the flags for a symbol.  This handles various cases which
2462    can only be fixed after all the input files are seen.  This is
2463    currently called by both adjust_dynamic_symbol and
2464    assign_sym_version, which is unnecessary but perhaps more robust in
2465    the face of future changes.  */
2466
2467 static bfd_boolean
2468 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2469                            struct elf_info_failed *eif)
2470 {
2471   const struct elf_backend_data *bed;
2472
2473   /* If this symbol was mentioned in a non-ELF file, try to set
2474      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2475      permit a non-ELF file to correctly refer to a symbol defined in
2476      an ELF dynamic object.  */
2477   if (h->non_elf)
2478     {
2479       while (h->root.type == bfd_link_hash_indirect)
2480         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2481
2482       if (h->root.type != bfd_link_hash_defined
2483           && h->root.type != bfd_link_hash_defweak)
2484         {
2485           h->ref_regular = 1;
2486           h->ref_regular_nonweak = 1;
2487         }
2488       else
2489         {
2490           if (h->root.u.def.section->owner != NULL
2491               && (bfd_get_flavour (h->root.u.def.section->owner)
2492                   == bfd_target_elf_flavour))
2493             {
2494               h->ref_regular = 1;
2495               h->ref_regular_nonweak = 1;
2496             }
2497           else
2498             h->def_regular = 1;
2499         }
2500
2501       if (h->dynindx == -1
2502           && (h->def_dynamic
2503               || h->ref_dynamic))
2504         {
2505           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2506             {
2507               eif->failed = TRUE;
2508               return FALSE;
2509             }
2510         }
2511     }
2512   else
2513     {
2514       /* Unfortunately, NON_ELF is only correct if the symbol
2515          was first seen in a non-ELF file.  Fortunately, if the symbol
2516          was first seen in an ELF file, we're probably OK unless the
2517          symbol was defined in a non-ELF file.  Catch that case here.
2518          FIXME: We're still in trouble if the symbol was first seen in
2519          a dynamic object, and then later in a non-ELF regular object.  */
2520       if ((h->root.type == bfd_link_hash_defined
2521            || h->root.type == bfd_link_hash_defweak)
2522           && !h->def_regular
2523           && (h->root.u.def.section->owner != NULL
2524               ? (bfd_get_flavour (h->root.u.def.section->owner)
2525                  != bfd_target_elf_flavour)
2526               : (bfd_is_abs_section (h->root.u.def.section)
2527                  && !h->def_dynamic)))
2528         h->def_regular = 1;
2529     }
2530
2531   /* Backend specific symbol fixup.  */
2532   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2533   if (bed->elf_backend_fixup_symbol
2534       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2535     return FALSE;
2536
2537   /* If this is a final link, and the symbol was defined as a common
2538      symbol in a regular object file, and there was no definition in
2539      any dynamic object, then the linker will have allocated space for
2540      the symbol in a common section but the DEF_REGULAR
2541      flag will not have been set.  */
2542   if (h->root.type == bfd_link_hash_defined
2543       && !h->def_regular
2544       && h->ref_regular
2545       && !h->def_dynamic
2546       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2547     h->def_regular = 1;
2548
2549   /* If -Bsymbolic was used (which means to bind references to global
2550      symbols to the definition within the shared object), and this
2551      symbol was defined in a regular object, then it actually doesn't
2552      need a PLT entry.  Likewise, if the symbol has non-default
2553      visibility.  If the symbol has hidden or internal visibility, we
2554      will force it local.  */
2555   if (h->needs_plt
2556       && eif->info->shared
2557       && is_elf_hash_table (eif->info->hash)
2558       && (SYMBOLIC_BIND (eif->info, h)
2559           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2560       && h->def_regular)
2561     {
2562       bfd_boolean force_local;
2563
2564       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2565                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2566       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2567     }
2568
2569   /* If a weak undefined symbol has non-default visibility, we also
2570      hide it from the dynamic linker.  */
2571   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2572       && h->root.type == bfd_link_hash_undefweak)
2573     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2574
2575   /* If this is a weak defined symbol in a dynamic object, and we know
2576      the real definition in the dynamic object, copy interesting flags
2577      over to the real definition.  */
2578   if (h->u.weakdef != NULL)
2579     {
2580       /* If the real definition is defined by a regular object file,
2581          don't do anything special.  See the longer description in
2582          _bfd_elf_adjust_dynamic_symbol, below.  */
2583       if (h->u.weakdef->def_regular)
2584         h->u.weakdef = NULL;
2585       else
2586         {
2587           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2588
2589           while (h->root.type == bfd_link_hash_indirect)
2590             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2591
2592           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2593                       || h->root.type == bfd_link_hash_defweak);
2594           BFD_ASSERT (weakdef->def_dynamic);
2595           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2596                       || weakdef->root.type == bfd_link_hash_defweak);
2597           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2598         }
2599     }
2600
2601   return TRUE;
2602 }
2603
2604 /* Make the backend pick a good value for a dynamic symbol.  This is
2605    called via elf_link_hash_traverse, and also calls itself
2606    recursively.  */
2607
2608 static bfd_boolean
2609 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2610 {
2611   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2612   bfd *dynobj;
2613   const struct elf_backend_data *bed;
2614
2615   if (! is_elf_hash_table (eif->info->hash))
2616     return FALSE;
2617
2618   /* Ignore indirect symbols.  These are added by the versioning code.  */
2619   if (h->root.type == bfd_link_hash_indirect)
2620     return TRUE;
2621
2622   /* Fix the symbol flags.  */
2623   if (! _bfd_elf_fix_symbol_flags (h, eif))
2624     return FALSE;
2625
2626   /* If this symbol does not require a PLT entry, and it is not
2627      defined by a dynamic object, or is not referenced by a regular
2628      object, ignore it.  We do have to handle a weak defined symbol,
2629      even if no regular object refers to it, if we decided to add it
2630      to the dynamic symbol table.  FIXME: Do we normally need to worry
2631      about symbols which are defined by one dynamic object and
2632      referenced by another one?  */
2633   if (!h->needs_plt
2634       && h->type != STT_GNU_IFUNC
2635       && (h->def_regular
2636           || !h->def_dynamic
2637           || (!h->ref_regular
2638               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2639     {
2640       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2641       return TRUE;
2642     }
2643
2644   /* If we've already adjusted this symbol, don't do it again.  This
2645      can happen via a recursive call.  */
2646   if (h->dynamic_adjusted)
2647     return TRUE;
2648
2649   /* Don't look at this symbol again.  Note that we must set this
2650      after checking the above conditions, because we may look at a
2651      symbol once, decide not to do anything, and then get called
2652      recursively later after REF_REGULAR is set below.  */
2653   h->dynamic_adjusted = 1;
2654
2655   /* If this is a weak definition, and we know a real definition, and
2656      the real symbol is not itself defined by a regular object file,
2657      then get a good value for the real definition.  We handle the
2658      real symbol first, for the convenience of the backend routine.
2659
2660      Note that there is a confusing case here.  If the real definition
2661      is defined by a regular object file, we don't get the real symbol
2662      from the dynamic object, but we do get the weak symbol.  If the
2663      processor backend uses a COPY reloc, then if some routine in the
2664      dynamic object changes the real symbol, we will not see that
2665      change in the corresponding weak symbol.  This is the way other
2666      ELF linkers work as well, and seems to be a result of the shared
2667      library model.
2668
2669      I will clarify this issue.  Most SVR4 shared libraries define the
2670      variable _timezone and define timezone as a weak synonym.  The
2671      tzset call changes _timezone.  If you write
2672        extern int timezone;
2673        int _timezone = 5;
2674        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2675      you might expect that, since timezone is a synonym for _timezone,
2676      the same number will print both times.  However, if the processor
2677      backend uses a COPY reloc, then actually timezone will be copied
2678      into your process image, and, since you define _timezone
2679      yourself, _timezone will not.  Thus timezone and _timezone will
2680      wind up at different memory locations.  The tzset call will set
2681      _timezone, leaving timezone unchanged.  */
2682
2683   if (h->u.weakdef != NULL)
2684     {
2685       /* If we get to this point, there is an implicit reference to
2686          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2687       h->u.weakdef->ref_regular = 1;
2688
2689       /* Ensure that the backend adjust_dynamic_symbol function sees
2690          H->U.WEAKDEF before H by recursively calling ourselves.  */
2691       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2692         return FALSE;
2693     }
2694
2695   /* If a symbol has no type and no size and does not require a PLT
2696      entry, then we are probably about to do the wrong thing here: we
2697      are probably going to create a COPY reloc for an empty object.
2698      This case can arise when a shared object is built with assembly
2699      code, and the assembly code fails to set the symbol type.  */
2700   if (h->size == 0
2701       && h->type == STT_NOTYPE
2702       && !h->needs_plt)
2703     (*_bfd_error_handler)
2704       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2705        h->root.root.string);
2706
2707   dynobj = elf_hash_table (eif->info)->dynobj;
2708   bed = get_elf_backend_data (dynobj);
2709
2710   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2711     {
2712       eif->failed = TRUE;
2713       return FALSE;
2714     }
2715
2716   return TRUE;
2717 }
2718
2719 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2720    DYNBSS.  */
2721
2722 bfd_boolean
2723 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2724                               struct elf_link_hash_entry *h,
2725                               asection *dynbss)
2726 {
2727   unsigned int power_of_two;
2728   bfd_vma mask;
2729   asection *sec = h->root.u.def.section;
2730
2731   /* The section aligment of definition is the maximum alignment
2732      requirement of symbols defined in the section.  Since we don't
2733      know the symbol alignment requirement, we start with the
2734      maximum alignment and check low bits of the symbol address
2735      for the minimum alignment.  */
2736   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2737   mask = ((bfd_vma) 1 << power_of_two) - 1;
2738   while ((h->root.u.def.value & mask) != 0)
2739     {
2740        mask >>= 1;
2741        --power_of_two;
2742     }
2743
2744   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2745                                                 dynbss))
2746     {
2747       /* Adjust the section alignment if needed.  */
2748       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2749                                        power_of_two))
2750         return FALSE;
2751     }
2752
2753   /* We make sure that the symbol will be aligned properly.  */
2754   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2755
2756   /* Define the symbol as being at this point in DYNBSS.  */
2757   h->root.u.def.section = dynbss;
2758   h->root.u.def.value = dynbss->size;
2759
2760   /* Increment the size of DYNBSS to make room for the symbol.  */
2761   dynbss->size += h->size;
2762
2763   /* No error if extern_protected_data is true.  */
2764   if (h->protected_def
2765       && (!info->extern_protected_data
2766           || (info->extern_protected_data < 0
2767               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2768     info->callbacks->einfo
2769       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2770        h->root.root.string);
2771
2772   return TRUE;
2773 }
2774
2775 /* Adjust all external symbols pointing into SEC_MERGE sections
2776    to reflect the object merging within the sections.  */
2777
2778 static bfd_boolean
2779 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2780 {
2781   asection *sec;
2782
2783   if ((h->root.type == bfd_link_hash_defined
2784        || h->root.type == bfd_link_hash_defweak)
2785       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2786       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2787     {
2788       bfd *output_bfd = (bfd *) data;
2789
2790       h->root.u.def.value =
2791         _bfd_merged_section_offset (output_bfd,
2792                                     &h->root.u.def.section,
2793                                     elf_section_data (sec)->sec_info,
2794                                     h->root.u.def.value);
2795     }
2796
2797   return TRUE;
2798 }
2799
2800 /* Returns false if the symbol referred to by H should be considered
2801    to resolve local to the current module, and true if it should be
2802    considered to bind dynamically.  */
2803
2804 bfd_boolean
2805 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2806                            struct bfd_link_info *info,
2807                            bfd_boolean not_local_protected)
2808 {
2809   bfd_boolean binding_stays_local_p;
2810   const struct elf_backend_data *bed;
2811   struct elf_link_hash_table *hash_table;
2812
2813   if (h == NULL)
2814     return FALSE;
2815
2816   while (h->root.type == bfd_link_hash_indirect
2817          || h->root.type == bfd_link_hash_warning)
2818     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2819
2820   /* If it was forced local, then clearly it's not dynamic.  */
2821   if (h->dynindx == -1)
2822     return FALSE;
2823   if (h->forced_local)
2824     return FALSE;
2825
2826   /* Identify the cases where name binding rules say that a
2827      visible symbol resolves locally.  */
2828   binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2829
2830   switch (ELF_ST_VISIBILITY (h->other))
2831     {
2832     case STV_INTERNAL:
2833     case STV_HIDDEN:
2834       return FALSE;
2835
2836     case STV_PROTECTED:
2837       hash_table = elf_hash_table (info);
2838       if (!is_elf_hash_table (hash_table))
2839         return FALSE;
2840
2841       bed = get_elf_backend_data (hash_table->dynobj);
2842
2843       /* Proper resolution for function pointer equality may require
2844          that these symbols perhaps be resolved dynamically, even though
2845          we should be resolving them to the current module.  */
2846       if (!not_local_protected || !bed->is_function_type (h->type))
2847         binding_stays_local_p = TRUE;
2848       break;
2849
2850     default:
2851       break;
2852     }
2853
2854   /* If it isn't defined locally, then clearly it's dynamic.  */
2855   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2856     return TRUE;
2857
2858   /* Otherwise, the symbol is dynamic if binding rules don't tell
2859      us that it remains local.  */
2860   return !binding_stays_local_p;
2861 }
2862
2863 /* Return true if the symbol referred to by H should be considered
2864    to resolve local to the current module, and false otherwise.  Differs
2865    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2866    undefined symbols.  The two functions are virtually identical except
2867    for the place where forced_local and dynindx == -1 are tested.  If
2868    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2869    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2870    the symbol is local only for defined symbols.
2871    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2872    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2873    treatment of undefined weak symbols.  For those that do not make
2874    undefined weak symbols dynamic, both functions may return false.  */
2875
2876 bfd_boolean
2877 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2878                               struct bfd_link_info *info,
2879                               bfd_boolean local_protected)
2880 {
2881   const struct elf_backend_data *bed;
2882   struct elf_link_hash_table *hash_table;
2883
2884   /* If it's a local sym, of course we resolve locally.  */
2885   if (h == NULL)
2886     return TRUE;
2887
2888   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2889   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2890       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2891     return TRUE;
2892
2893   /* Common symbols that become definitions don't get the DEF_REGULAR
2894      flag set, so test it first, and don't bail out.  */
2895   if (ELF_COMMON_DEF_P (h))
2896     /* Do nothing.  */;
2897   /* If we don't have a definition in a regular file, then we can't
2898      resolve locally.  The sym is either undefined or dynamic.  */
2899   else if (!h->def_regular)
2900     return FALSE;
2901
2902   /* Forced local symbols resolve locally.  */
2903   if (h->forced_local)
2904     return TRUE;
2905
2906   /* As do non-dynamic symbols.  */
2907   if (h->dynindx == -1)
2908     return TRUE;
2909
2910   /* At this point, we know the symbol is defined and dynamic.  In an
2911      executable it must resolve locally, likewise when building symbolic
2912      shared libraries.  */
2913   if (info->executable || SYMBOLIC_BIND (info, h))
2914     return TRUE;
2915
2916   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2917      with default visibility might not resolve locally.  */
2918   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2919     return FALSE;
2920
2921   hash_table = elf_hash_table (info);
2922   if (!is_elf_hash_table (hash_table))
2923     return TRUE;
2924
2925   bed = get_elf_backend_data (hash_table->dynobj);
2926
2927   /* If extern_protected_data is false, STV_PROTECTED non-function
2928      symbols are local.  */
2929   if ((!info->extern_protected_data
2930        || (info->extern_protected_data < 0
2931            && !bed->extern_protected_data))
2932       && !bed->is_function_type (h->type))
2933     return TRUE;
2934
2935   /* Function pointer equality tests may require that STV_PROTECTED
2936      symbols be treated as dynamic symbols.  If the address of a
2937      function not defined in an executable is set to that function's
2938      plt entry in the executable, then the address of the function in
2939      a shared library must also be the plt entry in the executable.  */
2940   return local_protected;
2941 }
2942
2943 /* Caches some TLS segment info, and ensures that the TLS segment vma is
2944    aligned.  Returns the first TLS output section.  */
2945
2946 struct bfd_section *
2947 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2948 {
2949   struct bfd_section *sec, *tls;
2950   unsigned int align = 0;
2951
2952   for (sec = obfd->sections; sec != NULL; sec = sec->next)
2953     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2954       break;
2955   tls = sec;
2956
2957   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2958     if (sec->alignment_power > align)
2959       align = sec->alignment_power;
2960
2961   elf_hash_table (info)->tls_sec = tls;
2962
2963   /* Ensure the alignment of the first section is the largest alignment,
2964      so that the tls segment starts aligned.  */
2965   if (tls != NULL)
2966     tls->alignment_power = align;
2967
2968   return tls;
2969 }
2970
2971 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2972 static bfd_boolean
2973 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2974                                   Elf_Internal_Sym *sym)
2975 {
2976   const struct elf_backend_data *bed;
2977
2978   /* Local symbols do not count, but target specific ones might.  */
2979   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2980       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2981     return FALSE;
2982
2983   bed = get_elf_backend_data (abfd);
2984   /* Function symbols do not count.  */
2985   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
2986     return FALSE;
2987
2988   /* If the section is undefined, then so is the symbol.  */
2989   if (sym->st_shndx == SHN_UNDEF)
2990     return FALSE;
2991
2992   /* If the symbol is defined in the common section, then
2993      it is a common definition and so does not count.  */
2994   if (bed->common_definition (sym))
2995     return FALSE;
2996
2997   /* If the symbol is in a target specific section then we
2998      must rely upon the backend to tell us what it is.  */
2999   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3000     /* FIXME - this function is not coded yet:
3001
3002        return _bfd_is_global_symbol_definition (abfd, sym);
3003
3004        Instead for now assume that the definition is not global,
3005        Even if this is wrong, at least the linker will behave
3006        in the same way that it used to do.  */
3007     return FALSE;
3008
3009   return TRUE;
3010 }
3011
3012 /* Search the symbol table of the archive element of the archive ABFD
3013    whose archive map contains a mention of SYMDEF, and determine if
3014    the symbol is defined in this element.  */
3015 static bfd_boolean
3016 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3017 {
3018   Elf_Internal_Shdr * hdr;
3019   bfd_size_type symcount;
3020   bfd_size_type extsymcount;
3021   bfd_size_type extsymoff;
3022   Elf_Internal_Sym *isymbuf;
3023   Elf_Internal_Sym *isym;
3024   Elf_Internal_Sym *isymend;
3025   bfd_boolean result;
3026
3027   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3028   if (abfd == NULL)
3029     return FALSE;
3030
3031   /* Return FALSE if the object has been claimed by plugin.  */
3032   if (abfd->plugin_format == bfd_plugin_yes)
3033     return FALSE;
3034
3035   if (! bfd_check_format (abfd, bfd_object))
3036     return FALSE;
3037
3038   /* Select the appropriate symbol table.  */
3039   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3040     hdr = &elf_tdata (abfd)->symtab_hdr;
3041   else
3042     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3043
3044   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3045
3046   /* The sh_info field of the symtab header tells us where the
3047      external symbols start.  We don't care about the local symbols.  */
3048   if (elf_bad_symtab (abfd))
3049     {
3050       extsymcount = symcount;
3051       extsymoff = 0;
3052     }
3053   else
3054     {
3055       extsymcount = symcount - hdr->sh_info;
3056       extsymoff = hdr->sh_info;
3057     }
3058
3059   if (extsymcount == 0)
3060     return FALSE;
3061
3062   /* Read in the symbol table.  */
3063   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3064                                   NULL, NULL, NULL);
3065   if (isymbuf == NULL)
3066     return FALSE;
3067
3068   /* Scan the symbol table looking for SYMDEF.  */
3069   result = FALSE;
3070   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3071     {
3072       const char *name;
3073
3074       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3075                                               isym->st_name);
3076       if (name == NULL)
3077         break;
3078
3079       if (strcmp (name, symdef->name) == 0)
3080         {
3081           result = is_global_data_symbol_definition (abfd, isym);
3082           break;
3083         }
3084     }
3085
3086   free (isymbuf);
3087
3088   return result;
3089 }
3090 \f
3091 /* Add an entry to the .dynamic table.  */
3092
3093 bfd_boolean
3094 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3095                             bfd_vma tag,
3096                             bfd_vma val)
3097 {
3098   struct elf_link_hash_table *hash_table;
3099   const struct elf_backend_data *bed;
3100   asection *s;
3101   bfd_size_type newsize;
3102   bfd_byte *newcontents;
3103   Elf_Internal_Dyn dyn;
3104
3105   hash_table = elf_hash_table (info);
3106   if (! is_elf_hash_table (hash_table))
3107     return FALSE;
3108
3109   bed = get_elf_backend_data (hash_table->dynobj);
3110   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3111   BFD_ASSERT (s != NULL);
3112
3113   newsize = s->size + bed->s->sizeof_dyn;
3114   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3115   if (newcontents == NULL)
3116     return FALSE;
3117
3118   dyn.d_tag = tag;
3119   dyn.d_un.d_val = val;
3120   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3121
3122   s->size = newsize;
3123   s->contents = newcontents;
3124
3125   return TRUE;
3126 }
3127
3128 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3129    otherwise just check whether one already exists.  Returns -1 on error,
3130    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3131
3132 static int
3133 elf_add_dt_needed_tag (bfd *abfd,
3134                        struct bfd_link_info *info,
3135                        const char *soname,
3136                        bfd_boolean do_it)
3137 {
3138   struct elf_link_hash_table *hash_table;
3139   bfd_size_type strindex;
3140
3141   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3142     return -1;
3143
3144   hash_table = elf_hash_table (info);
3145   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3146   if (strindex == (bfd_size_type) -1)
3147     return -1;
3148
3149   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3150     {
3151       asection *sdyn;
3152       const struct elf_backend_data *bed;
3153       bfd_byte *extdyn;
3154
3155       bed = get_elf_backend_data (hash_table->dynobj);
3156       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3157       if (sdyn != NULL)
3158         for (extdyn = sdyn->contents;
3159              extdyn < sdyn->contents + sdyn->size;
3160              extdyn += bed->s->sizeof_dyn)
3161           {
3162             Elf_Internal_Dyn dyn;
3163
3164             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3165             if (dyn.d_tag == DT_NEEDED
3166                 && dyn.d_un.d_val == strindex)
3167               {
3168                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3169                 return 1;
3170               }
3171           }
3172     }
3173
3174   if (do_it)
3175     {
3176       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3177         return -1;
3178
3179       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3180         return -1;
3181     }
3182   else
3183     /* We were just checking for existence of the tag.  */
3184     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3185
3186   return 0;
3187 }
3188
3189 static bfd_boolean
3190 on_needed_list (const char *soname, struct bfd_link_needed_list *needed)
3191 {
3192   for (; needed != NULL; needed = needed->next)
3193     if ((elf_dyn_lib_class (needed->by) & DYN_AS_NEEDED) == 0
3194         && strcmp (soname, needed->name) == 0)
3195       return TRUE;
3196
3197   return FALSE;
3198 }
3199
3200 /* Sort symbol by value, section, and size.  */
3201 static int
3202 elf_sort_symbol (const void *arg1, const void *arg2)
3203 {
3204   const struct elf_link_hash_entry *h1;
3205   const struct elf_link_hash_entry *h2;
3206   bfd_signed_vma vdiff;
3207
3208   h1 = *(const struct elf_link_hash_entry **) arg1;
3209   h2 = *(const struct elf_link_hash_entry **) arg2;
3210   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3211   if (vdiff != 0)
3212     return vdiff > 0 ? 1 : -1;
3213   else
3214     {
3215       long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3216       if (sdiff != 0)
3217         return sdiff > 0 ? 1 : -1;
3218     }
3219   vdiff = h1->size - h2->size;
3220   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3221 }
3222
3223 /* This function is used to adjust offsets into .dynstr for
3224    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3225
3226 static bfd_boolean
3227 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3228 {
3229   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3230
3231   if (h->dynindx != -1)
3232     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3233   return TRUE;
3234 }
3235
3236 /* Assign string offsets in .dynstr, update all structures referencing
3237    them.  */
3238
3239 static bfd_boolean
3240 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3241 {
3242   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3243   struct elf_link_local_dynamic_entry *entry;
3244   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3245   bfd *dynobj = hash_table->dynobj;
3246   asection *sdyn;
3247   bfd_size_type size;
3248   const struct elf_backend_data *bed;
3249   bfd_byte *extdyn;
3250
3251   _bfd_elf_strtab_finalize (dynstr);
3252   size = _bfd_elf_strtab_size (dynstr);
3253
3254   bed = get_elf_backend_data (dynobj);
3255   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3256   BFD_ASSERT (sdyn != NULL);
3257
3258   /* Update all .dynamic entries referencing .dynstr strings.  */
3259   for (extdyn = sdyn->contents;
3260        extdyn < sdyn->contents + sdyn->size;
3261        extdyn += bed->s->sizeof_dyn)
3262     {
3263       Elf_Internal_Dyn dyn;
3264
3265       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3266       switch (dyn.d_tag)
3267         {
3268         case DT_STRSZ:
3269           dyn.d_un.d_val = size;
3270           break;
3271         case DT_NEEDED:
3272         case DT_SONAME:
3273         case DT_RPATH:
3274         case DT_RUNPATH:
3275         case DT_FILTER:
3276         case DT_AUXILIARY:
3277         case DT_AUDIT:
3278         case DT_DEPAUDIT:
3279           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3280           break;
3281         default:
3282           continue;
3283         }
3284       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3285     }
3286
3287   /* Now update local dynamic symbols.  */
3288   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3289     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3290                                                   entry->isym.st_name);
3291
3292   /* And the rest of dynamic symbols.  */
3293   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3294
3295   /* Adjust version definitions.  */
3296   if (elf_tdata (output_bfd)->cverdefs)
3297     {
3298       asection *s;
3299       bfd_byte *p;
3300       bfd_size_type i;
3301       Elf_Internal_Verdef def;
3302       Elf_Internal_Verdaux defaux;
3303
3304       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3305       p = s->contents;
3306       do
3307         {
3308           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3309                                    &def);
3310           p += sizeof (Elf_External_Verdef);
3311           if (def.vd_aux != sizeof (Elf_External_Verdef))
3312             continue;
3313           for (i = 0; i < def.vd_cnt; ++i)
3314             {
3315               _bfd_elf_swap_verdaux_in (output_bfd,
3316                                         (Elf_External_Verdaux *) p, &defaux);
3317               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3318                                                         defaux.vda_name);
3319               _bfd_elf_swap_verdaux_out (output_bfd,
3320                                          &defaux, (Elf_External_Verdaux *) p);
3321               p += sizeof (Elf_External_Verdaux);
3322             }
3323         }
3324       while (def.vd_next);
3325     }
3326
3327   /* Adjust version references.  */
3328   if (elf_tdata (output_bfd)->verref)
3329     {
3330       asection *s;
3331       bfd_byte *p;
3332       bfd_size_type i;
3333       Elf_Internal_Verneed need;
3334       Elf_Internal_Vernaux needaux;
3335
3336       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3337       p = s->contents;
3338       do
3339         {
3340           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3341                                     &need);
3342           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3343           _bfd_elf_swap_verneed_out (output_bfd, &need,
3344                                      (Elf_External_Verneed *) p);
3345           p += sizeof (Elf_External_Verneed);
3346           for (i = 0; i < need.vn_cnt; ++i)
3347             {
3348               _bfd_elf_swap_vernaux_in (output_bfd,
3349                                         (Elf_External_Vernaux *) p, &needaux);
3350               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3351                                                          needaux.vna_name);
3352               _bfd_elf_swap_vernaux_out (output_bfd,
3353                                          &needaux,
3354                                          (Elf_External_Vernaux *) p);
3355               p += sizeof (Elf_External_Vernaux);
3356             }
3357         }
3358       while (need.vn_next);
3359     }
3360
3361   return TRUE;
3362 }
3363 \f
3364 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3365    The default is to only match when the INPUT and OUTPUT are exactly
3366    the same target.  */
3367
3368 bfd_boolean
3369 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3370                                     const bfd_target *output)
3371 {
3372   return input == output;
3373 }
3374
3375 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3376    This version is used when different targets for the same architecture
3377    are virtually identical.  */
3378
3379 bfd_boolean
3380 _bfd_elf_relocs_compatible (const bfd_target *input,
3381                             const bfd_target *output)
3382 {
3383   const struct elf_backend_data *obed, *ibed;
3384
3385   if (input == output)
3386     return TRUE;
3387
3388   ibed = xvec_get_elf_backend_data (input);
3389   obed = xvec_get_elf_backend_data (output);
3390
3391   if (ibed->arch != obed->arch)
3392     return FALSE;
3393
3394   /* If both backends are using this function, deem them compatible.  */
3395   return ibed->relocs_compatible == obed->relocs_compatible;
3396 }
3397
3398 /* Make a special call to the linker "notice" function to tell it that
3399    we are about to handle an as-needed lib, or have finished
3400    processing the lib.  */ 
3401
3402 bfd_boolean
3403 _bfd_elf_notice_as_needed (bfd *ibfd,
3404                            struct bfd_link_info *info,
3405                            enum notice_asneeded_action act)
3406 {
3407   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3408 }
3409
3410 /* Add symbols from an ELF object file to the linker hash table.  */
3411
3412 static bfd_boolean
3413 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3414 {
3415   Elf_Internal_Ehdr *ehdr;
3416   Elf_Internal_Shdr *hdr;
3417   bfd_size_type symcount;
3418   bfd_size_type extsymcount;
3419   bfd_size_type extsymoff;
3420   struct elf_link_hash_entry **sym_hash;
3421   bfd_boolean dynamic;
3422   Elf_External_Versym *extversym = NULL;
3423   Elf_External_Versym *ever;
3424   struct elf_link_hash_entry *weaks;
3425   struct elf_link_hash_entry **nondeflt_vers = NULL;
3426   bfd_size_type nondeflt_vers_cnt = 0;
3427   Elf_Internal_Sym *isymbuf = NULL;
3428   Elf_Internal_Sym *isym;
3429   Elf_Internal_Sym *isymend;
3430   const struct elf_backend_data *bed;
3431   bfd_boolean add_needed;
3432   struct elf_link_hash_table *htab;
3433   bfd_size_type amt;
3434   void *alloc_mark = NULL;
3435   struct bfd_hash_entry **old_table = NULL;
3436   unsigned int old_size = 0;
3437   unsigned int old_count = 0;
3438   void *old_tab = NULL;
3439   void *old_ent;
3440   struct bfd_link_hash_entry *old_undefs = NULL;
3441   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3442   long old_dynsymcount = 0;
3443   bfd_size_type old_dynstr_size = 0;
3444   size_t tabsize = 0;
3445   asection *s;
3446   bfd_boolean just_syms;
3447
3448   htab = elf_hash_table (info);
3449   bed = get_elf_backend_data (abfd);
3450
3451   if ((abfd->flags & DYNAMIC) == 0)
3452     dynamic = FALSE;
3453   else
3454     {
3455       dynamic = TRUE;
3456
3457       /* You can't use -r against a dynamic object.  Also, there's no
3458          hope of using a dynamic object which does not exactly match
3459          the format of the output file.  */
3460       if (info->relocatable
3461           || !is_elf_hash_table (htab)
3462           || info->output_bfd->xvec != abfd->xvec)
3463         {
3464           if (info->relocatable)
3465             bfd_set_error (bfd_error_invalid_operation);
3466           else
3467             bfd_set_error (bfd_error_wrong_format);
3468           goto error_return;
3469         }
3470     }
3471
3472   ehdr = elf_elfheader (abfd);
3473   if (info->warn_alternate_em
3474       && bed->elf_machine_code != ehdr->e_machine
3475       && ((bed->elf_machine_alt1 != 0
3476            && ehdr->e_machine == bed->elf_machine_alt1)
3477           || (bed->elf_machine_alt2 != 0
3478               && ehdr->e_machine == bed->elf_machine_alt2)))
3479     info->callbacks->einfo
3480       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3481        ehdr->e_machine, abfd, bed->elf_machine_code);
3482
3483   /* As a GNU extension, any input sections which are named
3484      .gnu.warning.SYMBOL are treated as warning symbols for the given
3485      symbol.  This differs from .gnu.warning sections, which generate
3486      warnings when they are included in an output file.  */
3487   /* PR 12761: Also generate this warning when building shared libraries.  */
3488   for (s = abfd->sections; s != NULL; s = s->next)
3489     {
3490       const char *name;
3491
3492       name = bfd_get_section_name (abfd, s);
3493       if (CONST_STRNEQ (name, ".gnu.warning."))
3494         {
3495           char *msg;
3496           bfd_size_type sz;
3497
3498           name += sizeof ".gnu.warning." - 1;
3499
3500           /* If this is a shared object, then look up the symbol
3501              in the hash table.  If it is there, and it is already
3502              been defined, then we will not be using the entry
3503              from this shared object, so we don't need to warn.
3504              FIXME: If we see the definition in a regular object
3505              later on, we will warn, but we shouldn't.  The only
3506              fix is to keep track of what warnings we are supposed
3507              to emit, and then handle them all at the end of the
3508              link.  */
3509           if (dynamic)
3510             {
3511               struct elf_link_hash_entry *h;
3512
3513               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3514
3515               /* FIXME: What about bfd_link_hash_common?  */
3516               if (h != NULL
3517                   && (h->root.type == bfd_link_hash_defined
3518                       || h->root.type == bfd_link_hash_defweak))
3519                 continue;
3520             }
3521
3522           sz = s->size;
3523           msg = (char *) bfd_alloc (abfd, sz + 1);
3524           if (msg == NULL)
3525             goto error_return;
3526
3527           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3528             goto error_return;
3529
3530           msg[sz] = '\0';
3531
3532           if (! (_bfd_generic_link_add_one_symbol
3533                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3534                   FALSE, bed->collect, NULL)))
3535             goto error_return;
3536
3537           if (info->executable)
3538             {
3539               /* Clobber the section size so that the warning does
3540                  not get copied into the output file.  */
3541               s->size = 0;
3542
3543               /* Also set SEC_EXCLUDE, so that symbols defined in
3544                  the warning section don't get copied to the output.  */
3545               s->flags |= SEC_EXCLUDE;
3546             }
3547         }
3548     }
3549
3550   just_syms = ((s = abfd->sections) != NULL
3551                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3552
3553   add_needed = TRUE;
3554   if (! dynamic)
3555     {
3556       /* If we are creating a shared library, create all the dynamic
3557          sections immediately.  We need to attach them to something,
3558          so we attach them to this BFD, provided it is the right
3559          format and is not from ld --just-symbols.  FIXME: If there
3560          are no input BFD's of the same format as the output, we can't
3561          make a shared library.  */
3562       if (!just_syms
3563           && info->shared
3564           && is_elf_hash_table (htab)
3565           && info->output_bfd->xvec == abfd->xvec
3566           && !htab->dynamic_sections_created)
3567         {
3568           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3569             goto error_return;
3570         }
3571     }
3572   else if (!is_elf_hash_table (htab))
3573     goto error_return;
3574   else
3575     {
3576       const char *soname = NULL;
3577       char *audit = NULL;
3578       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3579       int ret;
3580
3581       /* ld --just-symbols and dynamic objects don't mix very well.
3582          ld shouldn't allow it.  */
3583       if (just_syms)
3584         abort ();
3585
3586       /* If this dynamic lib was specified on the command line with
3587          --as-needed in effect, then we don't want to add a DT_NEEDED
3588          tag unless the lib is actually used.  Similary for libs brought
3589          in by another lib's DT_NEEDED.  When --no-add-needed is used
3590          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3591          any dynamic library in DT_NEEDED tags in the dynamic lib at
3592          all.  */
3593       add_needed = (elf_dyn_lib_class (abfd)
3594                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3595                        | DYN_NO_NEEDED)) == 0;
3596
3597       s = bfd_get_section_by_name (abfd, ".dynamic");
3598       if (s != NULL)
3599         {
3600           bfd_byte *dynbuf;
3601           bfd_byte *extdyn;
3602           unsigned int elfsec;
3603           unsigned long shlink;
3604
3605           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3606             {
3607 error_free_dyn:
3608               free (dynbuf);
3609               goto error_return;
3610             }
3611
3612           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3613           if (elfsec == SHN_BAD)
3614             goto error_free_dyn;
3615           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3616
3617           for (extdyn = dynbuf;
3618                extdyn < dynbuf + s->size;
3619                extdyn += bed->s->sizeof_dyn)
3620             {
3621               Elf_Internal_Dyn dyn;
3622
3623               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3624               if (dyn.d_tag == DT_SONAME)
3625                 {
3626                   unsigned int tagv = dyn.d_un.d_val;
3627                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3628                   if (soname == NULL)
3629                     goto error_free_dyn;
3630                 }
3631               if (dyn.d_tag == DT_NEEDED)
3632                 {
3633                   struct bfd_link_needed_list *n, **pn;
3634                   char *fnm, *anm;
3635                   unsigned int tagv = dyn.d_un.d_val;
3636
3637                   amt = sizeof (struct bfd_link_needed_list);
3638                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3639                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3640                   if (n == NULL || fnm == NULL)
3641                     goto error_free_dyn;
3642                   amt = strlen (fnm) + 1;
3643                   anm = (char *) bfd_alloc (abfd, amt);
3644                   if (anm == NULL)
3645                     goto error_free_dyn;
3646                   memcpy (anm, fnm, amt);
3647                   n->name = anm;
3648                   n->by = abfd;
3649                   n->next = NULL;
3650                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3651                     ;
3652                   *pn = n;
3653                 }
3654               if (dyn.d_tag == DT_RUNPATH)
3655                 {
3656                   struct bfd_link_needed_list *n, **pn;
3657                   char *fnm, *anm;
3658                   unsigned int tagv = dyn.d_un.d_val;
3659
3660                   amt = sizeof (struct bfd_link_needed_list);
3661                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3662                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3663                   if (n == NULL || fnm == NULL)
3664                     goto error_free_dyn;
3665                   amt = strlen (fnm) + 1;
3666                   anm = (char *) bfd_alloc (abfd, amt);
3667                   if (anm == NULL)
3668                     goto error_free_dyn;
3669                   memcpy (anm, fnm, amt);
3670                   n->name = anm;
3671                   n->by = abfd;
3672                   n->next = NULL;
3673                   for (pn = & runpath;
3674                        *pn != NULL;
3675                        pn = &(*pn)->next)
3676                     ;
3677                   *pn = n;
3678                 }
3679               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3680               if (!runpath && dyn.d_tag == DT_RPATH)
3681                 {
3682                   struct bfd_link_needed_list *n, **pn;
3683                   char *fnm, *anm;
3684                   unsigned int tagv = dyn.d_un.d_val;
3685
3686                   amt = sizeof (struct bfd_link_needed_list);
3687                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3688                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3689                   if (n == NULL || fnm == NULL)
3690                     goto error_free_dyn;
3691                   amt = strlen (fnm) + 1;
3692                   anm = (char *) bfd_alloc (abfd, amt);
3693                   if (anm == NULL)
3694                     goto error_free_dyn;
3695                   memcpy (anm, fnm, amt);
3696                   n->name = anm;
3697                   n->by = abfd;
3698                   n->next = NULL;
3699                   for (pn = & rpath;
3700                        *pn != NULL;
3701                        pn = &(*pn)->next)
3702                     ;
3703                   *pn = n;
3704                 }
3705               if (dyn.d_tag == DT_AUDIT)
3706                 {
3707                   unsigned int tagv = dyn.d_un.d_val;
3708                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3709                 }
3710             }
3711
3712           free (dynbuf);
3713         }
3714
3715       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3716          frees all more recently bfd_alloc'd blocks as well.  */
3717       if (runpath)
3718         rpath = runpath;
3719
3720       if (rpath)
3721         {
3722           struct bfd_link_needed_list **pn;
3723           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3724             ;
3725           *pn = rpath;
3726         }
3727
3728       /* We do not want to include any of the sections in a dynamic
3729          object in the output file.  We hack by simply clobbering the
3730          list of sections in the BFD.  This could be handled more
3731          cleanly by, say, a new section flag; the existing
3732          SEC_NEVER_LOAD flag is not the one we want, because that one
3733          still implies that the section takes up space in the output
3734          file.  */
3735       bfd_section_list_clear (abfd);
3736
3737       /* Find the name to use in a DT_NEEDED entry that refers to this
3738          object.  If the object has a DT_SONAME entry, we use it.
3739          Otherwise, if the generic linker stuck something in
3740          elf_dt_name, we use that.  Otherwise, we just use the file
3741          name.  */
3742       if (soname == NULL || *soname == '\0')
3743         {
3744           soname = elf_dt_name (abfd);
3745           if (soname == NULL || *soname == '\0')
3746             soname = bfd_get_filename (abfd);
3747         }
3748
3749       /* Save the SONAME because sometimes the linker emulation code
3750          will need to know it.  */
3751       elf_dt_name (abfd) = soname;
3752
3753       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3754       if (ret < 0)
3755         goto error_return;
3756
3757       /* If we have already included this dynamic object in the
3758          link, just ignore it.  There is no reason to include a
3759          particular dynamic object more than once.  */
3760       if (ret > 0)
3761         return TRUE;
3762
3763       /* Save the DT_AUDIT entry for the linker emulation code. */
3764       elf_dt_audit (abfd) = audit;
3765     }
3766
3767   /* If this is a dynamic object, we always link against the .dynsym
3768      symbol table, not the .symtab symbol table.  The dynamic linker
3769      will only see the .dynsym symbol table, so there is no reason to
3770      look at .symtab for a dynamic object.  */
3771
3772   if (! dynamic || elf_dynsymtab (abfd) == 0)
3773     hdr = &elf_tdata (abfd)->symtab_hdr;
3774   else
3775     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3776
3777   symcount = hdr->sh_size / bed->s->sizeof_sym;
3778
3779   /* The sh_info field of the symtab header tells us where the
3780      external symbols start.  We don't care about the local symbols at
3781      this point.  */
3782   if (elf_bad_symtab (abfd))
3783     {
3784       extsymcount = symcount;
3785       extsymoff = 0;
3786     }
3787   else
3788     {
3789       extsymcount = symcount - hdr->sh_info;
3790       extsymoff = hdr->sh_info;
3791     }
3792
3793   sym_hash = elf_sym_hashes (abfd);
3794   if (extsymcount != 0)
3795     {
3796       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3797                                       NULL, NULL, NULL);
3798       if (isymbuf == NULL)
3799         goto error_return;
3800
3801       if (sym_hash == NULL)
3802         {
3803           /* We store a pointer to the hash table entry for each
3804              external symbol.  */
3805           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3806           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3807           if (sym_hash == NULL)
3808             goto error_free_sym;
3809           elf_sym_hashes (abfd) = sym_hash;
3810         }
3811     }
3812
3813   if (dynamic)
3814     {
3815       /* Read in any version definitions.  */
3816       if (!_bfd_elf_slurp_version_tables (abfd,
3817                                           info->default_imported_symver))
3818         goto error_free_sym;
3819
3820       /* Read in the symbol versions, but don't bother to convert them
3821          to internal format.  */
3822       if (elf_dynversym (abfd) != 0)
3823         {
3824           Elf_Internal_Shdr *versymhdr;
3825
3826           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3827           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3828           if (extversym == NULL)
3829             goto error_free_sym;
3830           amt = versymhdr->sh_size;
3831           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3832               || bfd_bread (extversym, amt, abfd) != amt)
3833             goto error_free_vers;
3834         }
3835     }
3836
3837   /* If we are loading an as-needed shared lib, save the symbol table
3838      state before we start adding symbols.  If the lib turns out
3839      to be unneeded, restore the state.  */
3840   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3841     {
3842       unsigned int i;
3843       size_t entsize;
3844
3845       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3846         {
3847           struct bfd_hash_entry *p;
3848           struct elf_link_hash_entry *h;
3849
3850           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3851             {
3852               h = (struct elf_link_hash_entry *) p;
3853               entsize += htab->root.table.entsize;
3854               if (h->root.type == bfd_link_hash_warning)
3855                 entsize += htab->root.table.entsize;
3856             }
3857         }
3858
3859       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3860       old_tab = bfd_malloc (tabsize + entsize);
3861       if (old_tab == NULL)
3862         goto error_free_vers;
3863
3864       /* Remember the current objalloc pointer, so that all mem for
3865          symbols added can later be reclaimed.  */
3866       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3867       if (alloc_mark == NULL)
3868         goto error_free_vers;
3869
3870       /* Make a special call to the linker "notice" function to
3871          tell it that we are about to handle an as-needed lib.  */
3872       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
3873         goto error_free_vers;
3874
3875       /* Clone the symbol table.  Remember some pointers into the
3876          symbol table, and dynamic symbol count.  */
3877       old_ent = (char *) old_tab + tabsize;
3878       memcpy (old_tab, htab->root.table.table, tabsize);
3879       old_undefs = htab->root.undefs;
3880       old_undefs_tail = htab->root.undefs_tail;
3881       old_table = htab->root.table.table;
3882       old_size = htab->root.table.size;
3883       old_count = htab->root.table.count;
3884       old_dynsymcount = htab->dynsymcount;
3885       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
3886
3887       for (i = 0; i < htab->root.table.size; i++)
3888         {
3889           struct bfd_hash_entry *p;
3890           struct elf_link_hash_entry *h;
3891
3892           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3893             {
3894               memcpy (old_ent, p, htab->root.table.entsize);
3895               old_ent = (char *) old_ent + htab->root.table.entsize;
3896               h = (struct elf_link_hash_entry *) p;
3897               if (h->root.type == bfd_link_hash_warning)
3898                 {
3899                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3900                   old_ent = (char *) old_ent + htab->root.table.entsize;
3901                 }
3902             }
3903         }
3904     }
3905
3906   weaks = NULL;
3907   ever = extversym != NULL ? extversym + extsymoff : NULL;
3908   for (isym = isymbuf, isymend = isymbuf + extsymcount;
3909        isym < isymend;
3910        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3911     {
3912       int bind;
3913       bfd_vma value;
3914       asection *sec, *new_sec;
3915       flagword flags;
3916       const char *name;
3917       struct elf_link_hash_entry *h;
3918       struct elf_link_hash_entry *hi;
3919       bfd_boolean definition;
3920       bfd_boolean size_change_ok;
3921       bfd_boolean type_change_ok;
3922       bfd_boolean new_weakdef;
3923       bfd_boolean new_weak;
3924       bfd_boolean old_weak;
3925       bfd_boolean override;
3926       bfd_boolean common;
3927       unsigned int old_alignment;
3928       bfd *old_bfd;
3929       bfd_boolean matched;
3930
3931       override = FALSE;
3932
3933       flags = BSF_NO_FLAGS;
3934       sec = NULL;
3935       value = isym->st_value;
3936       common = bed->common_definition (isym);
3937
3938       bind = ELF_ST_BIND (isym->st_info);
3939       switch (bind)
3940         {
3941         case STB_LOCAL:
3942           /* This should be impossible, since ELF requires that all
3943              global symbols follow all local symbols, and that sh_info
3944              point to the first global symbol.  Unfortunately, Irix 5
3945              screws this up.  */
3946           continue;
3947
3948         case STB_GLOBAL:
3949           if (isym->st_shndx != SHN_UNDEF && !common)
3950             flags = BSF_GLOBAL;
3951           break;
3952
3953         case STB_WEAK:
3954           flags = BSF_WEAK;
3955           break;
3956
3957         case STB_GNU_UNIQUE:
3958           flags = BSF_GNU_UNIQUE;
3959           break;
3960
3961         default:
3962           /* Leave it up to the processor backend.  */
3963           break;
3964         }
3965
3966       if (isym->st_shndx == SHN_UNDEF)
3967         sec = bfd_und_section_ptr;
3968       else if (isym->st_shndx == SHN_ABS)
3969         sec = bfd_abs_section_ptr;
3970       else if (isym->st_shndx == SHN_COMMON)
3971         {
3972           sec = bfd_com_section_ptr;
3973           /* What ELF calls the size we call the value.  What ELF
3974              calls the value we call the alignment.  */
3975           value = isym->st_size;
3976         }
3977       else
3978         {
3979           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3980           if (sec == NULL)
3981             sec = bfd_abs_section_ptr;
3982           else if (discarded_section (sec))
3983             {
3984               /* Symbols from discarded section are undefined.  We keep
3985                  its visibility.  */
3986               sec = bfd_und_section_ptr;
3987               isym->st_shndx = SHN_UNDEF;
3988             }
3989           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3990             value -= sec->vma;
3991         }
3992
3993       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3994                                               isym->st_name);
3995       if (name == NULL)
3996         goto error_free_vers;
3997
3998       if (isym->st_shndx == SHN_COMMON
3999           && (abfd->flags & BFD_PLUGIN) != 0)
4000         {
4001           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4002
4003           if (xc == NULL)
4004             {
4005               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4006                                  | SEC_EXCLUDE);
4007               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4008               if (xc == NULL)
4009                 goto error_free_vers;
4010             }
4011           sec = xc;
4012         }
4013       else if (isym->st_shndx == SHN_COMMON
4014                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4015                && !info->relocatable)
4016         {
4017           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4018
4019           if (tcomm == NULL)
4020             {
4021               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4022                                  | SEC_LINKER_CREATED);
4023               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4024               if (tcomm == NULL)
4025                 goto error_free_vers;
4026             }
4027           sec = tcomm;
4028         }
4029       else if (bed->elf_add_symbol_hook)
4030         {
4031           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4032                                              &sec, &value))
4033             goto error_free_vers;
4034
4035           /* The hook function sets the name to NULL if this symbol
4036              should be skipped for some reason.  */
4037           if (name == NULL)
4038             continue;
4039         }
4040
4041       /* Sanity check that all possibilities were handled.  */
4042       if (sec == NULL)
4043         {
4044           bfd_set_error (bfd_error_bad_value);
4045           goto error_free_vers;
4046         }
4047
4048       /* Silently discard TLS symbols from --just-syms.  There's
4049          no way to combine a static TLS block with a new TLS block
4050          for this executable.  */
4051       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4052           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4053         continue;
4054
4055       if (bfd_is_und_section (sec)
4056           || bfd_is_com_section (sec))
4057         definition = FALSE;
4058       else
4059         definition = TRUE;
4060
4061       size_change_ok = FALSE;
4062       type_change_ok = bed->type_change_ok;
4063       old_weak = FALSE;
4064       matched = FALSE;
4065       old_alignment = 0;
4066       old_bfd = NULL;
4067       new_sec = sec;
4068
4069       if (is_elf_hash_table (htab))
4070         {
4071           Elf_Internal_Versym iver;
4072           unsigned int vernum = 0;
4073           bfd_boolean skip;
4074
4075           if (ever == NULL)
4076             {
4077               if (info->default_imported_symver)
4078                 /* Use the default symbol version created earlier.  */
4079                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4080               else
4081                 iver.vs_vers = 0;
4082             }
4083           else
4084             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4085
4086           vernum = iver.vs_vers & VERSYM_VERSION;
4087
4088           /* If this is a hidden symbol, or if it is not version
4089              1, we append the version name to the symbol name.
4090              However, we do not modify a non-hidden absolute symbol
4091              if it is not a function, because it might be the version
4092              symbol itself.  FIXME: What if it isn't?  */
4093           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4094               || (vernum > 1
4095                   && (!bfd_is_abs_section (sec)
4096                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4097             {
4098               const char *verstr;
4099               size_t namelen, verlen, newlen;
4100               char *newname, *p;
4101
4102               if (isym->st_shndx != SHN_UNDEF)
4103                 {
4104                   if (vernum > elf_tdata (abfd)->cverdefs)
4105                     verstr = NULL;
4106                   else if (vernum > 1)
4107                     verstr =
4108                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4109                   else
4110                     verstr = "";
4111
4112                   if (verstr == NULL)
4113                     {
4114                       (*_bfd_error_handler)
4115                         (_("%B: %s: invalid version %u (max %d)"),
4116                          abfd, name, vernum,
4117                          elf_tdata (abfd)->cverdefs);
4118                       bfd_set_error (bfd_error_bad_value);
4119                       goto error_free_vers;
4120                     }
4121                 }
4122               else
4123                 {
4124                   /* We cannot simply test for the number of
4125                      entries in the VERNEED section since the
4126                      numbers for the needed versions do not start
4127                      at 0.  */
4128                   Elf_Internal_Verneed *t;
4129
4130                   verstr = NULL;
4131                   for (t = elf_tdata (abfd)->verref;
4132                        t != NULL;
4133                        t = t->vn_nextref)
4134                     {
4135                       Elf_Internal_Vernaux *a;
4136
4137                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4138                         {
4139                           if (a->vna_other == vernum)
4140                             {
4141                               verstr = a->vna_nodename;
4142                               break;
4143                             }
4144                         }
4145                       if (a != NULL)
4146                         break;
4147                     }
4148                   if (verstr == NULL)
4149                     {
4150                       (*_bfd_error_handler)
4151                         (_("%B: %s: invalid needed version %d"),
4152                          abfd, name, vernum);
4153                       bfd_set_error (bfd_error_bad_value);
4154                       goto error_free_vers;
4155                     }
4156                 }
4157
4158               namelen = strlen (name);
4159               verlen = strlen (verstr);
4160               newlen = namelen + verlen + 2;
4161               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4162                   && isym->st_shndx != SHN_UNDEF)
4163                 ++newlen;
4164
4165               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4166               if (newname == NULL)
4167                 goto error_free_vers;
4168               memcpy (newname, name, namelen);
4169               p = newname + namelen;
4170               *p++ = ELF_VER_CHR;
4171               /* If this is a defined non-hidden version symbol,
4172                  we add another @ to the name.  This indicates the
4173                  default version of the symbol.  */
4174               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4175                   && isym->st_shndx != SHN_UNDEF)
4176                 *p++ = ELF_VER_CHR;
4177               memcpy (p, verstr, verlen + 1);
4178
4179               name = newname;
4180             }
4181
4182           /* If this symbol has default visibility and the user has
4183              requested we not re-export it, then mark it as hidden.  */
4184           if (definition
4185               && !dynamic
4186               && abfd->no_export
4187               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4188             isym->st_other = (STV_HIDDEN
4189                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4190
4191           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4192                                       sym_hash, &old_bfd, &old_weak,
4193                                       &old_alignment, &skip, &override,
4194                                       &type_change_ok, &size_change_ok,
4195                                       &matched))
4196             goto error_free_vers;
4197
4198           if (skip)
4199             continue;
4200
4201           /* Override a definition only if the new symbol matches the
4202              existing one.  */
4203           if (override && matched)
4204             definition = FALSE;
4205
4206           h = *sym_hash;
4207           while (h->root.type == bfd_link_hash_indirect
4208                  || h->root.type == bfd_link_hash_warning)
4209             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4210
4211           if (elf_tdata (abfd)->verdef != NULL
4212               && vernum > 1
4213               && definition)
4214             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4215         }
4216
4217       if (! (_bfd_generic_link_add_one_symbol
4218              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4219               (struct bfd_link_hash_entry **) sym_hash)))
4220         goto error_free_vers;
4221
4222       h = *sym_hash;
4223       /* We need to make sure that indirect symbol dynamic flags are
4224          updated.  */
4225       hi = h;
4226       while (h->root.type == bfd_link_hash_indirect
4227              || h->root.type == bfd_link_hash_warning)
4228         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4229
4230       *sym_hash = h;
4231
4232       new_weak = (flags & BSF_WEAK) != 0;
4233       new_weakdef = FALSE;
4234       if (dynamic
4235           && definition
4236           && new_weak
4237           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4238           && is_elf_hash_table (htab)
4239           && h->u.weakdef == NULL)
4240         {
4241           /* Keep a list of all weak defined non function symbols from
4242              a dynamic object, using the weakdef field.  Later in this
4243              function we will set the weakdef field to the correct
4244              value.  We only put non-function symbols from dynamic
4245              objects on this list, because that happens to be the only
4246              time we need to know the normal symbol corresponding to a
4247              weak symbol, and the information is time consuming to
4248              figure out.  If the weakdef field is not already NULL,
4249              then this symbol was already defined by some previous
4250              dynamic object, and we will be using that previous
4251              definition anyhow.  */
4252
4253           h->u.weakdef = weaks;
4254           weaks = h;
4255           new_weakdef = TRUE;
4256         }
4257
4258       /* Set the alignment of a common symbol.  */
4259       if ((common || bfd_is_com_section (sec))
4260           && h->root.type == bfd_link_hash_common)
4261         {
4262           unsigned int align;
4263
4264           if (common)
4265             align = bfd_log2 (isym->st_value);
4266           else
4267             {
4268               /* The new symbol is a common symbol in a shared object.
4269                  We need to get the alignment from the section.  */
4270               align = new_sec->alignment_power;
4271             }
4272           if (align > old_alignment)
4273             h->root.u.c.p->alignment_power = align;
4274           else
4275             h->root.u.c.p->alignment_power = old_alignment;
4276         }
4277
4278       if (is_elf_hash_table (htab))
4279         {
4280           /* Set a flag in the hash table entry indicating the type of
4281              reference or definition we just found.  A dynamic symbol
4282              is one which is referenced or defined by both a regular
4283              object and a shared object.  */
4284           bfd_boolean dynsym = FALSE;
4285
4286           /* Plugin symbols aren't normal.  Don't set def_regular or
4287              ref_regular for them, or make them dynamic.  */
4288           if ((abfd->flags & BFD_PLUGIN) != 0)
4289             ;
4290           else if (! dynamic)
4291             {
4292               if (! definition)
4293                 {
4294                   h->ref_regular = 1;
4295                   if (bind != STB_WEAK)
4296                     h->ref_regular_nonweak = 1;
4297                 }
4298               else
4299                 {
4300                   h->def_regular = 1;
4301                   if (h->def_dynamic)
4302                     {
4303                       h->def_dynamic = 0;
4304                       h->ref_dynamic = 1;
4305                     }
4306                 }
4307
4308               /* If the indirect symbol has been forced local, don't
4309                  make the real symbol dynamic.  */
4310               if ((h == hi || !hi->forced_local)
4311                   && ((! info->executable && ! info->relocatable)
4312                       || h->def_dynamic
4313                       || h->ref_dynamic))
4314                 dynsym = TRUE;
4315             }
4316           else
4317             {
4318               if (! definition)
4319                 {
4320                   h->ref_dynamic = 1;
4321                   hi->ref_dynamic = 1;
4322                 }
4323               else
4324                 {
4325                   h->def_dynamic = 1;
4326                   hi->def_dynamic = 1;
4327                 }
4328
4329               /* If the indirect symbol has been forced local, don't
4330                  make the real symbol dynamic.  */
4331               if ((h == hi || !hi->forced_local)
4332                   && (h->def_regular
4333                       || h->ref_regular
4334                       || (h->u.weakdef != NULL
4335                           && ! new_weakdef
4336                           && h->u.weakdef->dynindx != -1)))
4337                 dynsym = TRUE;
4338             }
4339
4340           /* Check to see if we need to add an indirect symbol for
4341              the default name.  */
4342           if (definition
4343               || (!override && h->root.type == bfd_link_hash_common))
4344             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4345                                               sec, value, &old_bfd, &dynsym))
4346               goto error_free_vers;
4347
4348           /* Check the alignment when a common symbol is involved. This
4349              can change when a common symbol is overridden by a normal
4350              definition or a common symbol is ignored due to the old
4351              normal definition. We need to make sure the maximum
4352              alignment is maintained.  */
4353           if ((old_alignment || common)
4354               && h->root.type != bfd_link_hash_common)
4355             {
4356               unsigned int common_align;
4357               unsigned int normal_align;
4358               unsigned int symbol_align;
4359               bfd *normal_bfd;
4360               bfd *common_bfd;
4361
4362               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4363                           || h->root.type == bfd_link_hash_defweak);
4364
4365               symbol_align = ffs (h->root.u.def.value) - 1;
4366               if (h->root.u.def.section->owner != NULL
4367                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4368                 {
4369                   normal_align = h->root.u.def.section->alignment_power;
4370                   if (normal_align > symbol_align)
4371                     normal_align = symbol_align;
4372                 }
4373               else
4374                 normal_align = symbol_align;
4375
4376               if (old_alignment)
4377                 {
4378                   common_align = old_alignment;
4379                   common_bfd = old_bfd;
4380                   normal_bfd = abfd;
4381                 }
4382               else
4383                 {
4384                   common_align = bfd_log2 (isym->st_value);
4385                   common_bfd = abfd;
4386                   normal_bfd = old_bfd;
4387                 }
4388
4389               if (normal_align < common_align)
4390                 {
4391                   /* PR binutils/2735 */
4392                   if (normal_bfd == NULL)
4393                     (*_bfd_error_handler)
4394                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4395                          " greater than the alignment (%u) of its section %A"),
4396                        common_bfd, h->root.u.def.section,
4397                        1 << common_align, name, 1 << normal_align);
4398                   else
4399                     (*_bfd_error_handler)
4400                       (_("Warning: alignment %u of symbol `%s' in %B"
4401                          " is smaller than %u in %B"),
4402                        normal_bfd, common_bfd,
4403                        1 << normal_align, name, 1 << common_align);
4404                 }
4405             }
4406
4407           /* Remember the symbol size if it isn't undefined.  */
4408           if (isym->st_size != 0
4409               && isym->st_shndx != SHN_UNDEF
4410               && (definition || h->size == 0))
4411             {
4412               if (h->size != 0
4413                   && h->size != isym->st_size
4414                   && ! size_change_ok)
4415                 (*_bfd_error_handler)
4416                   (_("Warning: size of symbol `%s' changed"
4417                      " from %lu in %B to %lu in %B"),
4418                    old_bfd, abfd,
4419                    name, (unsigned long) h->size,
4420                    (unsigned long) isym->st_size);
4421
4422               h->size = isym->st_size;
4423             }
4424
4425           /* If this is a common symbol, then we always want H->SIZE
4426              to be the size of the common symbol.  The code just above
4427              won't fix the size if a common symbol becomes larger.  We
4428              don't warn about a size change here, because that is
4429              covered by --warn-common.  Allow changes between different
4430              function types.  */
4431           if (h->root.type == bfd_link_hash_common)
4432             h->size = h->root.u.c.size;
4433
4434           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4435               && ((definition && !new_weak)
4436                   || (old_weak && h->root.type == bfd_link_hash_common)
4437                   || h->type == STT_NOTYPE))
4438             {
4439               unsigned int type = ELF_ST_TYPE (isym->st_info);
4440
4441               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4442                  symbol.  */
4443               if (type == STT_GNU_IFUNC
4444                   && (abfd->flags & DYNAMIC) != 0)
4445                 type = STT_FUNC;
4446
4447               if (h->type != type)
4448                 {
4449                   if (h->type != STT_NOTYPE && ! type_change_ok)
4450                     (*_bfd_error_handler)
4451                       (_("Warning: type of symbol `%s' changed"
4452                          " from %d to %d in %B"),
4453                        abfd, name, h->type, type);
4454
4455                   h->type = type;
4456                 }
4457             }
4458
4459           /* Merge st_other field.  */
4460           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4461
4462           /* We don't want to make debug symbol dynamic.  */
4463           if (definition && (sec->flags & SEC_DEBUGGING) && !info->relocatable)
4464             dynsym = FALSE;
4465
4466           /* Nor should we make plugin symbols dynamic.  */
4467           if ((abfd->flags & BFD_PLUGIN) != 0)
4468             dynsym = FALSE;
4469
4470           if (definition)
4471             {
4472               h->target_internal = isym->st_target_internal;
4473               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4474             }
4475
4476           if (definition && !dynamic)
4477             {
4478               char *p = strchr (name, ELF_VER_CHR);
4479               if (p != NULL && p[1] != ELF_VER_CHR)
4480                 {
4481                   /* Queue non-default versions so that .symver x, x@FOO
4482                      aliases can be checked.  */
4483                   if (!nondeflt_vers)
4484                     {
4485                       amt = ((isymend - isym + 1)
4486                              * sizeof (struct elf_link_hash_entry *));
4487                       nondeflt_vers
4488                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4489                       if (!nondeflt_vers)
4490                         goto error_free_vers;
4491                     }
4492                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4493                 }
4494             }
4495
4496           if (dynsym && h->dynindx == -1)
4497             {
4498               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4499                 goto error_free_vers;
4500               if (h->u.weakdef != NULL
4501                   && ! new_weakdef
4502                   && h->u.weakdef->dynindx == -1)
4503                 {
4504                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4505                     goto error_free_vers;
4506                 }
4507             }
4508           else if (dynsym && h->dynindx != -1)
4509             /* If the symbol already has a dynamic index, but
4510                visibility says it should not be visible, turn it into
4511                a local symbol.  */
4512             switch (ELF_ST_VISIBILITY (h->other))
4513               {
4514               case STV_INTERNAL:
4515               case STV_HIDDEN:
4516                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4517                 dynsym = FALSE;
4518                 break;
4519               }
4520
4521           /* Don't add DT_NEEDED for references from the dummy bfd.  */
4522           if (!add_needed
4523               && definition
4524               && ((dynsym
4525                    && h->ref_regular_nonweak
4526                    && (old_bfd == NULL
4527                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4528                   || (h->ref_dynamic_nonweak
4529                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4530                       && !on_needed_list (elf_dt_name (abfd), htab->needed))))
4531             {
4532               int ret;
4533               const char *soname = elf_dt_name (abfd);
4534
4535               info->callbacks->minfo ("%!", soname, old_bfd,
4536                                       h->root.root.string);
4537
4538               /* A symbol from a library loaded via DT_NEEDED of some
4539                  other library is referenced by a regular object.
4540                  Add a DT_NEEDED entry for it.  Issue an error if
4541                  --no-add-needed is used and the reference was not
4542                  a weak one.  */
4543               if (old_bfd != NULL
4544                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4545                 {
4546                   (*_bfd_error_handler)
4547                     (_("%B: undefined reference to symbol '%s'"),
4548                      old_bfd, name);
4549                   bfd_set_error (bfd_error_missing_dso);
4550                   goto error_free_vers;
4551                 }
4552
4553               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4554                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4555
4556               add_needed = TRUE;
4557               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4558               if (ret < 0)
4559                 goto error_free_vers;
4560
4561               BFD_ASSERT (ret == 0);
4562             }
4563         }
4564     }
4565
4566   if (extversym != NULL)
4567     {
4568       free (extversym);
4569       extversym = NULL;
4570     }
4571
4572   if (isymbuf != NULL)
4573     {
4574       free (isymbuf);
4575       isymbuf = NULL;
4576     }
4577
4578   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4579     {
4580       unsigned int i;
4581
4582       /* Restore the symbol table.  */
4583       old_ent = (char *) old_tab + tabsize;
4584       memset (elf_sym_hashes (abfd), 0,
4585               extsymcount * sizeof (struct elf_link_hash_entry *));
4586       htab->root.table.table = old_table;
4587       htab->root.table.size = old_size;
4588       htab->root.table.count = old_count;
4589       memcpy (htab->root.table.table, old_tab, tabsize);
4590       htab->root.undefs = old_undefs;
4591       htab->root.undefs_tail = old_undefs_tail;
4592       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4593       for (i = 0; i < htab->root.table.size; i++)
4594         {
4595           struct bfd_hash_entry *p;
4596           struct elf_link_hash_entry *h;
4597           bfd_size_type size;
4598           unsigned int alignment_power;
4599
4600           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4601             {
4602               h = (struct elf_link_hash_entry *) p;
4603               if (h->root.type == bfd_link_hash_warning)
4604                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4605               if (h->dynindx >= old_dynsymcount
4606                   && h->dynstr_index < old_dynstr_size)
4607                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4608
4609               /* Preserve the maximum alignment and size for common
4610                  symbols even if this dynamic lib isn't on DT_NEEDED
4611                  since it can still be loaded at run time by another
4612                  dynamic lib.  */
4613               if (h->root.type == bfd_link_hash_common)
4614                 {
4615                   size = h->root.u.c.size;
4616                   alignment_power = h->root.u.c.p->alignment_power;
4617                 }
4618               else
4619                 {
4620                   size = 0;
4621                   alignment_power = 0;
4622                 }
4623               memcpy (p, old_ent, htab->root.table.entsize);
4624               old_ent = (char *) old_ent + htab->root.table.entsize;
4625               h = (struct elf_link_hash_entry *) p;
4626               if (h->root.type == bfd_link_hash_warning)
4627                 {
4628                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4629                   old_ent = (char *) old_ent + htab->root.table.entsize;
4630                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4631                 }
4632               if (h->root.type == bfd_link_hash_common)
4633                 {
4634                   if (size > h->root.u.c.size)
4635                     h->root.u.c.size = size;
4636                   if (alignment_power > h->root.u.c.p->alignment_power)
4637                     h->root.u.c.p->alignment_power = alignment_power;
4638                 }
4639             }
4640         }
4641
4642       /* Make a special call to the linker "notice" function to
4643          tell it that symbols added for crefs may need to be removed.  */
4644       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4645         goto error_free_vers;
4646
4647       free (old_tab);
4648       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4649                            alloc_mark);
4650       if (nondeflt_vers != NULL)
4651         free (nondeflt_vers);
4652       return TRUE;
4653     }
4654
4655   if (old_tab != NULL)
4656     {
4657       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4658         goto error_free_vers;
4659       free (old_tab);
4660       old_tab = NULL;
4661     }
4662
4663   /* Now that all the symbols from this input file are created, if
4664      not performing a relocatable link, handle .symver foo, foo@BAR
4665      such that any relocs against foo become foo@BAR.  */
4666   if (!info->relocatable && nondeflt_vers != NULL)
4667     {
4668       bfd_size_type cnt, symidx;
4669
4670       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4671         {
4672           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4673           char *shortname, *p;
4674
4675           p = strchr (h->root.root.string, ELF_VER_CHR);
4676           if (p == NULL
4677               || (h->root.type != bfd_link_hash_defined
4678                   && h->root.type != bfd_link_hash_defweak))
4679             continue;
4680
4681           amt = p - h->root.root.string;
4682           shortname = (char *) bfd_malloc (amt + 1);
4683           if (!shortname)
4684             goto error_free_vers;
4685           memcpy (shortname, h->root.root.string, amt);
4686           shortname[amt] = '\0';
4687
4688           hi = (struct elf_link_hash_entry *)
4689                bfd_link_hash_lookup (&htab->root, shortname,
4690                                      FALSE, FALSE, FALSE);
4691           if (hi != NULL
4692               && hi->root.type == h->root.type
4693               && hi->root.u.def.value == h->root.u.def.value
4694               && hi->root.u.def.section == h->root.u.def.section)
4695             {
4696               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4697               hi->root.type = bfd_link_hash_indirect;
4698               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4699               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4700               sym_hash = elf_sym_hashes (abfd);
4701               if (sym_hash)
4702                 for (symidx = 0; symidx < extsymcount; ++symidx)
4703                   if (sym_hash[symidx] == hi)
4704                     {
4705                       sym_hash[symidx] = h;
4706                       break;
4707                     }
4708             }
4709           free (shortname);
4710         }
4711       free (nondeflt_vers);
4712       nondeflt_vers = NULL;
4713     }
4714
4715   /* Now set the weakdefs field correctly for all the weak defined
4716      symbols we found.  The only way to do this is to search all the
4717      symbols.  Since we only need the information for non functions in
4718      dynamic objects, that's the only time we actually put anything on
4719      the list WEAKS.  We need this information so that if a regular
4720      object refers to a symbol defined weakly in a dynamic object, the
4721      real symbol in the dynamic object is also put in the dynamic
4722      symbols; we also must arrange for both symbols to point to the
4723      same memory location.  We could handle the general case of symbol
4724      aliasing, but a general symbol alias can only be generated in
4725      assembler code, handling it correctly would be very time
4726      consuming, and other ELF linkers don't handle general aliasing
4727      either.  */
4728   if (weaks != NULL)
4729     {
4730       struct elf_link_hash_entry **hpp;
4731       struct elf_link_hash_entry **hppend;
4732       struct elf_link_hash_entry **sorted_sym_hash;
4733       struct elf_link_hash_entry *h;
4734       size_t sym_count;
4735
4736       /* Since we have to search the whole symbol list for each weak
4737          defined symbol, search time for N weak defined symbols will be
4738          O(N^2). Binary search will cut it down to O(NlogN).  */
4739       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4740       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4741       if (sorted_sym_hash == NULL)
4742         goto error_return;
4743       sym_hash = sorted_sym_hash;
4744       hpp = elf_sym_hashes (abfd);
4745       hppend = hpp + extsymcount;
4746       sym_count = 0;
4747       for (; hpp < hppend; hpp++)
4748         {
4749           h = *hpp;
4750           if (h != NULL
4751               && h->root.type == bfd_link_hash_defined
4752               && !bed->is_function_type (h->type))
4753             {
4754               *sym_hash = h;
4755               sym_hash++;
4756               sym_count++;
4757             }
4758         }
4759
4760       qsort (sorted_sym_hash, sym_count,
4761              sizeof (struct elf_link_hash_entry *),
4762              elf_sort_symbol);
4763
4764       while (weaks != NULL)
4765         {
4766           struct elf_link_hash_entry *hlook;
4767           asection *slook;
4768           bfd_vma vlook;
4769           size_t i, j, idx = 0;
4770
4771           hlook = weaks;
4772           weaks = hlook->u.weakdef;
4773           hlook->u.weakdef = NULL;
4774
4775           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4776                       || hlook->root.type == bfd_link_hash_defweak
4777                       || hlook->root.type == bfd_link_hash_common
4778                       || hlook->root.type == bfd_link_hash_indirect);
4779           slook = hlook->root.u.def.section;
4780           vlook = hlook->root.u.def.value;
4781
4782           i = 0;
4783           j = sym_count;
4784           while (i != j)
4785             {
4786               bfd_signed_vma vdiff;
4787               idx = (i + j) / 2;
4788               h = sorted_sym_hash[idx];
4789               vdiff = vlook - h->root.u.def.value;
4790               if (vdiff < 0)
4791                 j = idx;
4792               else if (vdiff > 0)
4793                 i = idx + 1;
4794               else
4795                 {
4796                   long sdiff = slook->id - h->root.u.def.section->id;
4797                   if (sdiff < 0)
4798                     j = idx;
4799                   else if (sdiff > 0)
4800                     i = idx + 1;
4801                   else
4802                     break;
4803                 }
4804             }
4805
4806           /* We didn't find a value/section match.  */
4807           if (i == j)
4808             continue;
4809
4810           /* With multiple aliases, or when the weak symbol is already
4811              strongly defined, we have multiple matching symbols and
4812              the binary search above may land on any of them.  Step
4813              one past the matching symbol(s).  */
4814           while (++idx != j)
4815             {
4816               h = sorted_sym_hash[idx];
4817               if (h->root.u.def.section != slook
4818                   || h->root.u.def.value != vlook)
4819                 break;
4820             }
4821
4822           /* Now look back over the aliases.  Since we sorted by size
4823              as well as value and section, we'll choose the one with
4824              the largest size.  */
4825           while (idx-- != i)
4826             {
4827               h = sorted_sym_hash[idx];
4828
4829               /* Stop if value or section doesn't match.  */
4830               if (h->root.u.def.section != slook
4831                   || h->root.u.def.value != vlook)
4832                 break;
4833               else if (h != hlook)
4834                 {
4835                   hlook->u.weakdef = h;
4836
4837                   /* If the weak definition is in the list of dynamic
4838                      symbols, make sure the real definition is put
4839                      there as well.  */
4840                   if (hlook->dynindx != -1 && h->dynindx == -1)
4841                     {
4842                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4843                         {
4844                         err_free_sym_hash:
4845                           free (sorted_sym_hash);
4846                           goto error_return;
4847                         }
4848                     }
4849
4850                   /* If the real definition is in the list of dynamic
4851                      symbols, make sure the weak definition is put
4852                      there as well.  If we don't do this, then the
4853                      dynamic loader might not merge the entries for the
4854                      real definition and the weak definition.  */
4855                   if (h->dynindx != -1 && hlook->dynindx == -1)
4856                     {
4857                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4858                         goto err_free_sym_hash;
4859                     }
4860                   break;
4861                 }
4862             }
4863         }
4864
4865       free (sorted_sym_hash);
4866     }
4867
4868   if (bed->check_directives
4869       && !(*bed->check_directives) (abfd, info))
4870     return FALSE;
4871
4872   /* If this object is the same format as the output object, and it is
4873      not a shared library, then let the backend look through the
4874      relocs.
4875
4876      This is required to build global offset table entries and to
4877      arrange for dynamic relocs.  It is not required for the
4878      particular common case of linking non PIC code, even when linking
4879      against shared libraries, but unfortunately there is no way of
4880      knowing whether an object file has been compiled PIC or not.
4881      Looking through the relocs is not particularly time consuming.
4882      The problem is that we must either (1) keep the relocs in memory,
4883      which causes the linker to require additional runtime memory or
4884      (2) read the relocs twice from the input file, which wastes time.
4885      This would be a good case for using mmap.
4886
4887      I have no idea how to handle linking PIC code into a file of a
4888      different format.  It probably can't be done.  */
4889   if (! dynamic
4890       && is_elf_hash_table (htab)
4891       && bed->check_relocs != NULL
4892       && elf_object_id (abfd) == elf_hash_table_id (htab)
4893       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4894     {
4895       asection *o;
4896
4897       for (o = abfd->sections; o != NULL; o = o->next)
4898         {
4899           Elf_Internal_Rela *internal_relocs;
4900           bfd_boolean ok;
4901
4902           if ((o->flags & SEC_RELOC) == 0
4903               || o->reloc_count == 0
4904               || ((info->strip == strip_all || info->strip == strip_debugger)
4905                   && (o->flags & SEC_DEBUGGING) != 0)
4906               || bfd_is_abs_section (o->output_section))
4907             continue;
4908
4909           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4910                                                        info->keep_memory);
4911           if (internal_relocs == NULL)
4912             goto error_return;
4913
4914           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4915
4916           if (elf_section_data (o)->relocs != internal_relocs)
4917             free (internal_relocs);
4918
4919           if (! ok)
4920             goto error_return;
4921         }
4922     }
4923
4924   /* If this is a non-traditional link, try to optimize the handling
4925      of the .stab/.stabstr sections.  */
4926   if (! dynamic
4927       && ! info->traditional_format
4928       && is_elf_hash_table (htab)
4929       && (info->strip != strip_all && info->strip != strip_debugger))
4930     {
4931       asection *stabstr;
4932
4933       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4934       if (stabstr != NULL)
4935         {
4936           bfd_size_type string_offset = 0;
4937           asection *stab;
4938
4939           for (stab = abfd->sections; stab; stab = stab->next)
4940             if (CONST_STRNEQ (stab->name, ".stab")
4941                 && (!stab->name[5] ||
4942                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4943                 && (stab->flags & SEC_MERGE) == 0
4944                 && !bfd_is_abs_section (stab->output_section))
4945               {
4946                 struct bfd_elf_section_data *secdata;
4947
4948                 secdata = elf_section_data (stab);
4949                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4950                                                stabstr, &secdata->sec_info,
4951                                                &string_offset))
4952                   goto error_return;
4953                 if (secdata->sec_info)
4954                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
4955             }
4956         }
4957     }
4958
4959   if (is_elf_hash_table (htab) && add_needed)
4960     {
4961       /* Add this bfd to the loaded list.  */
4962       struct elf_link_loaded_list *n;
4963
4964       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
4965       if (n == NULL)
4966         goto error_return;
4967       n->abfd = abfd;
4968       n->next = htab->loaded;
4969       htab->loaded = n;
4970     }
4971
4972   return TRUE;
4973
4974  error_free_vers:
4975   if (old_tab != NULL)
4976     free (old_tab);
4977   if (nondeflt_vers != NULL)
4978     free (nondeflt_vers);
4979   if (extversym != NULL)
4980     free (extversym);
4981  error_free_sym:
4982   if (isymbuf != NULL)
4983     free (isymbuf);
4984  error_return:
4985   return FALSE;
4986 }
4987
4988 /* Return the linker hash table entry of a symbol that might be
4989    satisfied by an archive symbol.  Return -1 on error.  */
4990
4991 struct elf_link_hash_entry *
4992 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4993                                 struct bfd_link_info *info,
4994                                 const char *name)
4995 {
4996   struct elf_link_hash_entry *h;
4997   char *p, *copy;
4998   size_t len, first;
4999
5000   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5001   if (h != NULL)
5002     return h;
5003
5004   /* If this is a default version (the name contains @@), look up the
5005      symbol again with only one `@' as well as without the version.
5006      The effect is that references to the symbol with and without the
5007      version will be matched by the default symbol in the archive.  */
5008
5009   p = strchr (name, ELF_VER_CHR);
5010   if (p == NULL || p[1] != ELF_VER_CHR)
5011     return h;
5012
5013   /* First check with only one `@'.  */
5014   len = strlen (name);
5015   copy = (char *) bfd_alloc (abfd, len);
5016   if (copy == NULL)
5017     return (struct elf_link_hash_entry *) 0 - 1;
5018
5019   first = p - name + 1;
5020   memcpy (copy, name, first);
5021   memcpy (copy + first, name + first + 1, len - first);
5022
5023   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5024   if (h == NULL)
5025     {
5026       /* We also need to check references to the symbol without the
5027          version.  */
5028       copy[first - 1] = '\0';
5029       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5030                                 FALSE, FALSE, TRUE);
5031     }
5032
5033   bfd_release (abfd, copy);
5034   return h;
5035 }
5036
5037 /* Add symbols from an ELF archive file to the linker hash table.  We
5038    don't use _bfd_generic_link_add_archive_symbols because we need to
5039    handle versioned symbols.
5040
5041    Fortunately, ELF archive handling is simpler than that done by
5042    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5043    oddities.  In ELF, if we find a symbol in the archive map, and the
5044    symbol is currently undefined, we know that we must pull in that
5045    object file.
5046
5047    Unfortunately, we do have to make multiple passes over the symbol
5048    table until nothing further is resolved.  */
5049
5050 static bfd_boolean
5051 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5052 {
5053   symindex c;
5054   unsigned char *included = NULL;
5055   carsym *symdefs;
5056   bfd_boolean loop;
5057   bfd_size_type amt;
5058   const struct elf_backend_data *bed;
5059   struct elf_link_hash_entry * (*archive_symbol_lookup)
5060     (bfd *, struct bfd_link_info *, const char *);
5061
5062   if (! bfd_has_map (abfd))
5063     {
5064       /* An empty archive is a special case.  */
5065       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5066         return TRUE;
5067       bfd_set_error (bfd_error_no_armap);
5068       return FALSE;
5069     }
5070
5071   /* Keep track of all symbols we know to be already defined, and all
5072      files we know to be already included.  This is to speed up the
5073      second and subsequent passes.  */
5074   c = bfd_ardata (abfd)->symdef_count;
5075   if (c == 0)
5076     return TRUE;
5077   amt = c;
5078   amt *= sizeof (*included);
5079   included = (unsigned char *) bfd_zmalloc (amt);
5080   if (included == NULL)
5081     return FALSE;
5082
5083   symdefs = bfd_ardata (abfd)->symdefs;
5084   bed = get_elf_backend_data (abfd);
5085   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5086
5087   do
5088     {
5089       file_ptr last;
5090       symindex i;
5091       carsym *symdef;
5092       carsym *symdefend;
5093
5094       loop = FALSE;
5095       last = -1;
5096
5097       symdef = symdefs;
5098       symdefend = symdef + c;
5099       for (i = 0; symdef < symdefend; symdef++, i++)
5100         {
5101           struct elf_link_hash_entry *h;
5102           bfd *element;
5103           struct bfd_link_hash_entry *undefs_tail;
5104           symindex mark;
5105
5106           if (included[i])
5107             continue;
5108           if (symdef->file_offset == last)
5109             {
5110               included[i] = TRUE;
5111               continue;
5112             }
5113
5114           h = archive_symbol_lookup (abfd, info, symdef->name);
5115           if (h == (struct elf_link_hash_entry *) 0 - 1)
5116             goto error_return;
5117
5118           if (h == NULL)
5119             continue;
5120
5121           if (h->root.type == bfd_link_hash_common)
5122             {
5123               /* We currently have a common symbol.  The archive map contains
5124                  a reference to this symbol, so we may want to include it.  We
5125                  only want to include it however, if this archive element
5126                  contains a definition of the symbol, not just another common
5127                  declaration of it.
5128
5129                  Unfortunately some archivers (including GNU ar) will put
5130                  declarations of common symbols into their archive maps, as
5131                  well as real definitions, so we cannot just go by the archive
5132                  map alone.  Instead we must read in the element's symbol
5133                  table and check that to see what kind of symbol definition
5134                  this is.  */
5135               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5136                 continue;
5137             }
5138           else if (h->root.type != bfd_link_hash_undefined)
5139             {
5140               if (h->root.type != bfd_link_hash_undefweak)
5141                 /* Symbol must be defined.  Don't check it again.  */
5142                 included[i] = TRUE;
5143               continue;
5144             }
5145
5146           /* We need to include this archive member.  */
5147           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5148           if (element == NULL)
5149             goto error_return;
5150
5151           if (! bfd_check_format (element, bfd_object))
5152             goto error_return;
5153
5154           undefs_tail = info->hash->undefs_tail;
5155
5156           if (!(*info->callbacks
5157                 ->add_archive_element) (info, element, symdef->name, &element))
5158             goto error_return;
5159           if (!bfd_link_add_symbols (element, info))
5160             goto error_return;
5161
5162           /* If there are any new undefined symbols, we need to make
5163              another pass through the archive in order to see whether
5164              they can be defined.  FIXME: This isn't perfect, because
5165              common symbols wind up on undefs_tail and because an
5166              undefined symbol which is defined later on in this pass
5167              does not require another pass.  This isn't a bug, but it
5168              does make the code less efficient than it could be.  */
5169           if (undefs_tail != info->hash->undefs_tail)
5170             loop = TRUE;
5171
5172           /* Look backward to mark all symbols from this object file
5173              which we have already seen in this pass.  */
5174           mark = i;
5175           do
5176             {
5177               included[mark] = TRUE;
5178               if (mark == 0)
5179                 break;
5180               --mark;
5181             }
5182           while (symdefs[mark].file_offset == symdef->file_offset);
5183
5184           /* We mark subsequent symbols from this object file as we go
5185              on through the loop.  */
5186           last = symdef->file_offset;
5187         }
5188     }
5189   while (loop);
5190
5191   free (included);
5192
5193   return TRUE;
5194
5195  error_return:
5196   if (included != NULL)
5197     free (included);
5198   return FALSE;
5199 }
5200
5201 /* Given an ELF BFD, add symbols to the global hash table as
5202    appropriate.  */
5203
5204 bfd_boolean
5205 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5206 {
5207   switch (bfd_get_format (abfd))
5208     {
5209     case bfd_object:
5210       return elf_link_add_object_symbols (abfd, info);
5211     case bfd_archive:
5212       return elf_link_add_archive_symbols (abfd, info);
5213     default:
5214       bfd_set_error (bfd_error_wrong_format);
5215       return FALSE;
5216     }
5217 }
5218 \f
5219 struct hash_codes_info
5220 {
5221   unsigned long *hashcodes;
5222   bfd_boolean error;
5223 };
5224
5225 /* This function will be called though elf_link_hash_traverse to store
5226    all hash value of the exported symbols in an array.  */
5227
5228 static bfd_boolean
5229 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5230 {
5231   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5232   const char *name;
5233   char *p;
5234   unsigned long ha;
5235   char *alc = NULL;
5236
5237   /* Ignore indirect symbols.  These are added by the versioning code.  */
5238   if (h->dynindx == -1)
5239     return TRUE;
5240
5241   name = h->root.root.string;
5242   p = strchr (name, ELF_VER_CHR);
5243   if (p != NULL)
5244     {
5245       alc = (char *) bfd_malloc (p - name + 1);
5246       if (alc == NULL)
5247         {
5248           inf->error = TRUE;
5249           return FALSE;
5250         }
5251       memcpy (alc, name, p - name);
5252       alc[p - name] = '\0';
5253       name = alc;
5254     }
5255
5256   /* Compute the hash value.  */
5257   ha = bfd_elf_hash (name);
5258
5259   /* Store the found hash value in the array given as the argument.  */
5260   *(inf->hashcodes)++ = ha;
5261
5262   /* And store it in the struct so that we can put it in the hash table
5263      later.  */
5264   h->u.elf_hash_value = ha;
5265
5266   if (alc != NULL)
5267     free (alc);
5268
5269   return TRUE;
5270 }
5271
5272 struct collect_gnu_hash_codes
5273 {
5274   bfd *output_bfd;
5275   const struct elf_backend_data *bed;
5276   unsigned long int nsyms;
5277   unsigned long int maskbits;
5278   unsigned long int *hashcodes;
5279   unsigned long int *hashval;
5280   unsigned long int *indx;
5281   unsigned long int *counts;
5282   bfd_vma *bitmask;
5283   bfd_byte *contents;
5284   long int min_dynindx;
5285   unsigned long int bucketcount;
5286   unsigned long int symindx;
5287   long int local_indx;
5288   long int shift1, shift2;
5289   unsigned long int mask;
5290   bfd_boolean error;
5291 };
5292
5293 /* This function will be called though elf_link_hash_traverse to store
5294    all hash value of the exported symbols in an array.  */
5295
5296 static bfd_boolean
5297 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5298 {
5299   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5300   const char *name;
5301   char *p;
5302   unsigned long ha;
5303   char *alc = NULL;
5304
5305   /* Ignore indirect symbols.  These are added by the versioning code.  */
5306   if (h->dynindx == -1)
5307     return TRUE;
5308
5309   /* Ignore also local symbols and undefined symbols.  */
5310   if (! (*s->bed->elf_hash_symbol) (h))
5311     return TRUE;
5312
5313   name = h->root.root.string;
5314   p = strchr (name, ELF_VER_CHR);
5315   if (p != NULL)
5316     {
5317       alc = (char *) bfd_malloc (p - name + 1);
5318       if (alc == NULL)
5319         {
5320           s->error = TRUE;
5321           return FALSE;
5322         }
5323       memcpy (alc, name, p - name);
5324       alc[p - name] = '\0';
5325       name = alc;
5326     }
5327
5328   /* Compute the hash value.  */
5329   ha = bfd_elf_gnu_hash (name);
5330
5331   /* Store the found hash value in the array for compute_bucket_count,
5332      and also for .dynsym reordering purposes.  */
5333   s->hashcodes[s->nsyms] = ha;
5334   s->hashval[h->dynindx] = ha;
5335   ++s->nsyms;
5336   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5337     s->min_dynindx = h->dynindx;
5338
5339   if (alc != NULL)
5340     free (alc);
5341
5342   return TRUE;
5343 }
5344
5345 /* This function will be called though elf_link_hash_traverse to do
5346    final dynaminc symbol renumbering.  */
5347
5348 static bfd_boolean
5349 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5350 {
5351   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5352   unsigned long int bucket;
5353   unsigned long int val;
5354
5355   /* Ignore indirect symbols.  */
5356   if (h->dynindx == -1)
5357     return TRUE;
5358
5359   /* Ignore also local symbols and undefined symbols.  */
5360   if (! (*s->bed->elf_hash_symbol) (h))
5361     {
5362       if (h->dynindx >= s->min_dynindx)
5363         h->dynindx = s->local_indx++;
5364       return TRUE;
5365     }
5366
5367   bucket = s->hashval[h->dynindx] % s->bucketcount;
5368   val = (s->hashval[h->dynindx] >> s->shift1)
5369         & ((s->maskbits >> s->shift1) - 1);
5370   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5371   s->bitmask[val]
5372     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5373   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5374   if (s->counts[bucket] == 1)
5375     /* Last element terminates the chain.  */
5376     val |= 1;
5377   bfd_put_32 (s->output_bfd, val,
5378               s->contents + (s->indx[bucket] - s->symindx) * 4);
5379   --s->counts[bucket];
5380   h->dynindx = s->indx[bucket]++;
5381   return TRUE;
5382 }
5383
5384 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5385
5386 bfd_boolean
5387 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5388 {
5389   return !(h->forced_local
5390            || h->root.type == bfd_link_hash_undefined
5391            || h->root.type == bfd_link_hash_undefweak
5392            || ((h->root.type == bfd_link_hash_defined
5393                 || h->root.type == bfd_link_hash_defweak)
5394                && h->root.u.def.section->output_section == NULL));
5395 }
5396
5397 /* Array used to determine the number of hash table buckets to use
5398    based on the number of symbols there are.  If there are fewer than
5399    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5400    fewer than 37 we use 17 buckets, and so forth.  We never use more
5401    than 32771 buckets.  */
5402
5403 static const size_t elf_buckets[] =
5404 {
5405   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5406   16411, 32771, 0
5407 };
5408
5409 /* Compute bucket count for hashing table.  We do not use a static set
5410    of possible tables sizes anymore.  Instead we determine for all
5411    possible reasonable sizes of the table the outcome (i.e., the
5412    number of collisions etc) and choose the best solution.  The
5413    weighting functions are not too simple to allow the table to grow
5414    without bounds.  Instead one of the weighting factors is the size.
5415    Therefore the result is always a good payoff between few collisions
5416    (= short chain lengths) and table size.  */
5417 static size_t
5418 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5419                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5420                       unsigned long int nsyms,
5421                       int gnu_hash)
5422 {
5423   size_t best_size = 0;
5424   unsigned long int i;
5425
5426   /* We have a problem here.  The following code to optimize the table
5427      size requires an integer type with more the 32 bits.  If
5428      BFD_HOST_U_64_BIT is set we know about such a type.  */
5429 #ifdef BFD_HOST_U_64_BIT
5430   if (info->optimize)
5431     {
5432       size_t minsize;
5433       size_t maxsize;
5434       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5435       bfd *dynobj = elf_hash_table (info)->dynobj;
5436       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5437       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5438       unsigned long int *counts;
5439       bfd_size_type amt;
5440       unsigned int no_improvement_count = 0;
5441
5442       /* Possible optimization parameters: if we have NSYMS symbols we say
5443          that the hashing table must at least have NSYMS/4 and at most
5444          2*NSYMS buckets.  */
5445       minsize = nsyms / 4;
5446       if (minsize == 0)
5447         minsize = 1;
5448       best_size = maxsize = nsyms * 2;
5449       if (gnu_hash)
5450         {
5451           if (minsize < 2)
5452             minsize = 2;
5453           if ((best_size & 31) == 0)
5454             ++best_size;
5455         }
5456
5457       /* Create array where we count the collisions in.  We must use bfd_malloc
5458          since the size could be large.  */
5459       amt = maxsize;
5460       amt *= sizeof (unsigned long int);
5461       counts = (unsigned long int *) bfd_malloc (amt);
5462       if (counts == NULL)
5463         return 0;
5464
5465       /* Compute the "optimal" size for the hash table.  The criteria is a
5466          minimal chain length.  The minor criteria is (of course) the size
5467          of the table.  */
5468       for (i = minsize; i < maxsize; ++i)
5469         {
5470           /* Walk through the array of hashcodes and count the collisions.  */
5471           BFD_HOST_U_64_BIT max;
5472           unsigned long int j;
5473           unsigned long int fact;
5474
5475           if (gnu_hash && (i & 31) == 0)
5476             continue;
5477
5478           memset (counts, '\0', i * sizeof (unsigned long int));
5479
5480           /* Determine how often each hash bucket is used.  */
5481           for (j = 0; j < nsyms; ++j)
5482             ++counts[hashcodes[j] % i];
5483
5484           /* For the weight function we need some information about the
5485              pagesize on the target.  This is information need not be 100%
5486              accurate.  Since this information is not available (so far) we
5487              define it here to a reasonable default value.  If it is crucial
5488              to have a better value some day simply define this value.  */
5489 # ifndef BFD_TARGET_PAGESIZE
5490 #  define BFD_TARGET_PAGESIZE   (4096)
5491 # endif
5492
5493           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5494              and the chains.  */
5495           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5496
5497 # if 1
5498           /* Variant 1: optimize for short chains.  We add the squares
5499              of all the chain lengths (which favors many small chain
5500              over a few long chains).  */
5501           for (j = 0; j < i; ++j)
5502             max += counts[j] * counts[j];
5503
5504           /* This adds penalties for the overall size of the table.  */
5505           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5506           max *= fact * fact;
5507 # else
5508           /* Variant 2: Optimize a lot more for small table.  Here we
5509              also add squares of the size but we also add penalties for
5510              empty slots (the +1 term).  */
5511           for (j = 0; j < i; ++j)
5512             max += (1 + counts[j]) * (1 + counts[j]);
5513
5514           /* The overall size of the table is considered, but not as
5515              strong as in variant 1, where it is squared.  */
5516           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5517           max *= fact;
5518 # endif
5519
5520           /* Compare with current best results.  */
5521           if (max < best_chlen)
5522             {
5523               best_chlen = max;
5524               best_size = i;
5525               no_improvement_count = 0;
5526             }
5527           /* PR 11843: Avoid futile long searches for the best bucket size
5528              when there are a large number of symbols.  */
5529           else if (++no_improvement_count == 100)
5530             break;
5531         }
5532
5533       free (counts);
5534     }
5535   else
5536 #endif /* defined (BFD_HOST_U_64_BIT) */
5537     {
5538       /* This is the fallback solution if no 64bit type is available or if we
5539          are not supposed to spend much time on optimizations.  We select the
5540          bucket count using a fixed set of numbers.  */
5541       for (i = 0; elf_buckets[i] != 0; i++)
5542         {
5543           best_size = elf_buckets[i];
5544           if (nsyms < elf_buckets[i + 1])
5545             break;
5546         }
5547       if (gnu_hash && best_size < 2)
5548         best_size = 2;
5549     }
5550
5551   return best_size;
5552 }
5553
5554 /* Size any SHT_GROUP section for ld -r.  */
5555
5556 bfd_boolean
5557 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5558 {
5559   bfd *ibfd;
5560
5561   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5562     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5563         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5564       return FALSE;
5565   return TRUE;
5566 }
5567
5568 /* Set a default stack segment size.  The value in INFO wins.  If it
5569    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5570    undefined it is initialized.  */
5571
5572 bfd_boolean
5573 bfd_elf_stack_segment_size (bfd *output_bfd,
5574                             struct bfd_link_info *info,
5575                             const char *legacy_symbol,
5576                             bfd_vma default_size)
5577 {
5578   struct elf_link_hash_entry *h = NULL;
5579
5580   /* Look for legacy symbol.  */
5581   if (legacy_symbol)
5582     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5583                               FALSE, FALSE, FALSE);
5584   if (h && (h->root.type == bfd_link_hash_defined
5585             || h->root.type == bfd_link_hash_defweak)
5586       && h->def_regular
5587       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5588     {
5589       /* The symbol has no type if specified on the command line.  */
5590       h->type = STT_OBJECT;
5591       if (info->stacksize)
5592         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5593                                output_bfd, legacy_symbol);
5594       else if (h->root.u.def.section != bfd_abs_section_ptr)
5595         (*_bfd_error_handler) (_("%B: %s not absolute"),
5596                                output_bfd, legacy_symbol);
5597       else
5598         info->stacksize = h->root.u.def.value;
5599     }
5600
5601   if (!info->stacksize)
5602     /* If the user didn't set a size, or explicitly inhibit the
5603        size, set it now.  */
5604     info->stacksize = default_size;
5605
5606   /* Provide the legacy symbol, if it is referenced.  */
5607   if (h && (h->root.type == bfd_link_hash_undefined
5608             || h->root.type == bfd_link_hash_undefweak))
5609     {
5610       struct bfd_link_hash_entry *bh = NULL;
5611
5612       if (!(_bfd_generic_link_add_one_symbol
5613             (info, output_bfd, legacy_symbol,
5614              BSF_GLOBAL, bfd_abs_section_ptr,
5615              info->stacksize >= 0 ? info->stacksize : 0,
5616              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5617         return FALSE;
5618
5619       h = (struct elf_link_hash_entry *) bh;
5620       h->def_regular = 1;
5621       h->type = STT_OBJECT;
5622     }
5623
5624   return TRUE;
5625 }
5626
5627 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5628    called by the ELF linker emulation before_allocation routine.  We
5629    must set the sizes of the sections before the linker sets the
5630    addresses of the various sections.  */
5631
5632 bfd_boolean
5633 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5634                                const char *soname,
5635                                const char *rpath,
5636                                const char *filter_shlib,
5637                                const char *audit,
5638                                const char *depaudit,
5639                                const char * const *auxiliary_filters,
5640                                struct bfd_link_info *info,
5641                                asection **sinterpptr)
5642 {
5643   bfd_size_type soname_indx;
5644   bfd *dynobj;
5645   const struct elf_backend_data *bed;
5646   struct elf_info_failed asvinfo;
5647
5648   *sinterpptr = NULL;
5649
5650   soname_indx = (bfd_size_type) -1;
5651
5652   if (!is_elf_hash_table (info->hash))
5653     return TRUE;
5654
5655   bed = get_elf_backend_data (output_bfd);
5656
5657   /* Any syms created from now on start with -1 in
5658      got.refcount/offset and plt.refcount/offset.  */
5659   elf_hash_table (info)->init_got_refcount
5660     = elf_hash_table (info)->init_got_offset;
5661   elf_hash_table (info)->init_plt_refcount
5662     = elf_hash_table (info)->init_plt_offset;
5663
5664   if (info->relocatable
5665       && !_bfd_elf_size_group_sections (info))
5666     return FALSE;
5667
5668   /* The backend may have to create some sections regardless of whether
5669      we're dynamic or not.  */
5670   if (bed->elf_backend_always_size_sections
5671       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5672     return FALSE;
5673
5674   /* Determine any GNU_STACK segment requirements, after the backend
5675      has had a chance to set a default segment size.  */
5676   if (info->execstack)
5677     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5678   else if (info->noexecstack)
5679     elf_stack_flags (output_bfd) = PF_R | PF_W;
5680   else
5681     {
5682       bfd *inputobj;
5683       asection *notesec = NULL;
5684       int exec = 0;
5685
5686       for (inputobj = info->input_bfds;
5687            inputobj;
5688            inputobj = inputobj->link.next)
5689         {
5690           asection *s;
5691
5692           if (inputobj->flags
5693               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5694             continue;
5695           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5696           if (s)
5697             {
5698               if (s->flags & SEC_CODE)
5699                 exec = PF_X;
5700               notesec = s;
5701             }
5702           else if (bed->default_execstack)
5703             exec = PF_X;
5704         }
5705       if (notesec || info->stacksize > 0)
5706         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5707       if (notesec && exec && info->relocatable
5708           && notesec->output_section != bfd_abs_section_ptr)
5709         notesec->output_section->flags |= SEC_CODE;
5710     }
5711
5712   dynobj = elf_hash_table (info)->dynobj;
5713
5714   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5715     {
5716       struct elf_info_failed eif;
5717       struct elf_link_hash_entry *h;
5718       asection *dynstr;
5719       struct bfd_elf_version_tree *t;
5720       struct bfd_elf_version_expr *d;
5721       asection *s;
5722       bfd_boolean all_defined;
5723
5724       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5725       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5726
5727       if (soname != NULL)
5728         {
5729           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5730                                              soname, TRUE);
5731           if (soname_indx == (bfd_size_type) -1
5732               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5733             return FALSE;
5734         }
5735
5736       if (info->symbolic)
5737         {
5738           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5739             return FALSE;
5740           info->flags |= DF_SYMBOLIC;
5741         }
5742
5743       if (rpath != NULL)
5744         {
5745           bfd_size_type indx;
5746           bfd_vma tag;
5747
5748           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5749                                       TRUE);
5750           if (indx == (bfd_size_type) -1)
5751             return FALSE;
5752
5753           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5754           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5755             return FALSE;
5756         }
5757
5758       if (filter_shlib != NULL)
5759         {
5760           bfd_size_type indx;
5761
5762           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5763                                       filter_shlib, TRUE);
5764           if (indx == (bfd_size_type) -1
5765               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5766             return FALSE;
5767         }
5768
5769       if (auxiliary_filters != NULL)
5770         {
5771           const char * const *p;
5772
5773           for (p = auxiliary_filters; *p != NULL; p++)
5774             {
5775               bfd_size_type indx;
5776
5777               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5778                                           *p, TRUE);
5779               if (indx == (bfd_size_type) -1
5780                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5781                 return FALSE;
5782             }
5783         }
5784
5785       if (audit != NULL)
5786         {
5787           bfd_size_type indx;
5788
5789           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5790                                       TRUE);
5791           if (indx == (bfd_size_type) -1
5792               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5793             return FALSE;
5794         }
5795
5796       if (depaudit != NULL)
5797         {
5798           bfd_size_type indx;
5799
5800           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5801                                       TRUE);
5802           if (indx == (bfd_size_type) -1
5803               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5804             return FALSE;
5805         }
5806
5807       eif.info = info;
5808       eif.failed = FALSE;
5809
5810       /* If we are supposed to export all symbols into the dynamic symbol
5811          table (this is not the normal case), then do so.  */
5812       if (info->export_dynamic
5813           || (info->executable && info->dynamic))
5814         {
5815           elf_link_hash_traverse (elf_hash_table (info),
5816                                   _bfd_elf_export_symbol,
5817                                   &eif);
5818           if (eif.failed)
5819             return FALSE;
5820         }
5821
5822       /* Make all global versions with definition.  */
5823       for (t = info->version_info; t != NULL; t = t->next)
5824         for (d = t->globals.list; d != NULL; d = d->next)
5825           if (!d->symver && d->literal)
5826             {
5827               const char *verstr, *name;
5828               size_t namelen, verlen, newlen;
5829               char *newname, *p, leading_char;
5830               struct elf_link_hash_entry *newh;
5831
5832               leading_char = bfd_get_symbol_leading_char (output_bfd);
5833               name = d->pattern;
5834               namelen = strlen (name) + (leading_char != '\0');
5835               verstr = t->name;
5836               verlen = strlen (verstr);
5837               newlen = namelen + verlen + 3;
5838
5839               newname = (char *) bfd_malloc (newlen);
5840               if (newname == NULL)
5841                 return FALSE;
5842               newname[0] = leading_char;
5843               memcpy (newname + (leading_char != '\0'), name, namelen);
5844
5845               /* Check the hidden versioned definition.  */
5846               p = newname + namelen;
5847               *p++ = ELF_VER_CHR;
5848               memcpy (p, verstr, verlen + 1);
5849               newh = elf_link_hash_lookup (elf_hash_table (info),
5850                                            newname, FALSE, FALSE,
5851                                            FALSE);
5852               if (newh == NULL
5853                   || (newh->root.type != bfd_link_hash_defined
5854                       && newh->root.type != bfd_link_hash_defweak))
5855                 {
5856                   /* Check the default versioned definition.  */
5857                   *p++ = ELF_VER_CHR;
5858                   memcpy (p, verstr, verlen + 1);
5859                   newh = elf_link_hash_lookup (elf_hash_table (info),
5860                                                newname, FALSE, FALSE,
5861                                                FALSE);
5862                 }
5863               free (newname);
5864
5865               /* Mark this version if there is a definition and it is
5866                  not defined in a shared object.  */
5867               if (newh != NULL
5868                   && !newh->def_dynamic
5869                   && (newh->root.type == bfd_link_hash_defined
5870                       || newh->root.type == bfd_link_hash_defweak))
5871                 d->symver = 1;
5872             }
5873
5874       /* Attach all the symbols to their version information.  */
5875       asvinfo.info = info;
5876       asvinfo.failed = FALSE;
5877
5878       elf_link_hash_traverse (elf_hash_table (info),
5879                               _bfd_elf_link_assign_sym_version,
5880                               &asvinfo);
5881       if (asvinfo.failed)
5882         return FALSE;
5883
5884       if (!info->allow_undefined_version)
5885         {
5886           /* Check if all global versions have a definition.  */
5887           all_defined = TRUE;
5888           for (t = info->version_info; t != NULL; t = t->next)
5889             for (d = t->globals.list; d != NULL; d = d->next)
5890               if (d->literal && !d->symver && !d->script)
5891                 {
5892                   (*_bfd_error_handler)
5893                     (_("%s: undefined version: %s"),
5894                      d->pattern, t->name);
5895                   all_defined = FALSE;
5896                 }
5897
5898           if (!all_defined)
5899             {
5900               bfd_set_error (bfd_error_bad_value);
5901               return FALSE;
5902             }
5903         }
5904
5905       /* Find all symbols which were defined in a dynamic object and make
5906          the backend pick a reasonable value for them.  */
5907       elf_link_hash_traverse (elf_hash_table (info),
5908                               _bfd_elf_adjust_dynamic_symbol,
5909                               &eif);
5910       if (eif.failed)
5911         return FALSE;
5912
5913       /* Add some entries to the .dynamic section.  We fill in some of the
5914          values later, in bfd_elf_final_link, but we must add the entries
5915          now so that we know the final size of the .dynamic section.  */
5916
5917       /* If there are initialization and/or finalization functions to
5918          call then add the corresponding DT_INIT/DT_FINI entries.  */
5919       h = (info->init_function
5920            ? elf_link_hash_lookup (elf_hash_table (info),
5921                                    info->init_function, FALSE,
5922                                    FALSE, FALSE)
5923            : NULL);
5924       if (h != NULL
5925           && (h->ref_regular
5926               || h->def_regular))
5927         {
5928           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5929             return FALSE;
5930         }
5931       h = (info->fini_function
5932            ? elf_link_hash_lookup (elf_hash_table (info),
5933                                    info->fini_function, FALSE,
5934                                    FALSE, FALSE)
5935            : NULL);
5936       if (h != NULL
5937           && (h->ref_regular
5938               || h->def_regular))
5939         {
5940           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5941             return FALSE;
5942         }
5943
5944       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5945       if (s != NULL && s->linker_has_input)
5946         {
5947           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5948           if (! info->executable)
5949             {
5950               bfd *sub;
5951               asection *o;
5952
5953               for (sub = info->input_bfds; sub != NULL;
5954                    sub = sub->link.next)
5955                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5956                   for (o = sub->sections; o != NULL; o = o->next)
5957                     if (elf_section_data (o)->this_hdr.sh_type
5958                         == SHT_PREINIT_ARRAY)
5959                       {
5960                         (*_bfd_error_handler)
5961                           (_("%B: .preinit_array section is not allowed in DSO"),
5962                            sub);
5963                         break;
5964                       }
5965
5966               bfd_set_error (bfd_error_nonrepresentable_section);
5967               return FALSE;
5968             }
5969
5970           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5971               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5972             return FALSE;
5973         }
5974       s = bfd_get_section_by_name (output_bfd, ".init_array");
5975       if (s != NULL && s->linker_has_input)
5976         {
5977           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5978               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5979             return FALSE;
5980         }
5981       s = bfd_get_section_by_name (output_bfd, ".fini_array");
5982       if (s != NULL && s->linker_has_input)
5983         {
5984           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5985               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5986             return FALSE;
5987         }
5988
5989       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
5990       /* If .dynstr is excluded from the link, we don't want any of
5991          these tags.  Strictly, we should be checking each section
5992          individually;  This quick check covers for the case where
5993          someone does a /DISCARD/ : { *(*) }.  */
5994       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5995         {
5996           bfd_size_type strsize;
5997
5998           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5999           if ((info->emit_hash
6000                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6001               || (info->emit_gnu_hash
6002                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6003               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6004               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6005               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6006               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6007                                               bed->s->sizeof_sym))
6008             return FALSE;
6009         }
6010     }
6011
6012   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6013     return FALSE;
6014
6015   /* The backend must work out the sizes of all the other dynamic
6016      sections.  */
6017   if (dynobj != NULL
6018       && bed->elf_backend_size_dynamic_sections != NULL
6019       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6020     return FALSE;
6021
6022   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6023     {
6024       unsigned long section_sym_count;
6025       struct bfd_elf_version_tree *verdefs;
6026       asection *s;
6027
6028       /* Set up the version definition section.  */
6029       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6030       BFD_ASSERT (s != NULL);
6031
6032       /* We may have created additional version definitions if we are
6033          just linking a regular application.  */
6034       verdefs = info->version_info;
6035
6036       /* Skip anonymous version tag.  */
6037       if (verdefs != NULL && verdefs->vernum == 0)
6038         verdefs = verdefs->next;
6039
6040       if (verdefs == NULL && !info->create_default_symver)
6041         s->flags |= SEC_EXCLUDE;
6042       else
6043         {
6044           unsigned int cdefs;
6045           bfd_size_type size;
6046           struct bfd_elf_version_tree *t;
6047           bfd_byte *p;
6048           Elf_Internal_Verdef def;
6049           Elf_Internal_Verdaux defaux;
6050           struct bfd_link_hash_entry *bh;
6051           struct elf_link_hash_entry *h;
6052           const char *name;
6053
6054           cdefs = 0;
6055           size = 0;
6056
6057           /* Make space for the base version.  */
6058           size += sizeof (Elf_External_Verdef);
6059           size += sizeof (Elf_External_Verdaux);
6060           ++cdefs;
6061
6062           /* Make space for the default version.  */
6063           if (info->create_default_symver)
6064             {
6065               size += sizeof (Elf_External_Verdef);
6066               ++cdefs;
6067             }
6068
6069           for (t = verdefs; t != NULL; t = t->next)
6070             {
6071               struct bfd_elf_version_deps *n;
6072
6073               /* Don't emit base version twice.  */
6074               if (t->vernum == 0)
6075                 continue;
6076
6077               size += sizeof (Elf_External_Verdef);
6078               size += sizeof (Elf_External_Verdaux);
6079               ++cdefs;
6080
6081               for (n = t->deps; n != NULL; n = n->next)
6082                 size += sizeof (Elf_External_Verdaux);
6083             }
6084
6085           s->size = size;
6086           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6087           if (s->contents == NULL && s->size != 0)
6088             return FALSE;
6089
6090           /* Fill in the version definition section.  */
6091
6092           p = s->contents;
6093
6094           def.vd_version = VER_DEF_CURRENT;
6095           def.vd_flags = VER_FLG_BASE;
6096           def.vd_ndx = 1;
6097           def.vd_cnt = 1;
6098           if (info->create_default_symver)
6099             {
6100               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6101               def.vd_next = sizeof (Elf_External_Verdef);
6102             }
6103           else
6104             {
6105               def.vd_aux = sizeof (Elf_External_Verdef);
6106               def.vd_next = (sizeof (Elf_External_Verdef)
6107                              + sizeof (Elf_External_Verdaux));
6108             }
6109
6110           if (soname_indx != (bfd_size_type) -1)
6111             {
6112               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6113                                       soname_indx);
6114               def.vd_hash = bfd_elf_hash (soname);
6115               defaux.vda_name = soname_indx;
6116               name = soname;
6117             }
6118           else
6119             {
6120               bfd_size_type indx;
6121
6122               name = lbasename (output_bfd->filename);
6123               def.vd_hash = bfd_elf_hash (name);
6124               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6125                                           name, FALSE);
6126               if (indx == (bfd_size_type) -1)
6127                 return FALSE;
6128               defaux.vda_name = indx;
6129             }
6130           defaux.vda_next = 0;
6131
6132           _bfd_elf_swap_verdef_out (output_bfd, &def,
6133                                     (Elf_External_Verdef *) p);
6134           p += sizeof (Elf_External_Verdef);
6135           if (info->create_default_symver)
6136             {
6137               /* Add a symbol representing this version.  */
6138               bh = NULL;
6139               if (! (_bfd_generic_link_add_one_symbol
6140                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6141                       0, NULL, FALSE,
6142                       get_elf_backend_data (dynobj)->collect, &bh)))
6143                 return FALSE;
6144               h = (struct elf_link_hash_entry *) bh;
6145               h->non_elf = 0;
6146               h->def_regular = 1;
6147               h->type = STT_OBJECT;
6148               h->verinfo.vertree = NULL;
6149
6150               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6151                 return FALSE;
6152
6153               /* Create a duplicate of the base version with the same
6154                  aux block, but different flags.  */
6155               def.vd_flags = 0;
6156               def.vd_ndx = 2;
6157               def.vd_aux = sizeof (Elf_External_Verdef);
6158               if (verdefs)
6159                 def.vd_next = (sizeof (Elf_External_Verdef)
6160                                + sizeof (Elf_External_Verdaux));
6161               else
6162                 def.vd_next = 0;
6163               _bfd_elf_swap_verdef_out (output_bfd, &def,
6164                                         (Elf_External_Verdef *) p);
6165               p += sizeof (Elf_External_Verdef);
6166             }
6167           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6168                                      (Elf_External_Verdaux *) p);
6169           p += sizeof (Elf_External_Verdaux);
6170
6171           for (t = verdefs; t != NULL; t = t->next)
6172             {
6173               unsigned int cdeps;
6174               struct bfd_elf_version_deps *n;
6175
6176               /* Don't emit the base version twice.  */
6177               if (t->vernum == 0)
6178                 continue;
6179
6180               cdeps = 0;
6181               for (n = t->deps; n != NULL; n = n->next)
6182                 ++cdeps;
6183
6184               /* Add a symbol representing this version.  */
6185               bh = NULL;
6186               if (! (_bfd_generic_link_add_one_symbol
6187                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6188                       0, NULL, FALSE,
6189                       get_elf_backend_data (dynobj)->collect, &bh)))
6190                 return FALSE;
6191               h = (struct elf_link_hash_entry *) bh;
6192               h->non_elf = 0;
6193               h->def_regular = 1;
6194               h->type = STT_OBJECT;
6195               h->verinfo.vertree = t;
6196
6197               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6198                 return FALSE;
6199
6200               def.vd_version = VER_DEF_CURRENT;
6201               def.vd_flags = 0;
6202               if (t->globals.list == NULL
6203                   && t->locals.list == NULL
6204                   && ! t->used)
6205                 def.vd_flags |= VER_FLG_WEAK;
6206               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6207               def.vd_cnt = cdeps + 1;
6208               def.vd_hash = bfd_elf_hash (t->name);
6209               def.vd_aux = sizeof (Elf_External_Verdef);
6210               def.vd_next = 0;
6211
6212               /* If a basever node is next, it *must* be the last node in
6213                  the chain, otherwise Verdef construction breaks.  */
6214               if (t->next != NULL && t->next->vernum == 0)
6215                 BFD_ASSERT (t->next->next == NULL);
6216
6217               if (t->next != NULL && t->next->vernum != 0)
6218                 def.vd_next = (sizeof (Elf_External_Verdef)
6219                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6220
6221               _bfd_elf_swap_verdef_out (output_bfd, &def,
6222                                         (Elf_External_Verdef *) p);
6223               p += sizeof (Elf_External_Verdef);
6224
6225               defaux.vda_name = h->dynstr_index;
6226               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6227                                       h->dynstr_index);
6228               defaux.vda_next = 0;
6229               if (t->deps != NULL)
6230                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6231               t->name_indx = defaux.vda_name;
6232
6233               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6234                                          (Elf_External_Verdaux *) p);
6235               p += sizeof (Elf_External_Verdaux);
6236
6237               for (n = t->deps; n != NULL; n = n->next)
6238                 {
6239                   if (n->version_needed == NULL)
6240                     {
6241                       /* This can happen if there was an error in the
6242                          version script.  */
6243                       defaux.vda_name = 0;
6244                     }
6245                   else
6246                     {
6247                       defaux.vda_name = n->version_needed->name_indx;
6248                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6249                                               defaux.vda_name);
6250                     }
6251                   if (n->next == NULL)
6252                     defaux.vda_next = 0;
6253                   else
6254                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6255
6256                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6257                                              (Elf_External_Verdaux *) p);
6258                   p += sizeof (Elf_External_Verdaux);
6259                 }
6260             }
6261
6262           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6263               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6264             return FALSE;
6265
6266           elf_tdata (output_bfd)->cverdefs = cdefs;
6267         }
6268
6269       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6270         {
6271           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6272             return FALSE;
6273         }
6274       else if (info->flags & DF_BIND_NOW)
6275         {
6276           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6277             return FALSE;
6278         }
6279
6280       if (info->flags_1)
6281         {
6282           if (info->executable)
6283             info->flags_1 &= ~ (DF_1_INITFIRST
6284                                 | DF_1_NODELETE
6285                                 | DF_1_NOOPEN);
6286           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6287             return FALSE;
6288         }
6289
6290       /* Work out the size of the version reference section.  */
6291
6292       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6293       BFD_ASSERT (s != NULL);
6294       {
6295         struct elf_find_verdep_info sinfo;
6296
6297         sinfo.info = info;
6298         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6299         if (sinfo.vers == 0)
6300           sinfo.vers = 1;
6301         sinfo.failed = FALSE;
6302
6303         elf_link_hash_traverse (elf_hash_table (info),
6304                                 _bfd_elf_link_find_version_dependencies,
6305                                 &sinfo);
6306         if (sinfo.failed)
6307           return FALSE;
6308
6309         if (elf_tdata (output_bfd)->verref == NULL)
6310           s->flags |= SEC_EXCLUDE;
6311         else
6312           {
6313             Elf_Internal_Verneed *t;
6314             unsigned int size;
6315             unsigned int crefs;
6316             bfd_byte *p;
6317
6318             /* Build the version dependency section.  */
6319             size = 0;
6320             crefs = 0;
6321             for (t = elf_tdata (output_bfd)->verref;
6322                  t != NULL;
6323                  t = t->vn_nextref)
6324               {
6325                 Elf_Internal_Vernaux *a;
6326
6327                 size += sizeof (Elf_External_Verneed);
6328                 ++crefs;
6329                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6330                   size += sizeof (Elf_External_Vernaux);
6331               }
6332
6333             s->size = size;
6334             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6335             if (s->contents == NULL)
6336               return FALSE;
6337
6338             p = s->contents;
6339             for (t = elf_tdata (output_bfd)->verref;
6340                  t != NULL;
6341                  t = t->vn_nextref)
6342               {
6343                 unsigned int caux;
6344                 Elf_Internal_Vernaux *a;
6345                 bfd_size_type indx;
6346
6347                 caux = 0;
6348                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6349                   ++caux;
6350
6351                 t->vn_version = VER_NEED_CURRENT;
6352                 t->vn_cnt = caux;
6353                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6354                                             elf_dt_name (t->vn_bfd) != NULL
6355                                             ? elf_dt_name (t->vn_bfd)
6356                                             : lbasename (t->vn_bfd->filename),
6357                                             FALSE);
6358                 if (indx == (bfd_size_type) -1)
6359                   return FALSE;
6360                 t->vn_file = indx;
6361                 t->vn_aux = sizeof (Elf_External_Verneed);
6362                 if (t->vn_nextref == NULL)
6363                   t->vn_next = 0;
6364                 else
6365                   t->vn_next = (sizeof (Elf_External_Verneed)
6366                                 + caux * sizeof (Elf_External_Vernaux));
6367
6368                 _bfd_elf_swap_verneed_out (output_bfd, t,
6369                                            (Elf_External_Verneed *) p);
6370                 p += sizeof (Elf_External_Verneed);
6371
6372                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6373                   {
6374                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6375                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6376                                                 a->vna_nodename, FALSE);
6377                     if (indx == (bfd_size_type) -1)
6378                       return FALSE;
6379                     a->vna_name = indx;
6380                     if (a->vna_nextptr == NULL)
6381                       a->vna_next = 0;
6382                     else
6383                       a->vna_next = sizeof (Elf_External_Vernaux);
6384
6385                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6386                                                (Elf_External_Vernaux *) p);
6387                     p += sizeof (Elf_External_Vernaux);
6388                   }
6389               }
6390
6391             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6392                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6393               return FALSE;
6394
6395             elf_tdata (output_bfd)->cverrefs = crefs;
6396           }
6397       }
6398
6399       if ((elf_tdata (output_bfd)->cverrefs == 0
6400            && elf_tdata (output_bfd)->cverdefs == 0)
6401           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6402                                              &section_sym_count) == 0)
6403         {
6404           s = bfd_get_linker_section (dynobj, ".gnu.version");
6405           s->flags |= SEC_EXCLUDE;
6406         }
6407     }
6408   return TRUE;
6409 }
6410
6411 /* Find the first non-excluded output section.  We'll use its
6412    section symbol for some emitted relocs.  */
6413 void
6414 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6415 {
6416   asection *s;
6417
6418   for (s = output_bfd->sections; s != NULL; s = s->next)
6419     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6420         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6421       {
6422         elf_hash_table (info)->text_index_section = s;
6423         break;
6424       }
6425 }
6426
6427 /* Find two non-excluded output sections, one for code, one for data.
6428    We'll use their section symbols for some emitted relocs.  */
6429 void
6430 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6431 {
6432   asection *s;
6433
6434   /* Data first, since setting text_index_section changes
6435      _bfd_elf_link_omit_section_dynsym.  */
6436   for (s = output_bfd->sections; s != NULL; s = s->next)
6437     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6438         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6439       {
6440         elf_hash_table (info)->data_index_section = s;
6441         break;
6442       }
6443
6444   for (s = output_bfd->sections; s != NULL; s = s->next)
6445     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6446          == (SEC_ALLOC | SEC_READONLY))
6447         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6448       {
6449         elf_hash_table (info)->text_index_section = s;
6450         break;
6451       }
6452
6453   if (elf_hash_table (info)->text_index_section == NULL)
6454     elf_hash_table (info)->text_index_section
6455       = elf_hash_table (info)->data_index_section;
6456 }
6457
6458 bfd_boolean
6459 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6460 {
6461   const struct elf_backend_data *bed;
6462
6463   if (!is_elf_hash_table (info->hash))
6464     return TRUE;
6465
6466   bed = get_elf_backend_data (output_bfd);
6467   (*bed->elf_backend_init_index_section) (output_bfd, info);
6468
6469   if (elf_hash_table (info)->dynamic_sections_created)
6470     {
6471       bfd *dynobj;
6472       asection *s;
6473       bfd_size_type dynsymcount;
6474       unsigned long section_sym_count;
6475       unsigned int dtagcount;
6476
6477       dynobj = elf_hash_table (info)->dynobj;
6478
6479       /* Assign dynsym indicies.  In a shared library we generate a
6480          section symbol for each output section, which come first.
6481          Next come all of the back-end allocated local dynamic syms,
6482          followed by the rest of the global symbols.  */
6483
6484       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6485                                                     &section_sym_count);
6486
6487       /* Work out the size of the symbol version section.  */
6488       s = bfd_get_linker_section (dynobj, ".gnu.version");
6489       BFD_ASSERT (s != NULL);
6490       if (dynsymcount != 0
6491           && (s->flags & SEC_EXCLUDE) == 0)
6492         {
6493           s->size = dynsymcount * sizeof (Elf_External_Versym);
6494           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6495           if (s->contents == NULL)
6496             return FALSE;
6497
6498           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6499             return FALSE;
6500         }
6501
6502       /* Set the size of the .dynsym and .hash sections.  We counted
6503          the number of dynamic symbols in elf_link_add_object_symbols.
6504          We will build the contents of .dynsym and .hash when we build
6505          the final symbol table, because until then we do not know the
6506          correct value to give the symbols.  We built the .dynstr
6507          section as we went along in elf_link_add_object_symbols.  */
6508       s = bfd_get_linker_section (dynobj, ".dynsym");
6509       BFD_ASSERT (s != NULL);
6510       s->size = dynsymcount * bed->s->sizeof_sym;
6511
6512       if (dynsymcount != 0)
6513         {
6514           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6515           if (s->contents == NULL)
6516             return FALSE;
6517
6518           /* The first entry in .dynsym is a dummy symbol.
6519              Clear all the section syms, in case we don't output them all.  */
6520           ++section_sym_count;
6521           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6522         }
6523
6524       elf_hash_table (info)->bucketcount = 0;
6525
6526       /* Compute the size of the hashing table.  As a side effect this
6527          computes the hash values for all the names we export.  */
6528       if (info->emit_hash)
6529         {
6530           unsigned long int *hashcodes;
6531           struct hash_codes_info hashinf;
6532           bfd_size_type amt;
6533           unsigned long int nsyms;
6534           size_t bucketcount;
6535           size_t hash_entry_size;
6536
6537           /* Compute the hash values for all exported symbols.  At the same
6538              time store the values in an array so that we could use them for
6539              optimizations.  */
6540           amt = dynsymcount * sizeof (unsigned long int);
6541           hashcodes = (unsigned long int *) bfd_malloc (amt);
6542           if (hashcodes == NULL)
6543             return FALSE;
6544           hashinf.hashcodes = hashcodes;
6545           hashinf.error = FALSE;
6546
6547           /* Put all hash values in HASHCODES.  */
6548           elf_link_hash_traverse (elf_hash_table (info),
6549                                   elf_collect_hash_codes, &hashinf);
6550           if (hashinf.error)
6551             {
6552               free (hashcodes);
6553               return FALSE;
6554             }
6555
6556           nsyms = hashinf.hashcodes - hashcodes;
6557           bucketcount
6558             = compute_bucket_count (info, hashcodes, nsyms, 0);
6559           free (hashcodes);
6560
6561           if (bucketcount == 0)
6562             return FALSE;
6563
6564           elf_hash_table (info)->bucketcount = bucketcount;
6565
6566           s = bfd_get_linker_section (dynobj, ".hash");
6567           BFD_ASSERT (s != NULL);
6568           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6569           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6570           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6571           if (s->contents == NULL)
6572             return FALSE;
6573
6574           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6575           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6576                    s->contents + hash_entry_size);
6577         }
6578
6579       if (info->emit_gnu_hash)
6580         {
6581           size_t i, cnt;
6582           unsigned char *contents;
6583           struct collect_gnu_hash_codes cinfo;
6584           bfd_size_type amt;
6585           size_t bucketcount;
6586
6587           memset (&cinfo, 0, sizeof (cinfo));
6588
6589           /* Compute the hash values for all exported symbols.  At the same
6590              time store the values in an array so that we could use them for
6591              optimizations.  */
6592           amt = dynsymcount * 2 * sizeof (unsigned long int);
6593           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6594           if (cinfo.hashcodes == NULL)
6595             return FALSE;
6596
6597           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6598           cinfo.min_dynindx = -1;
6599           cinfo.output_bfd = output_bfd;
6600           cinfo.bed = bed;
6601
6602           /* Put all hash values in HASHCODES.  */
6603           elf_link_hash_traverse (elf_hash_table (info),
6604                                   elf_collect_gnu_hash_codes, &cinfo);
6605           if (cinfo.error)
6606             {
6607               free (cinfo.hashcodes);
6608               return FALSE;
6609             }
6610
6611           bucketcount
6612             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6613
6614           if (bucketcount == 0)
6615             {
6616               free (cinfo.hashcodes);
6617               return FALSE;
6618             }
6619
6620           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6621           BFD_ASSERT (s != NULL);
6622
6623           if (cinfo.nsyms == 0)
6624             {
6625               /* Empty .gnu.hash section is special.  */
6626               BFD_ASSERT (cinfo.min_dynindx == -1);
6627               free (cinfo.hashcodes);
6628               s->size = 5 * 4 + bed->s->arch_size / 8;
6629               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6630               if (contents == NULL)
6631                 return FALSE;
6632               s->contents = contents;
6633               /* 1 empty bucket.  */
6634               bfd_put_32 (output_bfd, 1, contents);
6635               /* SYMIDX above the special symbol 0.  */
6636               bfd_put_32 (output_bfd, 1, contents + 4);
6637               /* Just one word for bitmask.  */
6638               bfd_put_32 (output_bfd, 1, contents + 8);
6639               /* Only hash fn bloom filter.  */
6640               bfd_put_32 (output_bfd, 0, contents + 12);
6641               /* No hashes are valid - empty bitmask.  */
6642               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6643               /* No hashes in the only bucket.  */
6644               bfd_put_32 (output_bfd, 0,
6645                           contents + 16 + bed->s->arch_size / 8);
6646             }
6647           else
6648             {
6649               unsigned long int maskwords, maskbitslog2, x;
6650               BFD_ASSERT (cinfo.min_dynindx != -1);
6651
6652               x = cinfo.nsyms;
6653               maskbitslog2 = 1;
6654               while ((x >>= 1) != 0)
6655                 ++maskbitslog2;
6656               if (maskbitslog2 < 3)
6657                 maskbitslog2 = 5;
6658               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6659                 maskbitslog2 = maskbitslog2 + 3;
6660               else
6661                 maskbitslog2 = maskbitslog2 + 2;
6662               if (bed->s->arch_size == 64)
6663                 {
6664                   if (maskbitslog2 == 5)
6665                     maskbitslog2 = 6;
6666                   cinfo.shift1 = 6;
6667                 }
6668               else
6669                 cinfo.shift1 = 5;
6670               cinfo.mask = (1 << cinfo.shift1) - 1;
6671               cinfo.shift2 = maskbitslog2;
6672               cinfo.maskbits = 1 << maskbitslog2;
6673               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6674               amt = bucketcount * sizeof (unsigned long int) * 2;
6675               amt += maskwords * sizeof (bfd_vma);
6676               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6677               if (cinfo.bitmask == NULL)
6678                 {
6679                   free (cinfo.hashcodes);
6680                   return FALSE;
6681                 }
6682
6683               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6684               cinfo.indx = cinfo.counts + bucketcount;
6685               cinfo.symindx = dynsymcount - cinfo.nsyms;
6686               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6687
6688               /* Determine how often each hash bucket is used.  */
6689               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6690               for (i = 0; i < cinfo.nsyms; ++i)
6691                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6692
6693               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6694                 if (cinfo.counts[i] != 0)
6695                   {
6696                     cinfo.indx[i] = cnt;
6697                     cnt += cinfo.counts[i];
6698                   }
6699               BFD_ASSERT (cnt == dynsymcount);
6700               cinfo.bucketcount = bucketcount;
6701               cinfo.local_indx = cinfo.min_dynindx;
6702
6703               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6704               s->size += cinfo.maskbits / 8;
6705               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6706               if (contents == NULL)
6707                 {
6708                   free (cinfo.bitmask);
6709                   free (cinfo.hashcodes);
6710                   return FALSE;
6711                 }
6712
6713               s->contents = contents;
6714               bfd_put_32 (output_bfd, bucketcount, contents);
6715               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6716               bfd_put_32 (output_bfd, maskwords, contents + 8);
6717               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6718               contents += 16 + cinfo.maskbits / 8;
6719
6720               for (i = 0; i < bucketcount; ++i)
6721                 {
6722                   if (cinfo.counts[i] == 0)
6723                     bfd_put_32 (output_bfd, 0, contents);
6724                   else
6725                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6726                   contents += 4;
6727                 }
6728
6729               cinfo.contents = contents;
6730
6731               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6732               elf_link_hash_traverse (elf_hash_table (info),
6733                                       elf_renumber_gnu_hash_syms, &cinfo);
6734
6735               contents = s->contents + 16;
6736               for (i = 0; i < maskwords; ++i)
6737                 {
6738                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6739                            contents);
6740                   contents += bed->s->arch_size / 8;
6741                 }
6742
6743               free (cinfo.bitmask);
6744               free (cinfo.hashcodes);
6745             }
6746         }
6747
6748       s = bfd_get_linker_section (dynobj, ".dynstr");
6749       BFD_ASSERT (s != NULL);
6750
6751       elf_finalize_dynstr (output_bfd, info);
6752
6753       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6754
6755       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6756         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6757           return FALSE;
6758     }
6759
6760   return TRUE;
6761 }
6762 \f
6763 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6764
6765 static void
6766 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6767                             asection *sec)
6768 {
6769   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6770   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6771 }
6772
6773 /* Finish SHF_MERGE section merging.  */
6774
6775 bfd_boolean
6776 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6777 {
6778   bfd *ibfd;
6779   asection *sec;
6780
6781   if (!is_elf_hash_table (info->hash))
6782     return FALSE;
6783
6784   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6785     if ((ibfd->flags & DYNAMIC) == 0)
6786       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6787         if ((sec->flags & SEC_MERGE) != 0
6788             && !bfd_is_abs_section (sec->output_section))
6789           {
6790             struct bfd_elf_section_data *secdata;
6791
6792             secdata = elf_section_data (sec);
6793             if (! _bfd_add_merge_section (abfd,
6794                                           &elf_hash_table (info)->merge_info,
6795                                           sec, &secdata->sec_info))
6796               return FALSE;
6797             else if (secdata->sec_info)
6798               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6799           }
6800
6801   if (elf_hash_table (info)->merge_info != NULL)
6802     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6803                          merge_sections_remove_hook);
6804   return TRUE;
6805 }
6806
6807 /* Create an entry in an ELF linker hash table.  */
6808
6809 struct bfd_hash_entry *
6810 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6811                             struct bfd_hash_table *table,
6812                             const char *string)
6813 {
6814   /* Allocate the structure if it has not already been allocated by a
6815      subclass.  */
6816   if (entry == NULL)
6817     {
6818       entry = (struct bfd_hash_entry *)
6819         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6820       if (entry == NULL)
6821         return entry;
6822     }
6823
6824   /* Call the allocation method of the superclass.  */
6825   entry = _bfd_link_hash_newfunc (entry, table, string);
6826   if (entry != NULL)
6827     {
6828       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6829       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6830
6831       /* Set local fields.  */
6832       ret->indx = -1;
6833       ret->dynindx = -1;
6834       ret->got = htab->init_got_refcount;
6835       ret->plt = htab->init_plt_refcount;
6836       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6837                               - offsetof (struct elf_link_hash_entry, size)));
6838       /* Assume that we have been called by a non-ELF symbol reader.
6839          This flag is then reset by the code which reads an ELF input
6840          file.  This ensures that a symbol created by a non-ELF symbol
6841          reader will have the flag set correctly.  */
6842       ret->non_elf = 1;
6843     }
6844
6845   return entry;
6846 }
6847
6848 /* Copy data from an indirect symbol to its direct symbol, hiding the
6849    old indirect symbol.  Also used for copying flags to a weakdef.  */
6850
6851 void
6852 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6853                                   struct elf_link_hash_entry *dir,
6854                                   struct elf_link_hash_entry *ind)
6855 {
6856   struct elf_link_hash_table *htab;
6857
6858   /* Copy down any references that we may have already seen to the
6859      symbol which just became indirect if DIR isn't a hidden versioned
6860      symbol.  */
6861
6862   if (!dir->hidden)
6863     {
6864       dir->ref_dynamic |= ind->ref_dynamic;
6865       dir->ref_regular |= ind->ref_regular;
6866       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6867       dir->non_got_ref |= ind->non_got_ref;
6868       dir->needs_plt |= ind->needs_plt;
6869       dir->pointer_equality_needed |= ind->pointer_equality_needed;
6870     }
6871
6872   if (ind->root.type != bfd_link_hash_indirect)
6873     return;
6874
6875   /* Copy over the global and procedure linkage table refcount entries.
6876      These may have been already set up by a check_relocs routine.  */
6877   htab = elf_hash_table (info);
6878   if (ind->got.refcount > htab->init_got_refcount.refcount)
6879     {
6880       if (dir->got.refcount < 0)
6881         dir->got.refcount = 0;
6882       dir->got.refcount += ind->got.refcount;
6883       ind->got.refcount = htab->init_got_refcount.refcount;
6884     }
6885
6886   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6887     {
6888       if (dir->plt.refcount < 0)
6889         dir->plt.refcount = 0;
6890       dir->plt.refcount += ind->plt.refcount;
6891       ind->plt.refcount = htab->init_plt_refcount.refcount;
6892     }
6893
6894   if (ind->dynindx != -1)
6895     {
6896       if (dir->dynindx != -1)
6897         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6898       dir->dynindx = ind->dynindx;
6899       dir->dynstr_index = ind->dynstr_index;
6900       ind->dynindx = -1;
6901       ind->dynstr_index = 0;
6902     }
6903 }
6904
6905 void
6906 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6907                                 struct elf_link_hash_entry *h,
6908                                 bfd_boolean force_local)
6909 {
6910   /* STT_GNU_IFUNC symbol must go through PLT.  */
6911   if (h->type != STT_GNU_IFUNC)
6912     {
6913       h->plt = elf_hash_table (info)->init_plt_offset;
6914       h->needs_plt = 0;
6915     }
6916   if (force_local)
6917     {
6918       h->forced_local = 1;
6919       if (h->dynindx != -1)
6920         {
6921           h->dynindx = -1;
6922           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6923                                   h->dynstr_index);
6924         }
6925     }
6926 }
6927
6928 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
6929    caller.  */
6930
6931 bfd_boolean
6932 _bfd_elf_link_hash_table_init
6933   (struct elf_link_hash_table *table,
6934    bfd *abfd,
6935    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6936                                       struct bfd_hash_table *,
6937                                       const char *),
6938    unsigned int entsize,
6939    enum elf_target_id target_id)
6940 {
6941   bfd_boolean ret;
6942   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6943
6944   table->init_got_refcount.refcount = can_refcount - 1;
6945   table->init_plt_refcount.refcount = can_refcount - 1;
6946   table->init_got_offset.offset = -(bfd_vma) 1;
6947   table->init_plt_offset.offset = -(bfd_vma) 1;
6948   /* The first dynamic symbol is a dummy.  */
6949   table->dynsymcount = 1;
6950
6951   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6952
6953   table->root.type = bfd_link_elf_hash_table;
6954   table->hash_table_id = target_id;
6955
6956   return ret;
6957 }
6958
6959 /* Create an ELF linker hash table.  */
6960
6961 struct bfd_link_hash_table *
6962 _bfd_elf_link_hash_table_create (bfd *abfd)
6963 {
6964   struct elf_link_hash_table *ret;
6965   bfd_size_type amt = sizeof (struct elf_link_hash_table);
6966
6967   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
6968   if (ret == NULL)
6969     return NULL;
6970
6971   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
6972                                        sizeof (struct elf_link_hash_entry),
6973                                        GENERIC_ELF_DATA))
6974     {
6975       free (ret);
6976       return NULL;
6977     }
6978   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
6979
6980   return &ret->root;
6981 }
6982
6983 /* Destroy an ELF linker hash table.  */
6984
6985 void
6986 _bfd_elf_link_hash_table_free (bfd *obfd)
6987 {
6988   struct elf_link_hash_table *htab;
6989
6990   htab = (struct elf_link_hash_table *) obfd->link.hash;
6991   if (htab->dynstr != NULL)
6992     _bfd_elf_strtab_free (htab->dynstr);
6993   _bfd_merge_sections_free (htab->merge_info);
6994   _bfd_generic_link_hash_table_free (obfd);
6995 }
6996
6997 /* This is a hook for the ELF emulation code in the generic linker to
6998    tell the backend linker what file name to use for the DT_NEEDED
6999    entry for a dynamic object.  */
7000
7001 void
7002 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7003 {
7004   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7005       && bfd_get_format (abfd) == bfd_object)
7006     elf_dt_name (abfd) = name;
7007 }
7008
7009 int
7010 bfd_elf_get_dyn_lib_class (bfd *abfd)
7011 {
7012   int lib_class;
7013   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7014       && bfd_get_format (abfd) == bfd_object)
7015     lib_class = elf_dyn_lib_class (abfd);
7016   else
7017     lib_class = 0;
7018   return lib_class;
7019 }
7020
7021 void
7022 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7023 {
7024   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7025       && bfd_get_format (abfd) == bfd_object)
7026     elf_dyn_lib_class (abfd) = lib_class;
7027 }
7028
7029 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7030    the linker ELF emulation code.  */
7031
7032 struct bfd_link_needed_list *
7033 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7034                          struct bfd_link_info *info)
7035 {
7036   if (! is_elf_hash_table (info->hash))
7037     return NULL;
7038   return elf_hash_table (info)->needed;
7039 }
7040
7041 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7042    hook for the linker ELF emulation code.  */
7043
7044 struct bfd_link_needed_list *
7045 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7046                           struct bfd_link_info *info)
7047 {
7048   if (! is_elf_hash_table (info->hash))
7049     return NULL;
7050   return elf_hash_table (info)->runpath;
7051 }
7052
7053 /* Get the name actually used for a dynamic object for a link.  This
7054    is the SONAME entry if there is one.  Otherwise, it is the string
7055    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7056
7057 const char *
7058 bfd_elf_get_dt_soname (bfd *abfd)
7059 {
7060   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7061       && bfd_get_format (abfd) == bfd_object)
7062     return elf_dt_name (abfd);
7063   return NULL;
7064 }
7065
7066 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7067    the ELF linker emulation code.  */
7068
7069 bfd_boolean
7070 bfd_elf_get_bfd_needed_list (bfd *abfd,
7071                              struct bfd_link_needed_list **pneeded)
7072 {
7073   asection *s;
7074   bfd_byte *dynbuf = NULL;
7075   unsigned int elfsec;
7076   unsigned long shlink;
7077   bfd_byte *extdyn, *extdynend;
7078   size_t extdynsize;
7079   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7080
7081   *pneeded = NULL;
7082
7083   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7084       || bfd_get_format (abfd) != bfd_object)
7085     return TRUE;
7086
7087   s = bfd_get_section_by_name (abfd, ".dynamic");
7088   if (s == NULL || s->size == 0)
7089     return TRUE;
7090
7091   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7092     goto error_return;
7093
7094   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7095   if (elfsec == SHN_BAD)
7096     goto error_return;
7097
7098   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7099
7100   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7101   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7102
7103   extdyn = dynbuf;
7104   extdynend = extdyn + s->size;
7105   for (; extdyn < extdynend; extdyn += extdynsize)
7106     {
7107       Elf_Internal_Dyn dyn;
7108
7109       (*swap_dyn_in) (abfd, extdyn, &dyn);
7110
7111       if (dyn.d_tag == DT_NULL)
7112         break;
7113
7114       if (dyn.d_tag == DT_NEEDED)
7115         {
7116           const char *string;
7117           struct bfd_link_needed_list *l;
7118           unsigned int tagv = dyn.d_un.d_val;
7119           bfd_size_type amt;
7120
7121           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7122           if (string == NULL)
7123             goto error_return;
7124
7125           amt = sizeof *l;
7126           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7127           if (l == NULL)
7128             goto error_return;
7129
7130           l->by = abfd;
7131           l->name = string;
7132           l->next = *pneeded;
7133           *pneeded = l;
7134         }
7135     }
7136
7137   free (dynbuf);
7138
7139   return TRUE;
7140
7141  error_return:
7142   if (dynbuf != NULL)
7143     free (dynbuf);
7144   return FALSE;
7145 }
7146
7147 struct elf_symbuf_symbol
7148 {
7149   unsigned long st_name;        /* Symbol name, index in string tbl */
7150   unsigned char st_info;        /* Type and binding attributes */
7151   unsigned char st_other;       /* Visibilty, and target specific */
7152 };
7153
7154 struct elf_symbuf_head
7155 {
7156   struct elf_symbuf_symbol *ssym;
7157   bfd_size_type count;
7158   unsigned int st_shndx;
7159 };
7160
7161 struct elf_symbol
7162 {
7163   union
7164     {
7165       Elf_Internal_Sym *isym;
7166       struct elf_symbuf_symbol *ssym;
7167     } u;
7168   const char *name;
7169 };
7170
7171 /* Sort references to symbols by ascending section number.  */
7172
7173 static int
7174 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7175 {
7176   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7177   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7178
7179   return s1->st_shndx - s2->st_shndx;
7180 }
7181
7182 static int
7183 elf_sym_name_compare (const void *arg1, const void *arg2)
7184 {
7185   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7186   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7187   return strcmp (s1->name, s2->name);
7188 }
7189
7190 static struct elf_symbuf_head *
7191 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7192 {
7193   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7194   struct elf_symbuf_symbol *ssym;
7195   struct elf_symbuf_head *ssymbuf, *ssymhead;
7196   bfd_size_type i, shndx_count, total_size;
7197
7198   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7199   if (indbuf == NULL)
7200     return NULL;
7201
7202   for (ind = indbuf, i = 0; i < symcount; i++)
7203     if (isymbuf[i].st_shndx != SHN_UNDEF)
7204       *ind++ = &isymbuf[i];
7205   indbufend = ind;
7206
7207   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7208          elf_sort_elf_symbol);
7209
7210   shndx_count = 0;
7211   if (indbufend > indbuf)
7212     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7213       if (ind[0]->st_shndx != ind[1]->st_shndx)
7214         shndx_count++;
7215
7216   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7217                 + (indbufend - indbuf) * sizeof (*ssym));
7218   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7219   if (ssymbuf == NULL)
7220     {
7221       free (indbuf);
7222       return NULL;
7223     }
7224
7225   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7226   ssymbuf->ssym = NULL;
7227   ssymbuf->count = shndx_count;
7228   ssymbuf->st_shndx = 0;
7229   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7230     {
7231       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7232         {
7233           ssymhead++;
7234           ssymhead->ssym = ssym;
7235           ssymhead->count = 0;
7236           ssymhead->st_shndx = (*ind)->st_shndx;
7237         }
7238       ssym->st_name = (*ind)->st_name;
7239       ssym->st_info = (*ind)->st_info;
7240       ssym->st_other = (*ind)->st_other;
7241       ssymhead->count++;
7242     }
7243   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7244               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7245                   == total_size));
7246
7247   free (indbuf);
7248   return ssymbuf;
7249 }
7250
7251 /* Check if 2 sections define the same set of local and global
7252    symbols.  */
7253
7254 static bfd_boolean
7255 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7256                                    struct bfd_link_info *info)
7257 {
7258   bfd *bfd1, *bfd2;
7259   const struct elf_backend_data *bed1, *bed2;
7260   Elf_Internal_Shdr *hdr1, *hdr2;
7261   bfd_size_type symcount1, symcount2;
7262   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7263   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7264   Elf_Internal_Sym *isym, *isymend;
7265   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7266   bfd_size_type count1, count2, i;
7267   unsigned int shndx1, shndx2;
7268   bfd_boolean result;
7269
7270   bfd1 = sec1->owner;
7271   bfd2 = sec2->owner;
7272
7273   /* Both sections have to be in ELF.  */
7274   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7275       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7276     return FALSE;
7277
7278   if (elf_section_type (sec1) != elf_section_type (sec2))
7279     return FALSE;
7280
7281   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7282   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7283   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7284     return FALSE;
7285
7286   bed1 = get_elf_backend_data (bfd1);
7287   bed2 = get_elf_backend_data (bfd2);
7288   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7289   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7290   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7291   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7292
7293   if (symcount1 == 0 || symcount2 == 0)
7294     return FALSE;
7295
7296   result = FALSE;
7297   isymbuf1 = NULL;
7298   isymbuf2 = NULL;
7299   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7300   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7301
7302   if (ssymbuf1 == NULL)
7303     {
7304       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7305                                        NULL, NULL, NULL);
7306       if (isymbuf1 == NULL)
7307         goto done;
7308
7309       if (!info->reduce_memory_overheads)
7310         elf_tdata (bfd1)->symbuf = ssymbuf1
7311           = elf_create_symbuf (symcount1, isymbuf1);
7312     }
7313
7314   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7315     {
7316       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7317                                        NULL, NULL, NULL);
7318       if (isymbuf2 == NULL)
7319         goto done;
7320
7321       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7322         elf_tdata (bfd2)->symbuf = ssymbuf2
7323           = elf_create_symbuf (symcount2, isymbuf2);
7324     }
7325
7326   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7327     {
7328       /* Optimized faster version.  */
7329       bfd_size_type lo, hi, mid;
7330       struct elf_symbol *symp;
7331       struct elf_symbuf_symbol *ssym, *ssymend;
7332
7333       lo = 0;
7334       hi = ssymbuf1->count;
7335       ssymbuf1++;
7336       count1 = 0;
7337       while (lo < hi)
7338         {
7339           mid = (lo + hi) / 2;
7340           if (shndx1 < ssymbuf1[mid].st_shndx)
7341             hi = mid;
7342           else if (shndx1 > ssymbuf1[mid].st_shndx)
7343             lo = mid + 1;
7344           else
7345             {
7346               count1 = ssymbuf1[mid].count;
7347               ssymbuf1 += mid;
7348               break;
7349             }
7350         }
7351
7352       lo = 0;
7353       hi = ssymbuf2->count;
7354       ssymbuf2++;
7355       count2 = 0;
7356       while (lo < hi)
7357         {
7358           mid = (lo + hi) / 2;
7359           if (shndx2 < ssymbuf2[mid].st_shndx)
7360             hi = mid;
7361           else if (shndx2 > ssymbuf2[mid].st_shndx)
7362             lo = mid + 1;
7363           else
7364             {
7365               count2 = ssymbuf2[mid].count;
7366               ssymbuf2 += mid;
7367               break;
7368             }
7369         }
7370
7371       if (count1 == 0 || count2 == 0 || count1 != count2)
7372         goto done;
7373
7374       symtable1
7375         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7376       symtable2
7377         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7378       if (symtable1 == NULL || symtable2 == NULL)
7379         goto done;
7380
7381       symp = symtable1;
7382       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7383            ssym < ssymend; ssym++, symp++)
7384         {
7385           symp->u.ssym = ssym;
7386           symp->name = bfd_elf_string_from_elf_section (bfd1,
7387                                                         hdr1->sh_link,
7388                                                         ssym->st_name);
7389         }
7390
7391       symp = symtable2;
7392       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7393            ssym < ssymend; ssym++, symp++)
7394         {
7395           symp->u.ssym = ssym;
7396           symp->name = bfd_elf_string_from_elf_section (bfd2,
7397                                                         hdr2->sh_link,
7398                                                         ssym->st_name);
7399         }
7400
7401       /* Sort symbol by name.  */
7402       qsort (symtable1, count1, sizeof (struct elf_symbol),
7403              elf_sym_name_compare);
7404       qsort (symtable2, count1, sizeof (struct elf_symbol),
7405              elf_sym_name_compare);
7406
7407       for (i = 0; i < count1; i++)
7408         /* Two symbols must have the same binding, type and name.  */
7409         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7410             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7411             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7412           goto done;
7413
7414       result = TRUE;
7415       goto done;
7416     }
7417
7418   symtable1 = (struct elf_symbol *)
7419       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7420   symtable2 = (struct elf_symbol *)
7421       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7422   if (symtable1 == NULL || symtable2 == NULL)
7423     goto done;
7424
7425   /* Count definitions in the section.  */
7426   count1 = 0;
7427   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7428     if (isym->st_shndx == shndx1)
7429       symtable1[count1++].u.isym = isym;
7430
7431   count2 = 0;
7432   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7433     if (isym->st_shndx == shndx2)
7434       symtable2[count2++].u.isym = isym;
7435
7436   if (count1 == 0 || count2 == 0 || count1 != count2)
7437     goto done;
7438
7439   for (i = 0; i < count1; i++)
7440     symtable1[i].name
7441       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7442                                          symtable1[i].u.isym->st_name);
7443
7444   for (i = 0; i < count2; i++)
7445     symtable2[i].name
7446       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7447                                          symtable2[i].u.isym->st_name);
7448
7449   /* Sort symbol by name.  */
7450   qsort (symtable1, count1, sizeof (struct elf_symbol),
7451          elf_sym_name_compare);
7452   qsort (symtable2, count1, sizeof (struct elf_symbol),
7453          elf_sym_name_compare);
7454
7455   for (i = 0; i < count1; i++)
7456     /* Two symbols must have the same binding, type and name.  */
7457     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7458         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7459         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7460       goto done;
7461
7462   result = TRUE;
7463
7464 done:
7465   if (symtable1)
7466     free (symtable1);
7467   if (symtable2)
7468     free (symtable2);
7469   if (isymbuf1)
7470     free (isymbuf1);
7471   if (isymbuf2)
7472     free (isymbuf2);
7473
7474   return result;
7475 }
7476
7477 /* Return TRUE if 2 section types are compatible.  */
7478
7479 bfd_boolean
7480 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7481                                  bfd *bbfd, const asection *bsec)
7482 {
7483   if (asec == NULL
7484       || bsec == NULL
7485       || abfd->xvec->flavour != bfd_target_elf_flavour
7486       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7487     return TRUE;
7488
7489   return elf_section_type (asec) == elf_section_type (bsec);
7490 }
7491 \f
7492 /* Final phase of ELF linker.  */
7493
7494 /* A structure we use to avoid passing large numbers of arguments.  */
7495
7496 struct elf_final_link_info
7497 {
7498   /* General link information.  */
7499   struct bfd_link_info *info;
7500   /* Output BFD.  */
7501   bfd *output_bfd;
7502   /* Symbol string table.  */
7503   struct elf_strtab_hash *symstrtab;
7504   /* .dynsym section.  */
7505   asection *dynsym_sec;
7506   /* .hash section.  */
7507   asection *hash_sec;
7508   /* symbol version section (.gnu.version).  */
7509   asection *symver_sec;
7510   /* Buffer large enough to hold contents of any section.  */
7511   bfd_byte *contents;
7512   /* Buffer large enough to hold external relocs of any section.  */
7513   void *external_relocs;
7514   /* Buffer large enough to hold internal relocs of any section.  */
7515   Elf_Internal_Rela *internal_relocs;
7516   /* Buffer large enough to hold external local symbols of any input
7517      BFD.  */
7518   bfd_byte *external_syms;
7519   /* And a buffer for symbol section indices.  */
7520   Elf_External_Sym_Shndx *locsym_shndx;
7521   /* Buffer large enough to hold internal local symbols of any input
7522      BFD.  */
7523   Elf_Internal_Sym *internal_syms;
7524   /* Array large enough to hold a symbol index for each local symbol
7525      of any input BFD.  */
7526   long *indices;
7527   /* Array large enough to hold a section pointer for each local
7528      symbol of any input BFD.  */
7529   asection **sections;
7530   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7531   Elf_External_Sym_Shndx *symshndxbuf;
7532   /* Number of STT_FILE syms seen.  */
7533   size_t filesym_count;
7534 };
7535
7536 /* This struct is used to pass information to elf_link_output_extsym.  */
7537
7538 struct elf_outext_info
7539 {
7540   bfd_boolean failed;
7541   bfd_boolean localsyms;
7542   bfd_boolean file_sym_done;
7543   struct elf_final_link_info *flinfo;
7544 };
7545
7546
7547 /* Support for evaluating a complex relocation.
7548
7549    Complex relocations are generalized, self-describing relocations.  The
7550    implementation of them consists of two parts: complex symbols, and the
7551    relocations themselves.
7552
7553    The relocations are use a reserved elf-wide relocation type code (R_RELC
7554    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7555    information (start bit, end bit, word width, etc) into the addend.  This
7556    information is extracted from CGEN-generated operand tables within gas.
7557
7558    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7559    internal) representing prefix-notation expressions, including but not
7560    limited to those sorts of expressions normally encoded as addends in the
7561    addend field.  The symbol mangling format is:
7562
7563    <node> := <literal>
7564           |  <unary-operator> ':' <node>
7565           |  <binary-operator> ':' <node> ':' <node>
7566           ;
7567
7568    <literal> := 's' <digits=N> ':' <N character symbol name>
7569              |  'S' <digits=N> ':' <N character section name>
7570              |  '#' <hexdigits>
7571              ;
7572
7573    <binary-operator> := as in C
7574    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7575
7576 static void
7577 set_symbol_value (bfd *bfd_with_globals,
7578                   Elf_Internal_Sym *isymbuf,
7579                   size_t locsymcount,
7580                   size_t symidx,
7581                   bfd_vma val)
7582 {
7583   struct elf_link_hash_entry **sym_hashes;
7584   struct elf_link_hash_entry *h;
7585   size_t extsymoff = locsymcount;
7586
7587   if (symidx < locsymcount)
7588     {
7589       Elf_Internal_Sym *sym;
7590
7591       sym = isymbuf + symidx;
7592       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7593         {
7594           /* It is a local symbol: move it to the
7595              "absolute" section and give it a value.  */
7596           sym->st_shndx = SHN_ABS;
7597           sym->st_value = val;
7598           return;
7599         }
7600       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7601       extsymoff = 0;
7602     }
7603
7604   /* It is a global symbol: set its link type
7605      to "defined" and give it a value.  */
7606
7607   sym_hashes = elf_sym_hashes (bfd_with_globals);
7608   h = sym_hashes [symidx - extsymoff];
7609   while (h->root.type == bfd_link_hash_indirect
7610          || h->root.type == bfd_link_hash_warning)
7611     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7612   h->root.type = bfd_link_hash_defined;
7613   h->root.u.def.value = val;
7614   h->root.u.def.section = bfd_abs_section_ptr;
7615 }
7616
7617 static bfd_boolean
7618 resolve_symbol (const char *name,
7619                 bfd *input_bfd,
7620                 struct elf_final_link_info *flinfo,
7621                 bfd_vma *result,
7622                 Elf_Internal_Sym *isymbuf,
7623                 size_t locsymcount)
7624 {
7625   Elf_Internal_Sym *sym;
7626   struct bfd_link_hash_entry *global_entry;
7627   const char *candidate = NULL;
7628   Elf_Internal_Shdr *symtab_hdr;
7629   size_t i;
7630
7631   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7632
7633   for (i = 0; i < locsymcount; ++ i)
7634     {
7635       sym = isymbuf + i;
7636
7637       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7638         continue;
7639
7640       candidate = bfd_elf_string_from_elf_section (input_bfd,
7641                                                    symtab_hdr->sh_link,
7642                                                    sym->st_name);
7643 #ifdef DEBUG
7644       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7645               name, candidate, (unsigned long) sym->st_value);
7646 #endif
7647       if (candidate && strcmp (candidate, name) == 0)
7648         {
7649           asection *sec = flinfo->sections [i];
7650
7651           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7652           *result += sec->output_offset + sec->output_section->vma;
7653 #ifdef DEBUG
7654           printf ("Found symbol with value %8.8lx\n",
7655                   (unsigned long) *result);
7656 #endif
7657           return TRUE;
7658         }
7659     }
7660
7661   /* Hmm, haven't found it yet. perhaps it is a global.  */
7662   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7663                                        FALSE, FALSE, TRUE);
7664   if (!global_entry)
7665     return FALSE;
7666
7667   if (global_entry->type == bfd_link_hash_defined
7668       || global_entry->type == bfd_link_hash_defweak)
7669     {
7670       *result = (global_entry->u.def.value
7671                  + global_entry->u.def.section->output_section->vma
7672                  + global_entry->u.def.section->output_offset);
7673 #ifdef DEBUG
7674       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7675               global_entry->root.string, (unsigned long) *result);
7676 #endif
7677       return TRUE;
7678     }
7679
7680   return FALSE;
7681 }
7682
7683 static bfd_boolean
7684 resolve_section (const char *name,
7685                  asection *sections,
7686                  bfd_vma *result)
7687 {
7688   asection *curr;
7689   unsigned int len;
7690
7691   for (curr = sections; curr; curr = curr->next)
7692     if (strcmp (curr->name, name) == 0)
7693       {
7694         *result = curr->vma;
7695         return TRUE;
7696       }
7697
7698   /* Hmm. still haven't found it. try pseudo-section names.  */
7699   for (curr = sections; curr; curr = curr->next)
7700     {
7701       len = strlen (curr->name);
7702       if (len > strlen (name))
7703         continue;
7704
7705       if (strncmp (curr->name, name, len) == 0)
7706         {
7707           if (strncmp (".end", name + len, 4) == 0)
7708             {
7709               *result = curr->vma + curr->size;
7710               return TRUE;
7711             }
7712
7713           /* Insert more pseudo-section names here, if you like.  */
7714         }
7715     }
7716
7717   return FALSE;
7718 }
7719
7720 static void
7721 undefined_reference (const char *reftype, const char *name)
7722 {
7723   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7724                       reftype, name);
7725 }
7726
7727 static bfd_boolean
7728 eval_symbol (bfd_vma *result,
7729              const char **symp,
7730              bfd *input_bfd,
7731              struct elf_final_link_info *flinfo,
7732              bfd_vma dot,
7733              Elf_Internal_Sym *isymbuf,
7734              size_t locsymcount,
7735              int signed_p)
7736 {
7737   size_t len;
7738   size_t symlen;
7739   bfd_vma a;
7740   bfd_vma b;
7741   char symbuf[4096];
7742   const char *sym = *symp;
7743   const char *symend;
7744   bfd_boolean symbol_is_section = FALSE;
7745
7746   len = strlen (sym);
7747   symend = sym + len;
7748
7749   if (len < 1 || len > sizeof (symbuf))
7750     {
7751       bfd_set_error (bfd_error_invalid_operation);
7752       return FALSE;
7753     }
7754
7755   switch (* sym)
7756     {
7757     case '.':
7758       *result = dot;
7759       *symp = sym + 1;
7760       return TRUE;
7761
7762     case '#':
7763       ++sym;
7764       *result = strtoul (sym, (char **) symp, 16);
7765       return TRUE;
7766
7767     case 'S':
7768       symbol_is_section = TRUE;
7769     case 's':
7770       ++sym;
7771       symlen = strtol (sym, (char **) symp, 10);
7772       sym = *symp + 1; /* Skip the trailing ':'.  */
7773
7774       if (symend < sym || symlen + 1 > sizeof (symbuf))
7775         {
7776           bfd_set_error (bfd_error_invalid_operation);
7777           return FALSE;
7778         }
7779
7780       memcpy (symbuf, sym, symlen);
7781       symbuf[symlen] = '\0';
7782       *symp = sym + symlen;
7783
7784       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7785          the symbol as a section, or vice-versa. so we're pretty liberal in our
7786          interpretation here; section means "try section first", not "must be a
7787          section", and likewise with symbol.  */
7788
7789       if (symbol_is_section)
7790         {
7791           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result)
7792               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7793                                   isymbuf, locsymcount))
7794             {
7795               undefined_reference ("section", symbuf);
7796               return FALSE;
7797             }
7798         }
7799       else
7800         {
7801           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7802                                isymbuf, locsymcount)
7803               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7804                                    result))
7805             {
7806               undefined_reference ("symbol", symbuf);
7807               return FALSE;
7808             }
7809         }
7810
7811       return TRUE;
7812
7813       /* All that remains are operators.  */
7814
7815 #define UNARY_OP(op)                                            \
7816   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7817     {                                                           \
7818       sym += strlen (#op);                                      \
7819       if (*sym == ':')                                          \
7820         ++sym;                                                  \
7821       *symp = sym;                                              \
7822       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7823                         isymbuf, locsymcount, signed_p))        \
7824         return FALSE;                                           \
7825       if (signed_p)                                             \
7826         *result = op ((bfd_signed_vma) a);                      \
7827       else                                                      \
7828         *result = op a;                                         \
7829       return TRUE;                                              \
7830     }
7831
7832 #define BINARY_OP(op)                                           \
7833   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7834     {                                                           \
7835       sym += strlen (#op);                                      \
7836       if (*sym == ':')                                          \
7837         ++sym;                                                  \
7838       *symp = sym;                                              \
7839       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7840                         isymbuf, locsymcount, signed_p))        \
7841         return FALSE;                                           \
7842       ++*symp;                                                  \
7843       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7844                         isymbuf, locsymcount, signed_p))        \
7845         return FALSE;                                           \
7846       if (signed_p)                                             \
7847         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7848       else                                                      \
7849         *result = a op b;                                       \
7850       return TRUE;                                              \
7851     }
7852
7853     default:
7854       UNARY_OP  (0-);
7855       BINARY_OP (<<);
7856       BINARY_OP (>>);
7857       BINARY_OP (==);
7858       BINARY_OP (!=);
7859       BINARY_OP (<=);
7860       BINARY_OP (>=);
7861       BINARY_OP (&&);
7862       BINARY_OP (||);
7863       UNARY_OP  (~);
7864       UNARY_OP  (!);
7865       BINARY_OP (*);
7866       BINARY_OP (/);
7867       BINARY_OP (%);
7868       BINARY_OP (^);
7869       BINARY_OP (|);
7870       BINARY_OP (&);
7871       BINARY_OP (+);
7872       BINARY_OP (-);
7873       BINARY_OP (<);
7874       BINARY_OP (>);
7875 #undef UNARY_OP
7876 #undef BINARY_OP
7877       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7878       bfd_set_error (bfd_error_invalid_operation);
7879       return FALSE;
7880     }
7881 }
7882
7883 static void
7884 put_value (bfd_vma size,
7885            unsigned long chunksz,
7886            bfd *input_bfd,
7887            bfd_vma x,
7888            bfd_byte *location)
7889 {
7890   location += (size - chunksz);
7891
7892   for (; size; size -= chunksz, location -= chunksz)
7893     {
7894       switch (chunksz)
7895         {
7896         case 1:
7897           bfd_put_8 (input_bfd, x, location);
7898           x >>= 8;
7899           break;
7900         case 2:
7901           bfd_put_16 (input_bfd, x, location);
7902           x >>= 16;
7903           break;
7904         case 4:
7905           bfd_put_32 (input_bfd, x, location);
7906           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
7907           x >>= 16;
7908           x >>= 16;
7909           break;
7910 #ifdef BFD64
7911         case 8:
7912           bfd_put_64 (input_bfd, x, location);
7913           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
7914           x >>= 32;
7915           x >>= 32;
7916           break;
7917 #endif
7918         default:
7919           abort ();
7920           break;
7921         }
7922     }
7923 }
7924
7925 static bfd_vma
7926 get_value (bfd_vma size,
7927            unsigned long chunksz,
7928            bfd *input_bfd,
7929            bfd_byte *location)
7930 {
7931   int shift;
7932   bfd_vma x = 0;
7933
7934   /* Sanity checks.  */
7935   BFD_ASSERT (chunksz <= sizeof (x)
7936               && size >= chunksz
7937               && chunksz != 0
7938               && (size % chunksz) == 0
7939               && input_bfd != NULL
7940               && location != NULL);
7941
7942   if (chunksz == sizeof (x))
7943     {
7944       BFD_ASSERT (size == chunksz);
7945
7946       /* Make sure that we do not perform an undefined shift operation.
7947          We know that size == chunksz so there will only be one iteration
7948          of the loop below.  */
7949       shift = 0;
7950     }
7951   else
7952     shift = 8 * chunksz;
7953
7954   for (; size; size -= chunksz, location += chunksz)
7955     {
7956       switch (chunksz)
7957         {
7958         case 1:
7959           x = (x << shift) | bfd_get_8 (input_bfd, location);
7960           break;
7961         case 2:
7962           x = (x << shift) | bfd_get_16 (input_bfd, location);
7963           break;
7964         case 4:
7965           x = (x << shift) | bfd_get_32 (input_bfd, location);
7966           break;
7967 #ifdef BFD64
7968         case 8:
7969           x = (x << shift) | bfd_get_64 (input_bfd, location);
7970           break;
7971 #endif
7972         default:
7973           abort ();
7974         }
7975     }
7976   return x;
7977 }
7978
7979 static void
7980 decode_complex_addend (unsigned long *start,   /* in bits */
7981                        unsigned long *oplen,   /* in bits */
7982                        unsigned long *len,     /* in bits */
7983                        unsigned long *wordsz,  /* in bytes */
7984                        unsigned long *chunksz, /* in bytes */
7985                        unsigned long *lsb0_p,
7986                        unsigned long *signed_p,
7987                        unsigned long *trunc_p,
7988                        unsigned long encoded)
7989 {
7990   * start     =  encoded        & 0x3F;
7991   * len       = (encoded >>  6) & 0x3F;
7992   * oplen     = (encoded >> 12) & 0x3F;
7993   * wordsz    = (encoded >> 18) & 0xF;
7994   * chunksz   = (encoded >> 22) & 0xF;
7995   * lsb0_p    = (encoded >> 27) & 1;
7996   * signed_p  = (encoded >> 28) & 1;
7997   * trunc_p   = (encoded >> 29) & 1;
7998 }
7999
8000 bfd_reloc_status_type
8001 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8002                                     asection *input_section ATTRIBUTE_UNUSED,
8003                                     bfd_byte *contents,
8004                                     Elf_Internal_Rela *rel,
8005                                     bfd_vma relocation)
8006 {
8007   bfd_vma shift, x, mask;
8008   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8009   bfd_reloc_status_type r;
8010
8011   /*  Perform this reloc, since it is complex.
8012       (this is not to say that it necessarily refers to a complex
8013       symbol; merely that it is a self-describing CGEN based reloc.
8014       i.e. the addend has the complete reloc information (bit start, end,
8015       word size, etc) encoded within it.).  */
8016
8017   decode_complex_addend (&start, &oplen, &len, &wordsz,
8018                          &chunksz, &lsb0_p, &signed_p,
8019                          &trunc_p, rel->r_addend);
8020
8021   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8022
8023   if (lsb0_p)
8024     shift = (start + 1) - len;
8025   else
8026     shift = (8 * wordsz) - (start + len);
8027
8028   /* FIXME: octets_per_byte.  */
8029   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
8030
8031 #ifdef DEBUG
8032   printf ("Doing complex reloc: "
8033           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8034           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8035           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8036           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8037           oplen, (unsigned long) x, (unsigned long) mask,
8038           (unsigned long) relocation);
8039 #endif
8040
8041   r = bfd_reloc_ok;
8042   if (! trunc_p)
8043     /* Now do an overflow check.  */
8044     r = bfd_check_overflow ((signed_p
8045                              ? complain_overflow_signed
8046                              : complain_overflow_unsigned),
8047                             len, 0, (8 * wordsz),
8048                             relocation);
8049
8050   /* Do the deed.  */
8051   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8052
8053 #ifdef DEBUG
8054   printf ("           relocation: %8.8lx\n"
8055           "         shifted mask: %8.8lx\n"
8056           " shifted/masked reloc: %8.8lx\n"
8057           "               result: %8.8lx\n",
8058           (unsigned long) relocation, (unsigned long) (mask << shift),
8059           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8060 #endif
8061   /* FIXME: octets_per_byte.  */
8062   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
8063   return r;
8064 }
8065
8066 /* qsort comparison functions sorting external relocs by r_offset.  */
8067
8068 static int
8069 cmp_ext32l_r_offset (const void *p, const void *q)
8070 {
8071   union aligned32
8072   {
8073     uint32_t v;
8074     unsigned char c[4];
8075   };
8076   const union aligned32 *a
8077     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8078   const union aligned32 *b
8079     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8080
8081   uint32_t aval = (  (uint32_t) a->c[0]
8082                    | (uint32_t) a->c[1] << 8
8083                    | (uint32_t) a->c[2] << 16
8084                    | (uint32_t) a->c[3] << 24);
8085   uint32_t bval = (  (uint32_t) b->c[0]
8086                    | (uint32_t) b->c[1] << 8
8087                    | (uint32_t) b->c[2] << 16
8088                    | (uint32_t) b->c[3] << 24);
8089   if (aval < bval)
8090     return -1;
8091   else if (aval > bval)
8092     return 1;
8093   return 0;
8094 }
8095
8096 static int
8097 cmp_ext32b_r_offset (const void *p, const void *q)
8098 {
8099   union aligned32
8100   {
8101     uint32_t v;
8102     unsigned char c[4];
8103   };
8104   const union aligned32 *a
8105     = (const union aligned32 *) ((const Elf32_External_Rel *) p)->r_offset;
8106   const union aligned32 *b
8107     = (const union aligned32 *) ((const Elf32_External_Rel *) q)->r_offset;
8108
8109   uint32_t aval = (  (uint32_t) a->c[0] << 24
8110                    | (uint32_t) a->c[1] << 16
8111                    | (uint32_t) a->c[2] << 8
8112                    | (uint32_t) a->c[3]);
8113   uint32_t bval = (  (uint32_t) b->c[0] << 24
8114                    | (uint32_t) b->c[1] << 16
8115                    | (uint32_t) b->c[2] << 8
8116                    | (uint32_t) b->c[3]);
8117   if (aval < bval)
8118     return -1;
8119   else if (aval > bval)
8120     return 1;
8121   return 0;
8122 }
8123
8124 #ifdef BFD_HOST_64_BIT
8125 static int
8126 cmp_ext64l_r_offset (const void *p, const void *q)
8127 {
8128   union aligned64
8129   {
8130     uint64_t v;
8131     unsigned char c[8];
8132   };
8133   const union aligned64 *a
8134     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8135   const union aligned64 *b
8136     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8137
8138   uint64_t aval = (  (uint64_t) a->c[0]
8139                    | (uint64_t) a->c[1] << 8
8140                    | (uint64_t) a->c[2] << 16
8141                    | (uint64_t) a->c[3] << 24
8142                    | (uint64_t) a->c[4] << 32
8143                    | (uint64_t) a->c[5] << 40
8144                    | (uint64_t) a->c[6] << 48
8145                    | (uint64_t) a->c[7] << 56);
8146   uint64_t bval = (  (uint64_t) b->c[0]
8147                    | (uint64_t) b->c[1] << 8
8148                    | (uint64_t) b->c[2] << 16
8149                    | (uint64_t) b->c[3] << 24
8150                    | (uint64_t) b->c[4] << 32
8151                    | (uint64_t) b->c[5] << 40
8152                    | (uint64_t) b->c[6] << 48
8153                    | (uint64_t) b->c[7] << 56);
8154   if (aval < bval)
8155     return -1;
8156   else if (aval > bval)
8157     return 1;
8158   return 0;
8159 }
8160
8161 static int
8162 cmp_ext64b_r_offset (const void *p, const void *q)
8163 {
8164   union aligned64
8165   {
8166     uint64_t v;
8167     unsigned char c[8];
8168   };
8169   const union aligned64 *a
8170     = (const union aligned64 *) ((const Elf64_External_Rel *) p)->r_offset;
8171   const union aligned64 *b
8172     = (const union aligned64 *) ((const Elf64_External_Rel *) q)->r_offset;
8173
8174   uint64_t aval = (  (uint64_t) a->c[0] << 56
8175                    | (uint64_t) a->c[1] << 48
8176                    | (uint64_t) a->c[2] << 40
8177                    | (uint64_t) a->c[3] << 32
8178                    | (uint64_t) a->c[4] << 24
8179                    | (uint64_t) a->c[5] << 16
8180                    | (uint64_t) a->c[6] << 8
8181                    | (uint64_t) a->c[7]);
8182   uint64_t bval = (  (uint64_t) b->c[0] << 56
8183                    | (uint64_t) b->c[1] << 48
8184                    | (uint64_t) b->c[2] << 40
8185                    | (uint64_t) b->c[3] << 32
8186                    | (uint64_t) b->c[4] << 24
8187                    | (uint64_t) b->c[5] << 16
8188                    | (uint64_t) b->c[6] << 8
8189                    | (uint64_t) b->c[7]);
8190   if (aval < bval)
8191     return -1;
8192   else if (aval > bval)
8193     return 1;
8194   return 0;
8195 }
8196 #endif
8197
8198 /* When performing a relocatable link, the input relocations are
8199    preserved.  But, if they reference global symbols, the indices
8200    referenced must be updated.  Update all the relocations found in
8201    RELDATA.  */
8202
8203 static void
8204 elf_link_adjust_relocs (bfd *abfd,
8205                         struct bfd_elf_section_reloc_data *reldata,
8206                         bfd_boolean sort)
8207 {
8208   unsigned int i;
8209   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8210   bfd_byte *erela;
8211   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8212   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8213   bfd_vma r_type_mask;
8214   int r_sym_shift;
8215   unsigned int count = reldata->count;
8216   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8217
8218   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8219     {
8220       swap_in = bed->s->swap_reloc_in;
8221       swap_out = bed->s->swap_reloc_out;
8222     }
8223   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8224     {
8225       swap_in = bed->s->swap_reloca_in;
8226       swap_out = bed->s->swap_reloca_out;
8227     }
8228   else
8229     abort ();
8230
8231   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8232     abort ();
8233
8234   if (bed->s->arch_size == 32)
8235     {
8236       r_type_mask = 0xff;
8237       r_sym_shift = 8;
8238     }
8239   else
8240     {
8241       r_type_mask = 0xffffffff;
8242       r_sym_shift = 32;
8243     }
8244
8245   erela = reldata->hdr->contents;
8246   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8247     {
8248       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8249       unsigned int j;
8250
8251       if (*rel_hash == NULL)
8252         continue;
8253
8254       BFD_ASSERT ((*rel_hash)->indx >= 0);
8255
8256       (*swap_in) (abfd, erela, irela);
8257       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8258         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8259                            | (irela[j].r_info & r_type_mask));
8260       (*swap_out) (abfd, irela, erela);
8261     }
8262
8263   if (sort)
8264     {
8265       int (*compare) (const void *, const void *);
8266
8267       if (bed->s->arch_size == 32)
8268         {
8269           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8270             compare = cmp_ext32l_r_offset;
8271           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8272             compare = cmp_ext32b_r_offset;
8273           else
8274             abort ();
8275         }
8276       else
8277         {
8278 #ifdef BFD_HOST_64_BIT
8279           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8280             compare = cmp_ext64l_r_offset;
8281           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8282             compare = cmp_ext64b_r_offset;
8283           else
8284 #endif
8285             abort ();
8286         }
8287       qsort (reldata->hdr->contents, count, reldata->hdr->sh_entsize, compare);
8288       free (reldata->hashes);
8289       reldata->hashes = NULL;
8290     }
8291 }
8292
8293 struct elf_link_sort_rela
8294 {
8295   union {
8296     bfd_vma offset;
8297     bfd_vma sym_mask;
8298   } u;
8299   enum elf_reloc_type_class type;
8300   /* We use this as an array of size int_rels_per_ext_rel.  */
8301   Elf_Internal_Rela rela[1];
8302 };
8303
8304 static int
8305 elf_link_sort_cmp1 (const void *A, const void *B)
8306 {
8307   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8308   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8309   int relativea, relativeb;
8310
8311   relativea = a->type == reloc_class_relative;
8312   relativeb = b->type == reloc_class_relative;
8313
8314   if (relativea < relativeb)
8315     return 1;
8316   if (relativea > relativeb)
8317     return -1;
8318   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8319     return -1;
8320   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8321     return 1;
8322   if (a->rela->r_offset < b->rela->r_offset)
8323     return -1;
8324   if (a->rela->r_offset > b->rela->r_offset)
8325     return 1;
8326   return 0;
8327 }
8328
8329 static int
8330 elf_link_sort_cmp2 (const void *A, const void *B)
8331 {
8332   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8333   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8334
8335   if (a->type < b->type)
8336     return -1;
8337   if (a->type > b->type)
8338     return 1;
8339   if (a->u.offset < b->u.offset)
8340     return -1;
8341   if (a->u.offset > b->u.offset)
8342     return 1;
8343   if (a->rela->r_offset < b->rela->r_offset)
8344     return -1;
8345   if (a->rela->r_offset > b->rela->r_offset)
8346     return 1;
8347   return 0;
8348 }
8349
8350 static size_t
8351 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8352 {
8353   asection *dynamic_relocs;
8354   asection *rela_dyn;
8355   asection *rel_dyn;
8356   bfd_size_type count, size;
8357   size_t i, ret, sort_elt, ext_size;
8358   bfd_byte *sort, *s_non_relative, *p;
8359   struct elf_link_sort_rela *sq;
8360   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8361   int i2e = bed->s->int_rels_per_ext_rel;
8362   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8363   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8364   struct bfd_link_order *lo;
8365   bfd_vma r_sym_mask;
8366   bfd_boolean use_rela;
8367
8368   /* Find a dynamic reloc section.  */
8369   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8370   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8371   if (rela_dyn != NULL && rela_dyn->size > 0
8372       && rel_dyn != NULL && rel_dyn->size > 0)
8373     {
8374       bfd_boolean use_rela_initialised = FALSE;
8375
8376       /* This is just here to stop gcc from complaining.
8377          It's initialization checking code is not perfect.  */
8378       use_rela = TRUE;
8379
8380       /* Both sections are present.  Examine the sizes
8381          of the indirect sections to help us choose.  */
8382       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8383         if (lo->type == bfd_indirect_link_order)
8384           {
8385             asection *o = lo->u.indirect.section;
8386
8387             if ((o->size % bed->s->sizeof_rela) == 0)
8388               {
8389                 if ((o->size % bed->s->sizeof_rel) == 0)
8390                   /* Section size is divisible by both rel and rela sizes.
8391                      It is of no help to us.  */
8392                   ;
8393                 else
8394                   {
8395                     /* Section size is only divisible by rela.  */
8396                     if (use_rela_initialised && (use_rela == FALSE))
8397                       {
8398                         _bfd_error_handler
8399                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8400                         bfd_set_error (bfd_error_invalid_operation);
8401                         return 0;
8402                       }
8403                     else
8404                       {
8405                         use_rela = TRUE;
8406                         use_rela_initialised = TRUE;
8407                       }
8408                   }
8409               }
8410             else if ((o->size % bed->s->sizeof_rel) == 0)
8411               {
8412                 /* Section size is only divisible by rel.  */
8413                 if (use_rela_initialised && (use_rela == TRUE))
8414                   {
8415                     _bfd_error_handler
8416                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8417                     bfd_set_error (bfd_error_invalid_operation);
8418                     return 0;
8419                   }
8420                 else
8421                   {
8422                     use_rela = FALSE;
8423                     use_rela_initialised = TRUE;
8424                   }
8425               }
8426             else
8427               {
8428                 /* The section size is not divisible by either - something is wrong.  */
8429                 _bfd_error_handler
8430                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8431                 bfd_set_error (bfd_error_invalid_operation);
8432                 return 0;
8433               }
8434           }
8435
8436       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8437         if (lo->type == bfd_indirect_link_order)
8438           {
8439             asection *o = lo->u.indirect.section;
8440
8441             if ((o->size % bed->s->sizeof_rela) == 0)
8442               {
8443                 if ((o->size % bed->s->sizeof_rel) == 0)
8444                   /* Section size is divisible by both rel and rela sizes.
8445                      It is of no help to us.  */
8446                   ;
8447                 else
8448                   {
8449                     /* Section size is only divisible by rela.  */
8450                     if (use_rela_initialised && (use_rela == FALSE))
8451                       {
8452                         _bfd_error_handler
8453                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8454                         bfd_set_error (bfd_error_invalid_operation);
8455                         return 0;
8456                       }
8457                     else
8458                       {
8459                         use_rela = TRUE;
8460                         use_rela_initialised = TRUE;
8461                       }
8462                   }
8463               }
8464             else if ((o->size % bed->s->sizeof_rel) == 0)
8465               {
8466                 /* Section size is only divisible by rel.  */
8467                 if (use_rela_initialised && (use_rela == TRUE))
8468                   {
8469                     _bfd_error_handler
8470                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8471                     bfd_set_error (bfd_error_invalid_operation);
8472                     return 0;
8473                   }
8474                 else
8475                   {
8476                     use_rela = FALSE;
8477                     use_rela_initialised = TRUE;
8478                   }
8479               }
8480             else
8481               {
8482                 /* The section size is not divisible by either - something is wrong.  */
8483                 _bfd_error_handler
8484                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8485                 bfd_set_error (bfd_error_invalid_operation);
8486                 return 0;
8487               }
8488           }
8489
8490       if (! use_rela_initialised)
8491         /* Make a guess.  */
8492         use_rela = TRUE;
8493     }
8494   else if (rela_dyn != NULL && rela_dyn->size > 0)
8495     use_rela = TRUE;
8496   else if (rel_dyn != NULL && rel_dyn->size > 0)
8497     use_rela = FALSE;
8498   else
8499     return 0;
8500
8501   if (use_rela)
8502     {
8503       dynamic_relocs = rela_dyn;
8504       ext_size = bed->s->sizeof_rela;
8505       swap_in = bed->s->swap_reloca_in;
8506       swap_out = bed->s->swap_reloca_out;
8507     }
8508   else
8509     {
8510       dynamic_relocs = rel_dyn;
8511       ext_size = bed->s->sizeof_rel;
8512       swap_in = bed->s->swap_reloc_in;
8513       swap_out = bed->s->swap_reloc_out;
8514     }
8515
8516   size = 0;
8517   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8518     if (lo->type == bfd_indirect_link_order)
8519       size += lo->u.indirect.section->size;
8520
8521   if (size != dynamic_relocs->size)
8522     return 0;
8523
8524   sort_elt = (sizeof (struct elf_link_sort_rela)
8525               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8526
8527   count = dynamic_relocs->size / ext_size;
8528   if (count == 0)
8529     return 0;
8530   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8531
8532   if (sort == NULL)
8533     {
8534       (*info->callbacks->warning)
8535         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8536       return 0;
8537     }
8538
8539   if (bed->s->arch_size == 32)
8540     r_sym_mask = ~(bfd_vma) 0xff;
8541   else
8542     r_sym_mask = ~(bfd_vma) 0xffffffff;
8543
8544   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8545     if (lo->type == bfd_indirect_link_order)
8546       {
8547         bfd_byte *erel, *erelend;
8548         asection *o = lo->u.indirect.section;
8549
8550         if (o->contents == NULL && o->size != 0)
8551           {
8552             /* This is a reloc section that is being handled as a normal
8553                section.  See bfd_section_from_shdr.  We can't combine
8554                relocs in this case.  */
8555             free (sort);
8556             return 0;
8557           }
8558         erel = o->contents;
8559         erelend = o->contents + o->size;
8560         /* FIXME: octets_per_byte.  */
8561         p = sort + o->output_offset / ext_size * sort_elt;
8562
8563         while (erel < erelend)
8564           {
8565             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8566
8567             (*swap_in) (abfd, erel, s->rela);
8568             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8569             s->u.sym_mask = r_sym_mask;
8570             p += sort_elt;
8571             erel += ext_size;
8572           }
8573       }
8574
8575   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8576
8577   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8578     {
8579       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8580       if (s->type != reloc_class_relative)
8581         break;
8582     }
8583   ret = i;
8584   s_non_relative = p;
8585
8586   sq = (struct elf_link_sort_rela *) s_non_relative;
8587   for (; i < count; i++, p += sort_elt)
8588     {
8589       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8590       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8591         sq = sp;
8592       sp->u.offset = sq->rela->r_offset;
8593     }
8594
8595   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8596
8597   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8598     if (lo->type == bfd_indirect_link_order)
8599       {
8600         bfd_byte *erel, *erelend;
8601         asection *o = lo->u.indirect.section;
8602
8603         erel = o->contents;
8604         erelend = o->contents + o->size;
8605         /* FIXME: octets_per_byte.  */
8606         p = sort + o->output_offset / ext_size * sort_elt;
8607         while (erel < erelend)
8608           {
8609             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8610             (*swap_out) (abfd, s->rela, erel);
8611             p += sort_elt;
8612             erel += ext_size;
8613           }
8614       }
8615
8616   free (sort);
8617   *psec = dynamic_relocs;
8618   return ret;
8619 }
8620
8621 /* Add a symbol to the output symbol string table.  */
8622
8623 static int
8624 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8625                            const char *name,
8626                            Elf_Internal_Sym *elfsym,
8627                            asection *input_sec,
8628                            struct elf_link_hash_entry *h)
8629 {
8630   int (*output_symbol_hook)
8631     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8632      struct elf_link_hash_entry *);
8633   struct elf_link_hash_table *hash_table;
8634   const struct elf_backend_data *bed;
8635   bfd_size_type strtabsize;
8636
8637   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8638
8639   bed = get_elf_backend_data (flinfo->output_bfd);
8640   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8641   if (output_symbol_hook != NULL)
8642     {
8643       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8644       if (ret != 1)
8645         return ret;
8646     }
8647
8648   if (name == NULL
8649       || *name == '\0'
8650       || (input_sec->flags & SEC_EXCLUDE))
8651     elfsym->st_name = (unsigned long) -1;
8652   else
8653     {
8654       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8655          to get the final offset for st_name.  */
8656       elfsym->st_name
8657         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8658                                                name, FALSE);
8659       if (elfsym->st_name == (unsigned long) -1)
8660         return 0;
8661     }
8662
8663   hash_table = elf_hash_table (flinfo->info);
8664   strtabsize = hash_table->strtabsize;
8665   if (strtabsize <= hash_table->strtabcount)
8666     {
8667       strtabsize += strtabsize;
8668       hash_table->strtabsize = strtabsize;
8669       strtabsize *= sizeof (*hash_table->strtab);
8670       hash_table->strtab
8671         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8672                                                  strtabsize);
8673       if (hash_table->strtab == NULL)
8674         return 0;
8675     }
8676   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8677   hash_table->strtab[hash_table->strtabcount].dest_index
8678     = hash_table->strtabcount;
8679   hash_table->strtab[hash_table->strtabcount].destshndx_index
8680     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8681
8682   bfd_get_symcount (flinfo->output_bfd) += 1;
8683   hash_table->strtabcount += 1;
8684
8685   return 1;
8686 }
8687
8688 /* Swap symbols out to the symbol table and flush the output symbols to
8689    the file.  */
8690
8691 static bfd_boolean
8692 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8693 {
8694   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8695   bfd_size_type amt, i;
8696   const struct elf_backend_data *bed;
8697   bfd_byte *symbuf;
8698   Elf_Internal_Shdr *hdr;
8699   file_ptr pos;
8700   bfd_boolean ret;
8701
8702   if (!hash_table->strtabcount)
8703     return TRUE;
8704
8705   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8706
8707   bed = get_elf_backend_data (flinfo->output_bfd);
8708
8709   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8710   symbuf = (bfd_byte *) bfd_malloc (amt);
8711   if (symbuf == NULL)
8712     return FALSE;
8713   
8714   if (flinfo->symshndxbuf)
8715     {
8716       amt = (sizeof (Elf_External_Sym_Shndx)
8717              * (bfd_get_symcount (flinfo->output_bfd)));
8718       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8719       if (flinfo->symshndxbuf == NULL)
8720         {
8721           free (symbuf);
8722           return FALSE;
8723         }
8724     }
8725
8726   for (i = 0; i < hash_table->strtabcount; i++)
8727     {
8728       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8729       if (elfsym->sym.st_name == (unsigned long) -1)
8730         elfsym->sym.st_name = 0;
8731       else
8732         elfsym->sym.st_name
8733           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8734                                                     elfsym->sym.st_name);
8735       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8736                                ((bfd_byte *) symbuf
8737                                 + (elfsym->dest_index
8738                                    * bed->s->sizeof_sym)),
8739                                (flinfo->symshndxbuf
8740                                 + elfsym->destshndx_index));
8741     }
8742
8743   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8744   pos = hdr->sh_offset + hdr->sh_size;
8745   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8746   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8747       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8748     {
8749       hdr->sh_size += amt;
8750       ret = TRUE;
8751     }
8752   else
8753     ret = FALSE;
8754
8755   free (symbuf);
8756
8757   free (hash_table->strtab);
8758   hash_table->strtab = NULL;
8759
8760   return ret;
8761 }
8762
8763 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8764
8765 static bfd_boolean
8766 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8767 {
8768   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8769       && sym->st_shndx < SHN_LORESERVE)
8770     {
8771       /* The gABI doesn't support dynamic symbols in output sections
8772          beyond 64k.  */
8773       (*_bfd_error_handler)
8774         (_("%B: Too many sections: %d (>= %d)"),
8775          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8776       bfd_set_error (bfd_error_nonrepresentable_section);
8777       return FALSE;
8778     }
8779   return TRUE;
8780 }
8781
8782 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8783    allowing an unsatisfied unversioned symbol in the DSO to match a
8784    versioned symbol that would normally require an explicit version.
8785    We also handle the case that a DSO references a hidden symbol
8786    which may be satisfied by a versioned symbol in another DSO.  */
8787
8788 static bfd_boolean
8789 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8790                                  const struct elf_backend_data *bed,
8791                                  struct elf_link_hash_entry *h)
8792 {
8793   bfd *abfd;
8794   struct elf_link_loaded_list *loaded;
8795
8796   if (!is_elf_hash_table (info->hash))
8797     return FALSE;
8798
8799   /* Check indirect symbol.  */
8800   while (h->root.type == bfd_link_hash_indirect)
8801     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8802
8803   switch (h->root.type)
8804     {
8805     default:
8806       abfd = NULL;
8807       break;
8808
8809     case bfd_link_hash_undefined:
8810     case bfd_link_hash_undefweak:
8811       abfd = h->root.u.undef.abfd;
8812       if ((abfd->flags & DYNAMIC) == 0
8813           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8814         return FALSE;
8815       break;
8816
8817     case bfd_link_hash_defined:
8818     case bfd_link_hash_defweak:
8819       abfd = h->root.u.def.section->owner;
8820       break;
8821
8822     case bfd_link_hash_common:
8823       abfd = h->root.u.c.p->section->owner;
8824       break;
8825     }
8826   BFD_ASSERT (abfd != NULL);
8827
8828   for (loaded = elf_hash_table (info)->loaded;
8829        loaded != NULL;
8830        loaded = loaded->next)
8831     {
8832       bfd *input;
8833       Elf_Internal_Shdr *hdr;
8834       bfd_size_type symcount;
8835       bfd_size_type extsymcount;
8836       bfd_size_type extsymoff;
8837       Elf_Internal_Shdr *versymhdr;
8838       Elf_Internal_Sym *isym;
8839       Elf_Internal_Sym *isymend;
8840       Elf_Internal_Sym *isymbuf;
8841       Elf_External_Versym *ever;
8842       Elf_External_Versym *extversym;
8843
8844       input = loaded->abfd;
8845
8846       /* We check each DSO for a possible hidden versioned definition.  */
8847       if (input == abfd
8848           || (input->flags & DYNAMIC) == 0
8849           || elf_dynversym (input) == 0)
8850         continue;
8851
8852       hdr = &elf_tdata (input)->dynsymtab_hdr;
8853
8854       symcount = hdr->sh_size / bed->s->sizeof_sym;
8855       if (elf_bad_symtab (input))
8856         {
8857           extsymcount = symcount;
8858           extsymoff = 0;
8859         }
8860       else
8861         {
8862           extsymcount = symcount - hdr->sh_info;
8863           extsymoff = hdr->sh_info;
8864         }
8865
8866       if (extsymcount == 0)
8867         continue;
8868
8869       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8870                                       NULL, NULL, NULL);
8871       if (isymbuf == NULL)
8872         return FALSE;
8873
8874       /* Read in any version definitions.  */
8875       versymhdr = &elf_tdata (input)->dynversym_hdr;
8876       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8877       if (extversym == NULL)
8878         goto error_ret;
8879
8880       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8881           || (bfd_bread (extversym, versymhdr->sh_size, input)
8882               != versymhdr->sh_size))
8883         {
8884           free (extversym);
8885         error_ret:
8886           free (isymbuf);
8887           return FALSE;
8888         }
8889
8890       ever = extversym + extsymoff;
8891       isymend = isymbuf + extsymcount;
8892       for (isym = isymbuf; isym < isymend; isym++, ever++)
8893         {
8894           const char *name;
8895           Elf_Internal_Versym iver;
8896           unsigned short version_index;
8897
8898           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8899               || isym->st_shndx == SHN_UNDEF)
8900             continue;
8901
8902           name = bfd_elf_string_from_elf_section (input,
8903                                                   hdr->sh_link,
8904                                                   isym->st_name);
8905           if (strcmp (name, h->root.root.string) != 0)
8906             continue;
8907
8908           _bfd_elf_swap_versym_in (input, ever, &iver);
8909
8910           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8911               && !(h->def_regular
8912                    && h->forced_local))
8913             {
8914               /* If we have a non-hidden versioned sym, then it should
8915                  have provided a definition for the undefined sym unless
8916                  it is defined in a non-shared object and forced local.
8917                */
8918               abort ();
8919             }
8920
8921           version_index = iver.vs_vers & VERSYM_VERSION;
8922           if (version_index == 1 || version_index == 2)
8923             {
8924               /* This is the base or first version.  We can use it.  */
8925               free (extversym);
8926               free (isymbuf);
8927               return TRUE;
8928             }
8929         }
8930
8931       free (extversym);
8932       free (isymbuf);
8933     }
8934
8935   return FALSE;
8936 }
8937
8938 /* Add an external symbol to the symbol table.  This is called from
8939    the hash table traversal routine.  When generating a shared object,
8940    we go through the symbol table twice.  The first time we output
8941    anything that might have been forced to local scope in a version
8942    script.  The second time we output the symbols that are still
8943    global symbols.  */
8944
8945 static bfd_boolean
8946 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8947 {
8948   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8949   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8950   struct elf_final_link_info *flinfo = eoinfo->flinfo;
8951   bfd_boolean strip;
8952   Elf_Internal_Sym sym;
8953   asection *input_sec;
8954   const struct elf_backend_data *bed;
8955   long indx;
8956   int ret;
8957   /* A symbol is bound locally if it is forced local or it is locally
8958      defined, hidden versioned, not referenced by shared library and
8959      not exported when linking executable.  */
8960   bfd_boolean local_bind = (h->forced_local
8961                             || (flinfo->info->executable
8962                                 && !flinfo->info->export_dynamic
8963                                 && !h->dynamic
8964                                 && !h->ref_dynamic
8965                                 && h->def_regular
8966                                 && h->hidden));
8967
8968   if (h->root.type == bfd_link_hash_warning)
8969     {
8970       h = (struct elf_link_hash_entry *) h->root.u.i.link;
8971       if (h->root.type == bfd_link_hash_new)
8972         return TRUE;
8973     }
8974
8975   /* Decide whether to output this symbol in this pass.  */
8976   if (eoinfo->localsyms)
8977     {
8978       if (!local_bind)
8979         return TRUE;
8980     }
8981   else
8982     {
8983       if (local_bind)
8984         return TRUE;
8985     }
8986
8987   bed = get_elf_backend_data (flinfo->output_bfd);
8988
8989   if (h->root.type == bfd_link_hash_undefined)
8990     {
8991       /* If we have an undefined symbol reference here then it must have
8992          come from a shared library that is being linked in.  (Undefined
8993          references in regular files have already been handled unless
8994          they are in unreferenced sections which are removed by garbage
8995          collection).  */
8996       bfd_boolean ignore_undef = FALSE;
8997
8998       /* Some symbols may be special in that the fact that they're
8999          undefined can be safely ignored - let backend determine that.  */
9000       if (bed->elf_backend_ignore_undef_symbol)
9001         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9002
9003       /* If we are reporting errors for this situation then do so now.  */
9004       if (!ignore_undef
9005           && h->ref_dynamic
9006           && (!h->ref_regular || flinfo->info->gc_sections)
9007           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9008           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9009         {
9010           if (!(flinfo->info->callbacks->undefined_symbol
9011                 (flinfo->info, h->root.root.string,
9012                  h->ref_regular ? NULL : h->root.u.undef.abfd,
9013                  NULL, 0,
9014                  (flinfo->info->unresolved_syms_in_shared_libs
9015                   == RM_GENERATE_ERROR))))
9016             {
9017               bfd_set_error (bfd_error_bad_value);
9018               eoinfo->failed = TRUE;
9019               return FALSE;
9020             }
9021         }
9022     }
9023
9024   /* We should also warn if a forced local symbol is referenced from
9025      shared libraries.  */
9026   if (flinfo->info->executable
9027       && h->forced_local
9028       && h->ref_dynamic
9029       && h->def_regular
9030       && !h->dynamic_def
9031       && h->ref_dynamic_nonweak
9032       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9033     {
9034       bfd *def_bfd;
9035       const char *msg;
9036       struct elf_link_hash_entry *hi = h;
9037
9038       /* Check indirect symbol.  */
9039       while (hi->root.type == bfd_link_hash_indirect)
9040         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9041
9042       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9043         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9044       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9045         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9046       else
9047         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9048       def_bfd = flinfo->output_bfd;
9049       if (hi->root.u.def.section != bfd_abs_section_ptr)
9050         def_bfd = hi->root.u.def.section->owner;
9051       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9052                              h->root.root.string);
9053       bfd_set_error (bfd_error_bad_value);
9054       eoinfo->failed = TRUE;
9055       return FALSE;
9056     }
9057
9058   /* We don't want to output symbols that have never been mentioned by
9059      a regular file, or that we have been told to strip.  However, if
9060      h->indx is set to -2, the symbol is used by a reloc and we must
9061      output it.  */
9062   strip = FALSE;
9063   if (h->indx == -2)
9064     ;
9065   else if ((h->def_dynamic
9066             || h->ref_dynamic
9067             || h->root.type == bfd_link_hash_new)
9068            && !h->def_regular
9069            && !h->ref_regular)
9070     strip = TRUE;
9071   else if (flinfo->info->strip == strip_all)
9072     strip = TRUE;
9073   else if (flinfo->info->strip == strip_some
9074            && bfd_hash_lookup (flinfo->info->keep_hash,
9075                                h->root.root.string, FALSE, FALSE) == NULL)
9076     strip = TRUE;
9077   else if ((h->root.type == bfd_link_hash_defined
9078             || h->root.type == bfd_link_hash_defweak)
9079            && ((flinfo->info->strip_discarded
9080                 && discarded_section (h->root.u.def.section))
9081                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9082                    && h->root.u.def.section->owner != NULL
9083                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9084     strip = TRUE;
9085   else if ((h->root.type == bfd_link_hash_undefined
9086             || h->root.type == bfd_link_hash_undefweak)
9087            && h->root.u.undef.abfd != NULL
9088            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9089     strip = TRUE;
9090
9091   /* If we're stripping it, and it's not a dynamic symbol, there's
9092      nothing else to do.   However, if it is a forced local symbol or
9093      an ifunc symbol we need to give the backend finish_dynamic_symbol
9094      function a chance to make it dynamic.  */
9095   if (strip
9096       && h->dynindx == -1
9097       && h->type != STT_GNU_IFUNC
9098       && !h->forced_local)
9099     return TRUE;
9100
9101   sym.st_value = 0;
9102   sym.st_size = h->size;
9103   sym.st_other = h->other;
9104   if (local_bind)
9105     {
9106       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
9107       /* Turn off visibility on local symbol.  */
9108       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9109     }
9110   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9111   else if (h->unique_global && h->def_regular)
9112     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
9113   else if (h->root.type == bfd_link_hash_undefweak
9114            || h->root.type == bfd_link_hash_defweak)
9115     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
9116   else
9117     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
9118   sym.st_target_internal = h->target_internal;
9119
9120   switch (h->root.type)
9121     {
9122     default:
9123     case bfd_link_hash_new:
9124     case bfd_link_hash_warning:
9125       abort ();
9126       return FALSE;
9127
9128     case bfd_link_hash_undefined:
9129     case bfd_link_hash_undefweak:
9130       input_sec = bfd_und_section_ptr;
9131       sym.st_shndx = SHN_UNDEF;
9132       break;
9133
9134     case bfd_link_hash_defined:
9135     case bfd_link_hash_defweak:
9136       {
9137         input_sec = h->root.u.def.section;
9138         if (input_sec->output_section != NULL)
9139           {
9140             sym.st_shndx =
9141               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9142                                                  input_sec->output_section);
9143             if (sym.st_shndx == SHN_BAD)
9144               {
9145                 (*_bfd_error_handler)
9146                   (_("%B: could not find output section %A for input section %A"),
9147                    flinfo->output_bfd, input_sec->output_section, input_sec);
9148                 bfd_set_error (bfd_error_nonrepresentable_section);
9149                 eoinfo->failed = TRUE;
9150                 return FALSE;
9151               }
9152
9153             /* ELF symbols in relocatable files are section relative,
9154                but in nonrelocatable files they are virtual
9155                addresses.  */
9156             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9157             if (!flinfo->info->relocatable)
9158               {
9159                 sym.st_value += input_sec->output_section->vma;
9160                 if (h->type == STT_TLS)
9161                   {
9162                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9163                     if (tls_sec != NULL)
9164                       sym.st_value -= tls_sec->vma;
9165                   }
9166               }
9167           }
9168         else
9169           {
9170             BFD_ASSERT (input_sec->owner == NULL
9171                         || (input_sec->owner->flags & DYNAMIC) != 0);
9172             sym.st_shndx = SHN_UNDEF;
9173             input_sec = bfd_und_section_ptr;
9174           }
9175       }
9176       break;
9177
9178     case bfd_link_hash_common:
9179       input_sec = h->root.u.c.p->section;
9180       sym.st_shndx = bed->common_section_index (input_sec);
9181       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9182       break;
9183
9184     case bfd_link_hash_indirect:
9185       /* These symbols are created by symbol versioning.  They point
9186          to the decorated version of the name.  For example, if the
9187          symbol foo@@GNU_1.2 is the default, which should be used when
9188          foo is used with no version, then we add an indirect symbol
9189          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9190          since the indirected symbol is already in the hash table.  */
9191       return TRUE;
9192     }
9193
9194   /* Give the processor backend a chance to tweak the symbol value,
9195      and also to finish up anything that needs to be done for this
9196      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9197      forced local syms when non-shared is due to a historical quirk.
9198      STT_GNU_IFUNC symbol must go through PLT.  */
9199   if ((h->type == STT_GNU_IFUNC
9200        && h->def_regular
9201        && !flinfo->info->relocatable)
9202       || ((h->dynindx != -1
9203            || h->forced_local)
9204           && ((flinfo->info->shared
9205                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9206                    || h->root.type != bfd_link_hash_undefweak))
9207               || !h->forced_local)
9208           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9209     {
9210       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9211              (flinfo->output_bfd, flinfo->info, h, &sym)))
9212         {
9213           eoinfo->failed = TRUE;
9214           return FALSE;
9215         }
9216     }
9217
9218   /* If we are marking the symbol as undefined, and there are no
9219      non-weak references to this symbol from a regular object, then
9220      mark the symbol as weak undefined; if there are non-weak
9221      references, mark the symbol as strong.  We can't do this earlier,
9222      because it might not be marked as undefined until the
9223      finish_dynamic_symbol routine gets through with it.  */
9224   if (sym.st_shndx == SHN_UNDEF
9225       && h->ref_regular
9226       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9227           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9228     {
9229       int bindtype;
9230       unsigned int type = ELF_ST_TYPE (sym.st_info);
9231
9232       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9233       if (type == STT_GNU_IFUNC)
9234         type = STT_FUNC;
9235
9236       if (h->ref_regular_nonweak)
9237         bindtype = STB_GLOBAL;
9238       else
9239         bindtype = STB_WEAK;
9240       sym.st_info = ELF_ST_INFO (bindtype, type);
9241     }
9242
9243   /* If this is a symbol defined in a dynamic library, don't use the
9244      symbol size from the dynamic library.  Relinking an executable
9245      against a new library may introduce gratuitous changes in the
9246      executable's symbols if we keep the size.  */
9247   if (sym.st_shndx == SHN_UNDEF
9248       && !h->def_regular
9249       && h->def_dynamic)
9250     sym.st_size = 0;
9251
9252   /* If a non-weak symbol with non-default visibility is not defined
9253      locally, it is a fatal error.  */
9254   if (!flinfo->info->relocatable
9255       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9256       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9257       && h->root.type == bfd_link_hash_undefined
9258       && !h->def_regular)
9259     {
9260       const char *msg;
9261
9262       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9263         msg = _("%B: protected symbol `%s' isn't defined");
9264       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9265         msg = _("%B: internal symbol `%s' isn't defined");
9266       else
9267         msg = _("%B: hidden symbol `%s' isn't defined");
9268       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9269       bfd_set_error (bfd_error_bad_value);
9270       eoinfo->failed = TRUE;
9271       return FALSE;
9272     }
9273
9274   /* If this symbol should be put in the .dynsym section, then put it
9275      there now.  We already know the symbol index.  We also fill in
9276      the entry in the .hash section.  */
9277   if (flinfo->dynsym_sec != NULL
9278       && h->dynindx != -1
9279       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9280     {
9281       bfd_byte *esym;
9282
9283       /* Since there is no version information in the dynamic string,
9284          if there is no version info in symbol version section, we will
9285          have a run-time problem if not linking executable, referenced
9286          by shared library, not locally defined, or not bound locally.
9287       */
9288       if (h->verinfo.verdef == NULL
9289           && !local_bind
9290           && (!flinfo->info->executable
9291               || h->ref_dynamic
9292               || !h->def_regular))
9293         {
9294           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9295
9296           if (p && p [1] != '\0')
9297             {
9298               (*_bfd_error_handler)
9299                 (_("%B: No symbol version section for versioned symbol `%s'"),
9300                  flinfo->output_bfd, h->root.root.string);
9301               eoinfo->failed = TRUE;
9302               return FALSE;
9303             }
9304         }
9305
9306       sym.st_name = h->dynstr_index;
9307       esym = flinfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
9308       if (!check_dynsym (flinfo->output_bfd, &sym))
9309         {
9310           eoinfo->failed = TRUE;
9311           return FALSE;
9312         }
9313       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9314
9315       if (flinfo->hash_sec != NULL)
9316         {
9317           size_t hash_entry_size;
9318           bfd_byte *bucketpos;
9319           bfd_vma chain;
9320           size_t bucketcount;
9321           size_t bucket;
9322
9323           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9324           bucket = h->u.elf_hash_value % bucketcount;
9325
9326           hash_entry_size
9327             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9328           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9329                        + (bucket + 2) * hash_entry_size);
9330           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9331           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9332                    bucketpos);
9333           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9334                    ((bfd_byte *) flinfo->hash_sec->contents
9335                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9336         }
9337
9338       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9339         {
9340           Elf_Internal_Versym iversym;
9341           Elf_External_Versym *eversym;
9342
9343           if (!h->def_regular)
9344             {
9345               if (h->verinfo.verdef == NULL
9346                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9347                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9348                 iversym.vs_vers = 0;
9349               else
9350                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9351             }
9352           else
9353             {
9354               if (h->verinfo.vertree == NULL)
9355                 iversym.vs_vers = 1;
9356               else
9357                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9358               if (flinfo->info->create_default_symver)
9359                 iversym.vs_vers++;
9360             }
9361
9362           /* Turn on VERSYM_HIDDEN only if the hidden vesioned symbol is
9363              defined locally.  */
9364           if (h->hidden && h->def_regular)
9365             iversym.vs_vers |= VERSYM_HIDDEN;
9366
9367           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9368           eversym += h->dynindx;
9369           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9370         }
9371     }
9372
9373   /* If the symbol is undefined, and we didn't output it to .dynsym,
9374      strip it from .symtab too.  Obviously we can't do this for
9375      relocatable output or when needed for --emit-relocs.  */
9376   else if (input_sec == bfd_und_section_ptr
9377            && h->indx != -2
9378            && !flinfo->info->relocatable)
9379     return TRUE;
9380   /* Also strip others that we couldn't earlier due to dynamic symbol
9381      processing.  */
9382   if (strip)
9383     return TRUE;
9384   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9385     return TRUE;
9386
9387   /* Output a FILE symbol so that following locals are not associated
9388      with the wrong input file.  We need one for forced local symbols
9389      if we've seen more than one FILE symbol or when we have exactly
9390      one FILE symbol but global symbols are present in a file other
9391      than the one with the FILE symbol.  We also need one if linker
9392      defined symbols are present.  In practice these conditions are
9393      always met, so just emit the FILE symbol unconditionally.  */
9394   if (eoinfo->localsyms
9395       && !eoinfo->file_sym_done
9396       && eoinfo->flinfo->filesym_count != 0)
9397     {
9398       Elf_Internal_Sym fsym;
9399
9400       memset (&fsym, 0, sizeof (fsym));
9401       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9402       fsym.st_shndx = SHN_ABS;
9403       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9404                                       bfd_und_section_ptr, NULL))
9405         return FALSE;
9406
9407       eoinfo->file_sym_done = TRUE;
9408     }
9409
9410   indx = bfd_get_symcount (flinfo->output_bfd);
9411   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9412                                    input_sec, h);
9413   if (ret == 0)
9414     {
9415       eoinfo->failed = TRUE;
9416       return FALSE;
9417     }
9418   else if (ret == 1)
9419     h->indx = indx;
9420   else if (h->indx == -2)
9421     abort();
9422
9423   return TRUE;
9424 }
9425
9426 /* Return TRUE if special handling is done for relocs in SEC against
9427    symbols defined in discarded sections.  */
9428
9429 static bfd_boolean
9430 elf_section_ignore_discarded_relocs (asection *sec)
9431 {
9432   const struct elf_backend_data *bed;
9433
9434   switch (sec->sec_info_type)
9435     {
9436     case SEC_INFO_TYPE_STABS:
9437     case SEC_INFO_TYPE_EH_FRAME:
9438     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9439       return TRUE;
9440     default:
9441       break;
9442     }
9443
9444   bed = get_elf_backend_data (sec->owner);
9445   if (bed->elf_backend_ignore_discarded_relocs != NULL
9446       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9447     return TRUE;
9448
9449   return FALSE;
9450 }
9451
9452 /* Return a mask saying how ld should treat relocations in SEC against
9453    symbols defined in discarded sections.  If this function returns
9454    COMPLAIN set, ld will issue a warning message.  If this function
9455    returns PRETEND set, and the discarded section was link-once and the
9456    same size as the kept link-once section, ld will pretend that the
9457    symbol was actually defined in the kept section.  Otherwise ld will
9458    zero the reloc (at least that is the intent, but some cooperation by
9459    the target dependent code is needed, particularly for REL targets).  */
9460
9461 unsigned int
9462 _bfd_elf_default_action_discarded (asection *sec)
9463 {
9464   if (sec->flags & SEC_DEBUGGING)
9465     return PRETEND;
9466
9467   if (strcmp (".eh_frame", sec->name) == 0)
9468     return 0;
9469
9470   if (strcmp (".gcc_except_table", sec->name) == 0)
9471     return 0;
9472
9473   return COMPLAIN | PRETEND;
9474 }
9475
9476 /* Find a match between a section and a member of a section group.  */
9477
9478 static asection *
9479 match_group_member (asection *sec, asection *group,
9480                     struct bfd_link_info *info)
9481 {
9482   asection *first = elf_next_in_group (group);
9483   asection *s = first;
9484
9485   while (s != NULL)
9486     {
9487       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9488         return s;
9489
9490       s = elf_next_in_group (s);
9491       if (s == first)
9492         break;
9493     }
9494
9495   return NULL;
9496 }
9497
9498 /* Check if the kept section of a discarded section SEC can be used
9499    to replace it.  Return the replacement if it is OK.  Otherwise return
9500    NULL.  */
9501
9502 asection *
9503 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9504 {
9505   asection *kept;
9506
9507   kept = sec->kept_section;
9508   if (kept != NULL)
9509     {
9510       if ((kept->flags & SEC_GROUP) != 0)
9511         kept = match_group_member (sec, kept, info);
9512       if (kept != NULL
9513           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9514               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9515         kept = NULL;
9516       sec->kept_section = kept;
9517     }
9518   return kept;
9519 }
9520
9521 /* Link an input file into the linker output file.  This function
9522    handles all the sections and relocations of the input file at once.
9523    This is so that we only have to read the local symbols once, and
9524    don't have to keep them in memory.  */
9525
9526 static bfd_boolean
9527 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9528 {
9529   int (*relocate_section)
9530     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9531      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9532   bfd *output_bfd;
9533   Elf_Internal_Shdr *symtab_hdr;
9534   size_t locsymcount;
9535   size_t extsymoff;
9536   Elf_Internal_Sym *isymbuf;
9537   Elf_Internal_Sym *isym;
9538   Elf_Internal_Sym *isymend;
9539   long *pindex;
9540   asection **ppsection;
9541   asection *o;
9542   const struct elf_backend_data *bed;
9543   struct elf_link_hash_entry **sym_hashes;
9544   bfd_size_type address_size;
9545   bfd_vma r_type_mask;
9546   int r_sym_shift;
9547   bfd_boolean have_file_sym = FALSE;
9548
9549   output_bfd = flinfo->output_bfd;
9550   bed = get_elf_backend_data (output_bfd);
9551   relocate_section = bed->elf_backend_relocate_section;
9552
9553   /* If this is a dynamic object, we don't want to do anything here:
9554      we don't want the local symbols, and we don't want the section
9555      contents.  */
9556   if ((input_bfd->flags & DYNAMIC) != 0)
9557     return TRUE;
9558
9559   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9560   if (elf_bad_symtab (input_bfd))
9561     {
9562       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9563       extsymoff = 0;
9564     }
9565   else
9566     {
9567       locsymcount = symtab_hdr->sh_info;
9568       extsymoff = symtab_hdr->sh_info;
9569     }
9570
9571   /* Read the local symbols.  */
9572   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9573   if (isymbuf == NULL && locsymcount != 0)
9574     {
9575       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9576                                       flinfo->internal_syms,
9577                                       flinfo->external_syms,
9578                                       flinfo->locsym_shndx);
9579       if (isymbuf == NULL)
9580         return FALSE;
9581     }
9582
9583   /* Find local symbol sections and adjust values of symbols in
9584      SEC_MERGE sections.  Write out those local symbols we know are
9585      going into the output file.  */
9586   isymend = isymbuf + locsymcount;
9587   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9588        isym < isymend;
9589        isym++, pindex++, ppsection++)
9590     {
9591       asection *isec;
9592       const char *name;
9593       Elf_Internal_Sym osym;
9594       long indx;
9595       int ret;
9596
9597       *pindex = -1;
9598
9599       if (elf_bad_symtab (input_bfd))
9600         {
9601           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9602             {
9603               *ppsection = NULL;
9604               continue;
9605             }
9606         }
9607
9608       if (isym->st_shndx == SHN_UNDEF)
9609         isec = bfd_und_section_ptr;
9610       else if (isym->st_shndx == SHN_ABS)
9611         isec = bfd_abs_section_ptr;
9612       else if (isym->st_shndx == SHN_COMMON)
9613         isec = bfd_com_section_ptr;
9614       else
9615         {
9616           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9617           if (isec == NULL)
9618             {
9619               /* Don't attempt to output symbols with st_shnx in the
9620                  reserved range other than SHN_ABS and SHN_COMMON.  */
9621               *ppsection = NULL;
9622               continue;
9623             }
9624           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9625                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9626             isym->st_value =
9627               _bfd_merged_section_offset (output_bfd, &isec,
9628                                           elf_section_data (isec)->sec_info,
9629                                           isym->st_value);
9630         }
9631
9632       *ppsection = isec;
9633
9634       /* Don't output the first, undefined, symbol.  In fact, don't
9635          output any undefined local symbol.  */
9636       if (isec == bfd_und_section_ptr)
9637         continue;
9638
9639       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9640         {
9641           /* We never output section symbols.  Instead, we use the
9642              section symbol of the corresponding section in the output
9643              file.  */
9644           continue;
9645         }
9646
9647       /* If we are stripping all symbols, we don't want to output this
9648          one.  */
9649       if (flinfo->info->strip == strip_all)
9650         continue;
9651
9652       /* If we are discarding all local symbols, we don't want to
9653          output this one.  If we are generating a relocatable output
9654          file, then some of the local symbols may be required by
9655          relocs; we output them below as we discover that they are
9656          needed.  */
9657       if (flinfo->info->discard == discard_all)
9658         continue;
9659
9660       /* If this symbol is defined in a section which we are
9661          discarding, we don't need to keep it.  */
9662       if (isym->st_shndx != SHN_UNDEF
9663           && isym->st_shndx < SHN_LORESERVE
9664           && bfd_section_removed_from_list (output_bfd,
9665                                             isec->output_section))
9666         continue;
9667
9668       /* Get the name of the symbol.  */
9669       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9670                                               isym->st_name);
9671       if (name == NULL)
9672         return FALSE;
9673
9674       /* See if we are discarding symbols with this name.  */
9675       if ((flinfo->info->strip == strip_some
9676            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9677                == NULL))
9678           || (((flinfo->info->discard == discard_sec_merge
9679                 && (isec->flags & SEC_MERGE) && !flinfo->info->relocatable)
9680                || flinfo->info->discard == discard_l)
9681               && bfd_is_local_label_name (input_bfd, name)))
9682         continue;
9683
9684       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9685         {
9686           if (input_bfd->lto_output)
9687             /* -flto puts a temp file name here.  This means builds
9688                are not reproducible.  Discard the symbol.  */
9689             continue;
9690           have_file_sym = TRUE;
9691           flinfo->filesym_count += 1;
9692         }
9693       if (!have_file_sym)
9694         {
9695           /* In the absence of debug info, bfd_find_nearest_line uses
9696              FILE symbols to determine the source file for local
9697              function symbols.  Provide a FILE symbol here if input
9698              files lack such, so that their symbols won't be
9699              associated with a previous input file.  It's not the
9700              source file, but the best we can do.  */
9701           have_file_sym = TRUE;
9702           flinfo->filesym_count += 1;
9703           memset (&osym, 0, sizeof (osym));
9704           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9705           osym.st_shndx = SHN_ABS;
9706           if (!elf_link_output_symstrtab (flinfo,
9707                                           (input_bfd->lto_output ? NULL
9708                                            : input_bfd->filename),
9709                                           &osym, bfd_abs_section_ptr,
9710                                           NULL))
9711             return FALSE;
9712         }
9713
9714       osym = *isym;
9715
9716       /* Adjust the section index for the output file.  */
9717       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9718                                                          isec->output_section);
9719       if (osym.st_shndx == SHN_BAD)
9720         return FALSE;
9721
9722       /* ELF symbols in relocatable files are section relative, but
9723          in executable files they are virtual addresses.  Note that
9724          this code assumes that all ELF sections have an associated
9725          BFD section with a reasonable value for output_offset; below
9726          we assume that they also have a reasonable value for
9727          output_section.  Any special sections must be set up to meet
9728          these requirements.  */
9729       osym.st_value += isec->output_offset;
9730       if (!flinfo->info->relocatable)
9731         {
9732           osym.st_value += isec->output_section->vma;
9733           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9734             {
9735               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9736               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9737               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9738             }
9739         }
9740
9741       indx = bfd_get_symcount (output_bfd);
9742       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
9743       if (ret == 0)
9744         return FALSE;
9745       else if (ret == 1)
9746         *pindex = indx;
9747     }
9748
9749   if (bed->s->arch_size == 32)
9750     {
9751       r_type_mask = 0xff;
9752       r_sym_shift = 8;
9753       address_size = 4;
9754     }
9755   else
9756     {
9757       r_type_mask = 0xffffffff;
9758       r_sym_shift = 32;
9759       address_size = 8;
9760     }
9761
9762   /* Relocate the contents of each section.  */
9763   sym_hashes = elf_sym_hashes (input_bfd);
9764   for (o = input_bfd->sections; o != NULL; o = o->next)
9765     {
9766       bfd_byte *contents;
9767
9768       if (! o->linker_mark)
9769         {
9770           /* This section was omitted from the link.  */
9771           continue;
9772         }
9773
9774       if (flinfo->info->relocatable
9775           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9776         {
9777           /* Deal with the group signature symbol.  */
9778           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9779           unsigned long symndx = sec_data->this_hdr.sh_info;
9780           asection *osec = o->output_section;
9781
9782           if (symndx >= locsymcount
9783               || (elf_bad_symtab (input_bfd)
9784                   && flinfo->sections[symndx] == NULL))
9785             {
9786               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9787               while (h->root.type == bfd_link_hash_indirect
9788                      || h->root.type == bfd_link_hash_warning)
9789                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9790               /* Arrange for symbol to be output.  */
9791               h->indx = -2;
9792               elf_section_data (osec)->this_hdr.sh_info = -2;
9793             }
9794           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9795             {
9796               /* We'll use the output section target_index.  */
9797               asection *sec = flinfo->sections[symndx]->output_section;
9798               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9799             }
9800           else
9801             {
9802               if (flinfo->indices[symndx] == -1)
9803                 {
9804                   /* Otherwise output the local symbol now.  */
9805                   Elf_Internal_Sym sym = isymbuf[symndx];
9806                   asection *sec = flinfo->sections[symndx]->output_section;
9807                   const char *name;
9808                   long indx;
9809                   int ret;
9810
9811                   name = bfd_elf_string_from_elf_section (input_bfd,
9812                                                           symtab_hdr->sh_link,
9813                                                           sym.st_name);
9814                   if (name == NULL)
9815                     return FALSE;
9816
9817                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9818                                                                     sec);
9819                   if (sym.st_shndx == SHN_BAD)
9820                     return FALSE;
9821
9822                   sym.st_value += o->output_offset;
9823
9824                   indx = bfd_get_symcount (output_bfd);
9825                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
9826                                                    NULL);
9827                   if (ret == 0)
9828                     return FALSE;
9829                   else if (ret == 1)
9830                     flinfo->indices[symndx] = indx;
9831                   else
9832                     abort ();
9833                 }
9834               elf_section_data (osec)->this_hdr.sh_info
9835                 = flinfo->indices[symndx];
9836             }
9837         }
9838
9839       if ((o->flags & SEC_HAS_CONTENTS) == 0
9840           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9841         continue;
9842
9843       if ((o->flags & SEC_LINKER_CREATED) != 0)
9844         {
9845           /* Section was created by _bfd_elf_link_create_dynamic_sections
9846              or somesuch.  */
9847           continue;
9848         }
9849
9850       /* Get the contents of the section.  They have been cached by a
9851          relaxation routine.  Note that o is a section in an input
9852          file, so the contents field will not have been set by any of
9853          the routines which work on output files.  */
9854       if (elf_section_data (o)->this_hdr.contents != NULL)
9855         {
9856           contents = elf_section_data (o)->this_hdr.contents;
9857           if (bed->caches_rawsize
9858               && o->rawsize != 0
9859               && o->rawsize < o->size)
9860             {
9861               memcpy (flinfo->contents, contents, o->rawsize);
9862               contents = flinfo->contents;
9863             }
9864         }
9865       else
9866         {
9867           contents = flinfo->contents;
9868           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9869             return FALSE;
9870         }
9871
9872       if ((o->flags & SEC_RELOC) != 0)
9873         {
9874           Elf_Internal_Rela *internal_relocs;
9875           Elf_Internal_Rela *rel, *relend;
9876           int action_discarded;
9877           int ret;
9878
9879           /* Get the swapped relocs.  */
9880           internal_relocs
9881             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
9882                                          flinfo->internal_relocs, FALSE);
9883           if (internal_relocs == NULL
9884               && o->reloc_count > 0)
9885             return FALSE;
9886
9887           /* We need to reverse-copy input .ctors/.dtors sections if
9888              they are placed in .init_array/.finit_array for output.  */
9889           if (o->size > address_size
9890               && ((strncmp (o->name, ".ctors", 6) == 0
9891                    && strcmp (o->output_section->name,
9892                               ".init_array") == 0)
9893                   || (strncmp (o->name, ".dtors", 6) == 0
9894                       && strcmp (o->output_section->name,
9895                                  ".fini_array") == 0))
9896               && (o->name[6] == 0 || o->name[6] == '.'))
9897             {
9898               if (o->size != o->reloc_count * address_size)
9899                 {
9900                   (*_bfd_error_handler)
9901                     (_("error: %B: size of section %A is not "
9902                        "multiple of address size"),
9903                      input_bfd, o);
9904                   bfd_set_error (bfd_error_on_input);
9905                   return FALSE;
9906                 }
9907               o->flags |= SEC_ELF_REVERSE_COPY;
9908             }
9909
9910           action_discarded = -1;
9911           if (!elf_section_ignore_discarded_relocs (o))
9912             action_discarded = (*bed->action_discarded) (o);
9913
9914           /* Run through the relocs evaluating complex reloc symbols and
9915              looking for relocs against symbols from discarded sections
9916              or section symbols from removed link-once sections.
9917              Complain about relocs against discarded sections.  Zero
9918              relocs against removed link-once sections.  */
9919
9920           rel = internal_relocs;
9921           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9922           for ( ; rel < relend; rel++)
9923             {
9924               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9925               unsigned int s_type;
9926               asection **ps, *sec;
9927               struct elf_link_hash_entry *h = NULL;
9928               const char *sym_name;
9929
9930               if (r_symndx == STN_UNDEF)
9931                 continue;
9932
9933               if (r_symndx >= locsymcount
9934                   || (elf_bad_symtab (input_bfd)
9935                       && flinfo->sections[r_symndx] == NULL))
9936                 {
9937                   h = sym_hashes[r_symndx - extsymoff];
9938
9939                   /* Badly formatted input files can contain relocs that
9940                      reference non-existant symbols.  Check here so that
9941                      we do not seg fault.  */
9942                   if (h == NULL)
9943                     {
9944                       char buffer [32];
9945
9946                       sprintf_vma (buffer, rel->r_info);
9947                       (*_bfd_error_handler)
9948                         (_("error: %B contains a reloc (0x%s) for section %A "
9949                            "that references a non-existent global symbol"),
9950                          input_bfd, o, buffer);
9951                       bfd_set_error (bfd_error_bad_value);
9952                       return FALSE;
9953                     }
9954
9955                   while (h->root.type == bfd_link_hash_indirect
9956                          || h->root.type == bfd_link_hash_warning)
9957                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9958
9959                   s_type = h->type;
9960
9961                   /* If a plugin symbol is referenced from a non-IR file,
9962                      mark the symbol as undefined.  Note that the
9963                      linker may attach linker created dynamic sections
9964                      to the plugin bfd.  Symbols defined in linker
9965                      created sections are not plugin symbols.  */
9966                   if (h->root.non_ir_ref
9967                       && (h->root.type == bfd_link_hash_defined
9968                           || h->root.type == bfd_link_hash_defweak)
9969                       && (h->root.u.def.section->flags
9970                           & SEC_LINKER_CREATED) == 0
9971                       && h->root.u.def.section->owner != NULL
9972                       && (h->root.u.def.section->owner->flags
9973                           & BFD_PLUGIN) != 0)
9974                     {
9975                       h->root.type = bfd_link_hash_undefined;
9976                       h->root.u.undef.abfd = h->root.u.def.section->owner;
9977                     }
9978
9979                   ps = NULL;
9980                   if (h->root.type == bfd_link_hash_defined
9981                       || h->root.type == bfd_link_hash_defweak)
9982                     ps = &h->root.u.def.section;
9983
9984                   sym_name = h->root.root.string;
9985                 }
9986               else
9987                 {
9988                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
9989
9990                   s_type = ELF_ST_TYPE (sym->st_info);
9991                   ps = &flinfo->sections[r_symndx];
9992                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9993                                                sym, *ps);
9994                 }
9995
9996               if ((s_type == STT_RELC || s_type == STT_SRELC)
9997                   && !flinfo->info->relocatable)
9998                 {
9999                   bfd_vma val;
10000                   bfd_vma dot = (rel->r_offset
10001                                  + o->output_offset + o->output_section->vma);
10002 #ifdef DEBUG
10003                   printf ("Encountered a complex symbol!");
10004                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10005                           input_bfd->filename, o->name,
10006                           (long) (rel - internal_relocs));
10007                   printf (" symbol: idx  %8.8lx, name %s\n",
10008                           r_symndx, sym_name);
10009                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10010                           (unsigned long) rel->r_info,
10011                           (unsigned long) rel->r_offset);
10012 #endif
10013                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10014                                     isymbuf, locsymcount, s_type == STT_SRELC))
10015                     return FALSE;
10016
10017                   /* Symbol evaluated OK.  Update to absolute value.  */
10018                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10019                                     r_symndx, val);
10020                   continue;
10021                 }
10022
10023               if (action_discarded != -1 && ps != NULL)
10024                 {
10025                   /* Complain if the definition comes from a
10026                      discarded section.  */
10027                   if ((sec = *ps) != NULL && discarded_section (sec))
10028                     {
10029                       BFD_ASSERT (r_symndx != STN_UNDEF);
10030                       if (action_discarded & COMPLAIN)
10031                         (*flinfo->info->callbacks->einfo)
10032                           (_("%X`%s' referenced in section `%A' of %B: "
10033                              "defined in discarded section `%A' of %B\n"),
10034                            sym_name, o, input_bfd, sec, sec->owner);
10035
10036                       /* Try to do the best we can to support buggy old
10037                          versions of gcc.  Pretend that the symbol is
10038                          really defined in the kept linkonce section.
10039                          FIXME: This is quite broken.  Modifying the
10040                          symbol here means we will be changing all later
10041                          uses of the symbol, not just in this section.  */
10042                       if (action_discarded & PRETEND)
10043                         {
10044                           asection *kept;
10045
10046                           kept = _bfd_elf_check_kept_section (sec,
10047                                                               flinfo->info);
10048                           if (kept != NULL)
10049                             {
10050                               *ps = kept;
10051                               continue;
10052                             }
10053                         }
10054                     }
10055                 }
10056             }
10057
10058           /* Relocate the section by invoking a back end routine.
10059
10060              The back end routine is responsible for adjusting the
10061              section contents as necessary, and (if using Rela relocs
10062              and generating a relocatable output file) adjusting the
10063              reloc addend as necessary.
10064
10065              The back end routine does not have to worry about setting
10066              the reloc address or the reloc symbol index.
10067
10068              The back end routine is given a pointer to the swapped in
10069              internal symbols, and can access the hash table entries
10070              for the external symbols via elf_sym_hashes (input_bfd).
10071
10072              When generating relocatable output, the back end routine
10073              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10074              output symbol is going to be a section symbol
10075              corresponding to the output section, which will require
10076              the addend to be adjusted.  */
10077
10078           ret = (*relocate_section) (output_bfd, flinfo->info,
10079                                      input_bfd, o, contents,
10080                                      internal_relocs,
10081                                      isymbuf,
10082                                      flinfo->sections);
10083           if (!ret)
10084             return FALSE;
10085
10086           if (ret == 2
10087               || flinfo->info->relocatable
10088               || flinfo->info->emitrelocations)
10089             {
10090               Elf_Internal_Rela *irela;
10091               Elf_Internal_Rela *irelaend, *irelamid;
10092               bfd_vma last_offset;
10093               struct elf_link_hash_entry **rel_hash;
10094               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10095               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10096               unsigned int next_erel;
10097               bfd_boolean rela_normal;
10098               struct bfd_elf_section_data *esdi, *esdo;
10099
10100               esdi = elf_section_data (o);
10101               esdo = elf_section_data (o->output_section);
10102               rela_normal = FALSE;
10103
10104               /* Adjust the reloc addresses and symbol indices.  */
10105
10106               irela = internal_relocs;
10107               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10108               rel_hash = esdo->rel.hashes + esdo->rel.count;
10109               /* We start processing the REL relocs, if any.  When we reach
10110                  IRELAMID in the loop, we switch to the RELA relocs.  */
10111               irelamid = irela;
10112               if (esdi->rel.hdr != NULL)
10113                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10114                              * bed->s->int_rels_per_ext_rel);
10115               rel_hash_list = rel_hash;
10116               rela_hash_list = NULL;
10117               last_offset = o->output_offset;
10118               if (!flinfo->info->relocatable)
10119                 last_offset += o->output_section->vma;
10120               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10121                 {
10122                   unsigned long r_symndx;
10123                   asection *sec;
10124                   Elf_Internal_Sym sym;
10125
10126                   if (next_erel == bed->s->int_rels_per_ext_rel)
10127                     {
10128                       rel_hash++;
10129                       next_erel = 0;
10130                     }
10131
10132                   if (irela == irelamid)
10133                     {
10134                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10135                       rela_hash_list = rel_hash;
10136                       rela_normal = bed->rela_normal;
10137                     }
10138
10139                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10140                                                              flinfo->info, o,
10141                                                              irela->r_offset);
10142                   if (irela->r_offset >= (bfd_vma) -2)
10143                     {
10144                       /* This is a reloc for a deleted entry or somesuch.
10145                          Turn it into an R_*_NONE reloc, at the same
10146                          offset as the last reloc.  elf_eh_frame.c and
10147                          bfd_elf_discard_info rely on reloc offsets
10148                          being ordered.  */
10149                       irela->r_offset = last_offset;
10150                       irela->r_info = 0;
10151                       irela->r_addend = 0;
10152                       continue;
10153                     }
10154
10155                   irela->r_offset += o->output_offset;
10156
10157                   /* Relocs in an executable have to be virtual addresses.  */
10158                   if (!flinfo->info->relocatable)
10159                     irela->r_offset += o->output_section->vma;
10160
10161                   last_offset = irela->r_offset;
10162
10163                   r_symndx = irela->r_info >> r_sym_shift;
10164                   if (r_symndx == STN_UNDEF)
10165                     continue;
10166
10167                   if (r_symndx >= locsymcount
10168                       || (elf_bad_symtab (input_bfd)
10169                           && flinfo->sections[r_symndx] == NULL))
10170                     {
10171                       struct elf_link_hash_entry *rh;
10172                       unsigned long indx;
10173
10174                       /* This is a reloc against a global symbol.  We
10175                          have not yet output all the local symbols, so
10176                          we do not know the symbol index of any global
10177                          symbol.  We set the rel_hash entry for this
10178                          reloc to point to the global hash table entry
10179                          for this symbol.  The symbol index is then
10180                          set at the end of bfd_elf_final_link.  */
10181                       indx = r_symndx - extsymoff;
10182                       rh = elf_sym_hashes (input_bfd)[indx];
10183                       while (rh->root.type == bfd_link_hash_indirect
10184                              || rh->root.type == bfd_link_hash_warning)
10185                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10186
10187                       /* Setting the index to -2 tells
10188                          elf_link_output_extsym that this symbol is
10189                          used by a reloc.  */
10190                       BFD_ASSERT (rh->indx < 0);
10191                       rh->indx = -2;
10192
10193                       *rel_hash = rh;
10194
10195                       continue;
10196                     }
10197
10198                   /* This is a reloc against a local symbol.  */
10199
10200                   *rel_hash = NULL;
10201                   sym = isymbuf[r_symndx];
10202                   sec = flinfo->sections[r_symndx];
10203                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10204                     {
10205                       /* I suppose the backend ought to fill in the
10206                          section of any STT_SECTION symbol against a
10207                          processor specific section.  */
10208                       r_symndx = STN_UNDEF;
10209                       if (bfd_is_abs_section (sec))
10210                         ;
10211                       else if (sec == NULL || sec->owner == NULL)
10212                         {
10213                           bfd_set_error (bfd_error_bad_value);
10214                           return FALSE;
10215                         }
10216                       else
10217                         {
10218                           asection *osec = sec->output_section;
10219
10220                           /* If we have discarded a section, the output
10221                              section will be the absolute section.  In
10222                              case of discarded SEC_MERGE sections, use
10223                              the kept section.  relocate_section should
10224                              have already handled discarded linkonce
10225                              sections.  */
10226                           if (bfd_is_abs_section (osec)
10227                               && sec->kept_section != NULL
10228                               && sec->kept_section->output_section != NULL)
10229                             {
10230                               osec = sec->kept_section->output_section;
10231                               irela->r_addend -= osec->vma;
10232                             }
10233
10234                           if (!bfd_is_abs_section (osec))
10235                             {
10236                               r_symndx = osec->target_index;
10237                               if (r_symndx == STN_UNDEF)
10238                                 {
10239                                   irela->r_addend += osec->vma;
10240                                   osec = _bfd_nearby_section (output_bfd, osec,
10241                                                               osec->vma);
10242                                   irela->r_addend -= osec->vma;
10243                                   r_symndx = osec->target_index;
10244                                 }
10245                             }
10246                         }
10247
10248                       /* Adjust the addend according to where the
10249                          section winds up in the output section.  */
10250                       if (rela_normal)
10251                         irela->r_addend += sec->output_offset;
10252                     }
10253                   else
10254                     {
10255                       if (flinfo->indices[r_symndx] == -1)
10256                         {
10257                           unsigned long shlink;
10258                           const char *name;
10259                           asection *osec;
10260                           long indx;
10261
10262                           if (flinfo->info->strip == strip_all)
10263                             {
10264                               /* You can't do ld -r -s.  */
10265                               bfd_set_error (bfd_error_invalid_operation);
10266                               return FALSE;
10267                             }
10268
10269                           /* This symbol was skipped earlier, but
10270                              since it is needed by a reloc, we
10271                              must output it now.  */
10272                           shlink = symtab_hdr->sh_link;
10273                           name = (bfd_elf_string_from_elf_section
10274                                   (input_bfd, shlink, sym.st_name));
10275                           if (name == NULL)
10276                             return FALSE;
10277
10278                           osec = sec->output_section;
10279                           sym.st_shndx =
10280                             _bfd_elf_section_from_bfd_section (output_bfd,
10281                                                                osec);
10282                           if (sym.st_shndx == SHN_BAD)
10283                             return FALSE;
10284
10285                           sym.st_value += sec->output_offset;
10286                           if (!flinfo->info->relocatable)
10287                             {
10288                               sym.st_value += osec->vma;
10289                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10290                                 {
10291                                   /* STT_TLS symbols are relative to PT_TLS
10292                                      segment base.  */
10293                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10294                                               ->tls_sec != NULL);
10295                                   sym.st_value -= (elf_hash_table (flinfo->info)
10296                                                    ->tls_sec->vma);
10297                                 }
10298                             }
10299
10300                           indx = bfd_get_symcount (output_bfd);
10301                           ret = elf_link_output_symstrtab (flinfo, name,
10302                                                            &sym, sec,
10303                                                            NULL);
10304                           if (ret == 0)
10305                             return FALSE;
10306                           else if (ret == 1)
10307                             flinfo->indices[r_symndx] = indx;
10308                           else
10309                             abort ();
10310                         }
10311
10312                       r_symndx = flinfo->indices[r_symndx];
10313                     }
10314
10315                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10316                                    | (irela->r_info & r_type_mask));
10317                 }
10318
10319               /* Swap out the relocs.  */
10320               input_rel_hdr = esdi->rel.hdr;
10321               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10322                 {
10323                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10324                                                      input_rel_hdr,
10325                                                      internal_relocs,
10326                                                      rel_hash_list))
10327                     return FALSE;
10328                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10329                                       * bed->s->int_rels_per_ext_rel);
10330                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10331                 }
10332
10333               input_rela_hdr = esdi->rela.hdr;
10334               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10335                 {
10336                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10337                                                      input_rela_hdr,
10338                                                      internal_relocs,
10339                                                      rela_hash_list))
10340                     return FALSE;
10341                 }
10342             }
10343         }
10344
10345       /* Write out the modified section contents.  */
10346       if (bed->elf_backend_write_section
10347           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10348                                                 contents))
10349         {
10350           /* Section written out.  */
10351         }
10352       else switch (o->sec_info_type)
10353         {
10354         case SEC_INFO_TYPE_STABS:
10355           if (! (_bfd_write_section_stabs
10356                  (output_bfd,
10357                   &elf_hash_table (flinfo->info)->stab_info,
10358                   o, &elf_section_data (o)->sec_info, contents)))
10359             return FALSE;
10360           break;
10361         case SEC_INFO_TYPE_MERGE:
10362           if (! _bfd_write_merged_section (output_bfd, o,
10363                                            elf_section_data (o)->sec_info))
10364             return FALSE;
10365           break;
10366         case SEC_INFO_TYPE_EH_FRAME:
10367           {
10368             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10369                                                    o, contents))
10370               return FALSE;
10371           }
10372           break;
10373         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10374           {
10375             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10376                                                          flinfo->info,
10377                                                          o, contents))
10378               return FALSE;
10379           }
10380           break;
10381         default:
10382           {
10383             /* FIXME: octets_per_byte.  */
10384             if (! (o->flags & SEC_EXCLUDE))
10385               {
10386                 file_ptr offset = (file_ptr) o->output_offset;
10387                 bfd_size_type todo = o->size;
10388                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10389                   {
10390                     /* Reverse-copy input section to output.  */
10391                     do
10392                       {
10393                         todo -= address_size;
10394                         if (! bfd_set_section_contents (output_bfd,
10395                                                         o->output_section,
10396                                                         contents + todo,
10397                                                         offset,
10398                                                         address_size))
10399                           return FALSE;
10400                         if (todo == 0)
10401                           break;
10402                         offset += address_size;
10403                       }
10404                     while (1);
10405                   }
10406                 else if (! bfd_set_section_contents (output_bfd,
10407                                                      o->output_section,
10408                                                      contents,
10409                                                      offset, todo))
10410                   return FALSE;
10411               }
10412           }
10413           break;
10414         }
10415     }
10416
10417   return TRUE;
10418 }
10419
10420 /* Generate a reloc when linking an ELF file.  This is a reloc
10421    requested by the linker, and does not come from any input file.  This
10422    is used to build constructor and destructor tables when linking
10423    with -Ur.  */
10424
10425 static bfd_boolean
10426 elf_reloc_link_order (bfd *output_bfd,
10427                       struct bfd_link_info *info,
10428                       asection *output_section,
10429                       struct bfd_link_order *link_order)
10430 {
10431   reloc_howto_type *howto;
10432   long indx;
10433   bfd_vma offset;
10434   bfd_vma addend;
10435   struct bfd_elf_section_reloc_data *reldata;
10436   struct elf_link_hash_entry **rel_hash_ptr;
10437   Elf_Internal_Shdr *rel_hdr;
10438   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10439   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10440   bfd_byte *erel;
10441   unsigned int i;
10442   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10443
10444   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10445   if (howto == NULL)
10446     {
10447       bfd_set_error (bfd_error_bad_value);
10448       return FALSE;
10449     }
10450
10451   addend = link_order->u.reloc.p->addend;
10452
10453   if (esdo->rel.hdr)
10454     reldata = &esdo->rel;
10455   else if (esdo->rela.hdr)
10456     reldata = &esdo->rela;
10457   else
10458     {
10459       reldata = NULL;
10460       BFD_ASSERT (0);
10461     }
10462
10463   /* Figure out the symbol index.  */
10464   rel_hash_ptr = reldata->hashes + reldata->count;
10465   if (link_order->type == bfd_section_reloc_link_order)
10466     {
10467       indx = link_order->u.reloc.p->u.section->target_index;
10468       BFD_ASSERT (indx != 0);
10469       *rel_hash_ptr = NULL;
10470     }
10471   else
10472     {
10473       struct elf_link_hash_entry *h;
10474
10475       /* Treat a reloc against a defined symbol as though it were
10476          actually against the section.  */
10477       h = ((struct elf_link_hash_entry *)
10478            bfd_wrapped_link_hash_lookup (output_bfd, info,
10479                                          link_order->u.reloc.p->u.name,
10480                                          FALSE, FALSE, TRUE));
10481       if (h != NULL
10482           && (h->root.type == bfd_link_hash_defined
10483               || h->root.type == bfd_link_hash_defweak))
10484         {
10485           asection *section;
10486
10487           section = h->root.u.def.section;
10488           indx = section->output_section->target_index;
10489           *rel_hash_ptr = NULL;
10490           /* It seems that we ought to add the symbol value to the
10491              addend here, but in practice it has already been added
10492              because it was passed to constructor_callback.  */
10493           addend += section->output_section->vma + section->output_offset;
10494         }
10495       else if (h != NULL)
10496         {
10497           /* Setting the index to -2 tells elf_link_output_extsym that
10498              this symbol is used by a reloc.  */
10499           h->indx = -2;
10500           *rel_hash_ptr = h;
10501           indx = 0;
10502         }
10503       else
10504         {
10505           if (! ((*info->callbacks->unattached_reloc)
10506                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10507             return FALSE;
10508           indx = 0;
10509         }
10510     }
10511
10512   /* If this is an inplace reloc, we must write the addend into the
10513      object file.  */
10514   if (howto->partial_inplace && addend != 0)
10515     {
10516       bfd_size_type size;
10517       bfd_reloc_status_type rstat;
10518       bfd_byte *buf;
10519       bfd_boolean ok;
10520       const char *sym_name;
10521
10522       size = (bfd_size_type) bfd_get_reloc_size (howto);
10523       buf = (bfd_byte *) bfd_zmalloc (size);
10524       if (buf == NULL && size != 0)
10525         return FALSE;
10526       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10527       switch (rstat)
10528         {
10529         case bfd_reloc_ok:
10530           break;
10531
10532         default:
10533         case bfd_reloc_outofrange:
10534           abort ();
10535
10536         case bfd_reloc_overflow:
10537           if (link_order->type == bfd_section_reloc_link_order)
10538             sym_name = bfd_section_name (output_bfd,
10539                                          link_order->u.reloc.p->u.section);
10540           else
10541             sym_name = link_order->u.reloc.p->u.name;
10542           if (! ((*info->callbacks->reloc_overflow)
10543                  (info, NULL, sym_name, howto->name, addend, NULL,
10544                   NULL, (bfd_vma) 0)))
10545             {
10546               free (buf);
10547               return FALSE;
10548             }
10549           break;
10550         }
10551       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10552                                      link_order->offset, size);
10553       free (buf);
10554       if (! ok)
10555         return FALSE;
10556     }
10557
10558   /* The address of a reloc is relative to the section in a
10559      relocatable file, and is a virtual address in an executable
10560      file.  */
10561   offset = link_order->offset;
10562   if (! info->relocatable)
10563     offset += output_section->vma;
10564
10565   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10566     {
10567       irel[i].r_offset = offset;
10568       irel[i].r_info = 0;
10569       irel[i].r_addend = 0;
10570     }
10571   if (bed->s->arch_size == 32)
10572     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10573   else
10574     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10575
10576   rel_hdr = reldata->hdr;
10577   erel = rel_hdr->contents;
10578   if (rel_hdr->sh_type == SHT_REL)
10579     {
10580       erel += reldata->count * bed->s->sizeof_rel;
10581       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10582     }
10583   else
10584     {
10585       irel[0].r_addend = addend;
10586       erel += reldata->count * bed->s->sizeof_rela;
10587       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10588     }
10589
10590   ++reldata->count;
10591
10592   return TRUE;
10593 }
10594
10595
10596 /* Get the output vma of the section pointed to by the sh_link field.  */
10597
10598 static bfd_vma
10599 elf_get_linked_section_vma (struct bfd_link_order *p)
10600 {
10601   Elf_Internal_Shdr **elf_shdrp;
10602   asection *s;
10603   int elfsec;
10604
10605   s = p->u.indirect.section;
10606   elf_shdrp = elf_elfsections (s->owner);
10607   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10608   elfsec = elf_shdrp[elfsec]->sh_link;
10609   /* PR 290:
10610      The Intel C compiler generates SHT_IA_64_UNWIND with
10611      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10612      sh_info fields.  Hence we could get the situation
10613      where elfsec is 0.  */
10614   if (elfsec == 0)
10615     {
10616       const struct elf_backend_data *bed
10617         = get_elf_backend_data (s->owner);
10618       if (bed->link_order_error_handler)
10619         bed->link_order_error_handler
10620           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10621       return 0;
10622     }
10623   else
10624     {
10625       s = elf_shdrp[elfsec]->bfd_section;
10626       return s->output_section->vma + s->output_offset;
10627     }
10628 }
10629
10630
10631 /* Compare two sections based on the locations of the sections they are
10632    linked to.  Used by elf_fixup_link_order.  */
10633
10634 static int
10635 compare_link_order (const void * a, const void * b)
10636 {
10637   bfd_vma apos;
10638   bfd_vma bpos;
10639
10640   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10641   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10642   if (apos < bpos)
10643     return -1;
10644   return apos > bpos;
10645 }
10646
10647
10648 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10649    order as their linked sections.  Returns false if this could not be done
10650    because an output section includes both ordered and unordered
10651    sections.  Ideally we'd do this in the linker proper.  */
10652
10653 static bfd_boolean
10654 elf_fixup_link_order (bfd *abfd, asection *o)
10655 {
10656   int seen_linkorder;
10657   int seen_other;
10658   int n;
10659   struct bfd_link_order *p;
10660   bfd *sub;
10661   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10662   unsigned elfsec;
10663   struct bfd_link_order **sections;
10664   asection *s, *other_sec, *linkorder_sec;
10665   bfd_vma offset;
10666
10667   other_sec = NULL;
10668   linkorder_sec = NULL;
10669   seen_other = 0;
10670   seen_linkorder = 0;
10671   for (p = o->map_head.link_order; p != NULL; p = p->next)
10672     {
10673       if (p->type == bfd_indirect_link_order)
10674         {
10675           s = p->u.indirect.section;
10676           sub = s->owner;
10677           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10678               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10679               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10680               && elfsec < elf_numsections (sub)
10681               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10682               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10683             {
10684               seen_linkorder++;
10685               linkorder_sec = s;
10686             }
10687           else
10688             {
10689               seen_other++;
10690               other_sec = s;
10691             }
10692         }
10693       else
10694         seen_other++;
10695
10696       if (seen_other && seen_linkorder)
10697         {
10698           if (other_sec && linkorder_sec)
10699             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10700                                    o, linkorder_sec,
10701                                    linkorder_sec->owner, other_sec,
10702                                    other_sec->owner);
10703           else
10704             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10705                                    o);
10706           bfd_set_error (bfd_error_bad_value);
10707           return FALSE;
10708         }
10709     }
10710
10711   if (!seen_linkorder)
10712     return TRUE;
10713
10714   sections = (struct bfd_link_order **)
10715     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10716   if (sections == NULL)
10717     return FALSE;
10718   seen_linkorder = 0;
10719
10720   for (p = o->map_head.link_order; p != NULL; p = p->next)
10721     {
10722       sections[seen_linkorder++] = p;
10723     }
10724   /* Sort the input sections in the order of their linked section.  */
10725   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10726          compare_link_order);
10727
10728   /* Change the offsets of the sections.  */
10729   offset = 0;
10730   for (n = 0; n < seen_linkorder; n++)
10731     {
10732       s = sections[n]->u.indirect.section;
10733       offset &= ~(bfd_vma) 0 << s->alignment_power;
10734       s->output_offset = offset;
10735       sections[n]->offset = offset;
10736       /* FIXME: octets_per_byte.  */
10737       offset += sections[n]->size;
10738     }
10739
10740   free (sections);
10741   return TRUE;
10742 }
10743
10744 static void
10745 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10746 {
10747   asection *o;
10748
10749   if (flinfo->symstrtab != NULL)
10750     _bfd_elf_strtab_free (flinfo->symstrtab);
10751   if (flinfo->contents != NULL)
10752     free (flinfo->contents);
10753   if (flinfo->external_relocs != NULL)
10754     free (flinfo->external_relocs);
10755   if (flinfo->internal_relocs != NULL)
10756     free (flinfo->internal_relocs);
10757   if (flinfo->external_syms != NULL)
10758     free (flinfo->external_syms);
10759   if (flinfo->locsym_shndx != NULL)
10760     free (flinfo->locsym_shndx);
10761   if (flinfo->internal_syms != NULL)
10762     free (flinfo->internal_syms);
10763   if (flinfo->indices != NULL)
10764     free (flinfo->indices);
10765   if (flinfo->sections != NULL)
10766     free (flinfo->sections);
10767   if (flinfo->symshndxbuf != NULL)
10768     free (flinfo->symshndxbuf);
10769   for (o = obfd->sections; o != NULL; o = o->next)
10770     {
10771       struct bfd_elf_section_data *esdo = elf_section_data (o);
10772       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10773         free (esdo->rel.hashes);
10774       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10775         free (esdo->rela.hashes);
10776     }
10777 }
10778
10779 /* Do the final step of an ELF link.  */
10780
10781 bfd_boolean
10782 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10783 {
10784   bfd_boolean dynamic;
10785   bfd_boolean emit_relocs;
10786   bfd *dynobj;
10787   struct elf_final_link_info flinfo;
10788   asection *o;
10789   struct bfd_link_order *p;
10790   bfd *sub;
10791   bfd_size_type max_contents_size;
10792   bfd_size_type max_external_reloc_size;
10793   bfd_size_type max_internal_reloc_count;
10794   bfd_size_type max_sym_count;
10795   bfd_size_type max_sym_shndx_count;
10796   Elf_Internal_Sym elfsym;
10797   unsigned int i;
10798   Elf_Internal_Shdr *symtab_hdr;
10799   Elf_Internal_Shdr *symtab_shndx_hdr;
10800   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10801   struct elf_outext_info eoinfo;
10802   bfd_boolean merged;
10803   size_t relativecount = 0;
10804   asection *reldyn = 0;
10805   bfd_size_type amt;
10806   asection *attr_section = NULL;
10807   bfd_vma attr_size = 0;
10808   const char *std_attrs_section;
10809
10810   if (! is_elf_hash_table (info->hash))
10811     return FALSE;
10812
10813   if (info->shared)
10814     abfd->flags |= DYNAMIC;
10815
10816   dynamic = elf_hash_table (info)->dynamic_sections_created;
10817   dynobj = elf_hash_table (info)->dynobj;
10818
10819   emit_relocs = (info->relocatable
10820                  || info->emitrelocations);
10821
10822   flinfo.info = info;
10823   flinfo.output_bfd = abfd;
10824   flinfo.symstrtab = _bfd_elf_strtab_init ();
10825   if (flinfo.symstrtab == NULL)
10826     return FALSE;
10827
10828   if (! dynamic)
10829     {
10830       flinfo.dynsym_sec = NULL;
10831       flinfo.hash_sec = NULL;
10832       flinfo.symver_sec = NULL;
10833     }
10834   else
10835     {
10836       flinfo.dynsym_sec = bfd_get_linker_section (dynobj, ".dynsym");
10837       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
10838       /* Note that dynsym_sec can be NULL (on VMS).  */
10839       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
10840       /* Note that it is OK if symver_sec is NULL.  */
10841     }
10842
10843   flinfo.contents = NULL;
10844   flinfo.external_relocs = NULL;
10845   flinfo.internal_relocs = NULL;
10846   flinfo.external_syms = NULL;
10847   flinfo.locsym_shndx = NULL;
10848   flinfo.internal_syms = NULL;
10849   flinfo.indices = NULL;
10850   flinfo.sections = NULL;
10851   flinfo.symshndxbuf = NULL;
10852   flinfo.filesym_count = 0;
10853
10854   /* The object attributes have been merged.  Remove the input
10855      sections from the link, and set the contents of the output
10856      secton.  */
10857   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10858   for (o = abfd->sections; o != NULL; o = o->next)
10859     {
10860       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10861           || strcmp (o->name, ".gnu.attributes") == 0)
10862         {
10863           for (p = o->map_head.link_order; p != NULL; p = p->next)
10864             {
10865               asection *input_section;
10866
10867               if (p->type != bfd_indirect_link_order)
10868                 continue;
10869               input_section = p->u.indirect.section;
10870               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10871                  elf_link_input_bfd ignores this section.  */
10872               input_section->flags &= ~SEC_HAS_CONTENTS;
10873             }
10874
10875           attr_size = bfd_elf_obj_attr_size (abfd);
10876           if (attr_size)
10877             {
10878               bfd_set_section_size (abfd, o, attr_size);
10879               attr_section = o;
10880               /* Skip this section later on.  */
10881               o->map_head.link_order = NULL;
10882             }
10883           else
10884             o->flags |= SEC_EXCLUDE;
10885         }
10886     }
10887
10888   /* Count up the number of relocations we will output for each output
10889      section, so that we know the sizes of the reloc sections.  We
10890      also figure out some maximum sizes.  */
10891   max_contents_size = 0;
10892   max_external_reloc_size = 0;
10893   max_internal_reloc_count = 0;
10894   max_sym_count = 0;
10895   max_sym_shndx_count = 0;
10896   merged = FALSE;
10897   for (o = abfd->sections; o != NULL; o = o->next)
10898     {
10899       struct bfd_elf_section_data *esdo = elf_section_data (o);
10900       o->reloc_count = 0;
10901
10902       for (p = o->map_head.link_order; p != NULL; p = p->next)
10903         {
10904           unsigned int reloc_count = 0;
10905           struct bfd_elf_section_data *esdi = NULL;
10906
10907           if (p->type == bfd_section_reloc_link_order
10908               || p->type == bfd_symbol_reloc_link_order)
10909             reloc_count = 1;
10910           else if (p->type == bfd_indirect_link_order)
10911             {
10912               asection *sec;
10913
10914               sec = p->u.indirect.section;
10915               esdi = elf_section_data (sec);
10916
10917               /* Mark all sections which are to be included in the
10918                  link.  This will normally be every section.  We need
10919                  to do this so that we can identify any sections which
10920                  the linker has decided to not include.  */
10921               sec->linker_mark = TRUE;
10922
10923               if (sec->flags & SEC_MERGE)
10924                 merged = TRUE;
10925
10926               if (esdo->this_hdr.sh_type == SHT_REL
10927                   || esdo->this_hdr.sh_type == SHT_RELA)
10928                 /* Some backends use reloc_count in relocation sections
10929                    to count particular types of relocs.  Of course,
10930                    reloc sections themselves can't have relocations.  */
10931                 reloc_count = 0;
10932               else if (info->relocatable || info->emitrelocations)
10933                 reloc_count = sec->reloc_count;
10934               else if (bed->elf_backend_count_relocs)
10935                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10936
10937               if (sec->rawsize > max_contents_size)
10938                 max_contents_size = sec->rawsize;
10939               if (sec->size > max_contents_size)
10940                 max_contents_size = sec->size;
10941
10942               /* We are interested in just local symbols, not all
10943                  symbols.  */
10944               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10945                   && (sec->owner->flags & DYNAMIC) == 0)
10946                 {
10947                   size_t sym_count;
10948
10949                   if (elf_bad_symtab (sec->owner))
10950                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10951                                  / bed->s->sizeof_sym);
10952                   else
10953                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10954
10955                   if (sym_count > max_sym_count)
10956                     max_sym_count = sym_count;
10957
10958                   if (sym_count > max_sym_shndx_count
10959                       && elf_symtab_shndx (sec->owner) != 0)
10960                     max_sym_shndx_count = sym_count;
10961
10962                   if ((sec->flags & SEC_RELOC) != 0)
10963                     {
10964                       size_t ext_size = 0;
10965
10966                       if (esdi->rel.hdr != NULL)
10967                         ext_size = esdi->rel.hdr->sh_size;
10968                       if (esdi->rela.hdr != NULL)
10969                         ext_size += esdi->rela.hdr->sh_size;
10970
10971                       if (ext_size > max_external_reloc_size)
10972                         max_external_reloc_size = ext_size;
10973                       if (sec->reloc_count > max_internal_reloc_count)
10974                         max_internal_reloc_count = sec->reloc_count;
10975                     }
10976                 }
10977             }
10978
10979           if (reloc_count == 0)
10980             continue;
10981
10982           o->reloc_count += reloc_count;
10983
10984           if (p->type == bfd_indirect_link_order
10985               && (info->relocatable || info->emitrelocations))
10986             {
10987               if (esdi->rel.hdr)
10988                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
10989               if (esdi->rela.hdr)
10990                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
10991             }
10992           else
10993             {
10994               if (o->use_rela_p)
10995                 esdo->rela.count += reloc_count;
10996               else
10997                 esdo->rel.count += reloc_count;
10998             }
10999         }
11000
11001       if (o->reloc_count > 0)
11002         o->flags |= SEC_RELOC;
11003       else
11004         {
11005           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11006              set it (this is probably a bug) and if it is set
11007              assign_section_numbers will create a reloc section.  */
11008           o->flags &=~ SEC_RELOC;
11009         }
11010
11011       /* If the SEC_ALLOC flag is not set, force the section VMA to
11012          zero.  This is done in elf_fake_sections as well, but forcing
11013          the VMA to 0 here will ensure that relocs against these
11014          sections are handled correctly.  */
11015       if ((o->flags & SEC_ALLOC) == 0
11016           && ! o->user_set_vma)
11017         o->vma = 0;
11018     }
11019
11020   if (! info->relocatable && merged)
11021     elf_link_hash_traverse (elf_hash_table (info),
11022                             _bfd_elf_link_sec_merge_syms, abfd);
11023
11024   /* Figure out the file positions for everything but the symbol table
11025      and the relocs.  We set symcount to force assign_section_numbers
11026      to create a symbol table.  */
11027   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11028   BFD_ASSERT (! abfd->output_has_begun);
11029   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11030     goto error_return;
11031
11032   /* Set sizes, and assign file positions for reloc sections.  */
11033   for (o = abfd->sections; o != NULL; o = o->next)
11034     {
11035       struct bfd_elf_section_data *esdo = elf_section_data (o);
11036       if ((o->flags & SEC_RELOC) != 0)
11037         {
11038           if (esdo->rel.hdr
11039               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11040             goto error_return;
11041
11042           if (esdo->rela.hdr
11043               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11044             goto error_return;
11045         }
11046
11047       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11048          to count upwards while actually outputting the relocations.  */
11049       esdo->rel.count = 0;
11050       esdo->rela.count = 0;
11051
11052       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11053         {
11054           /* Cache the section contents so that they can be compressed
11055              later.  Use bfd_malloc since it will be freed by
11056              bfd_compress_section_contents.  */
11057           unsigned char *contents = esdo->this_hdr.contents;
11058           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11059             abort ();
11060           contents
11061             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11062           if (contents == NULL)
11063             goto error_return;
11064           esdo->this_hdr.contents = contents;
11065         }
11066     }
11067
11068   /* We have now assigned file positions for all the sections except
11069      .symtab, .strtab, and non-loaded reloc sections.  We start the
11070      .symtab section at the current file position, and write directly
11071      to it.  We build the .strtab section in memory.  */
11072   bfd_get_symcount (abfd) = 0;
11073   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11074   /* sh_name is set in prep_headers.  */
11075   symtab_hdr->sh_type = SHT_SYMTAB;
11076   /* sh_flags, sh_addr and sh_size all start off zero.  */
11077   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11078   /* sh_link is set in assign_section_numbers.  */
11079   /* sh_info is set below.  */
11080   /* sh_offset is set just below.  */
11081   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11082
11083   if (max_sym_count < 20)
11084     max_sym_count = 20;
11085   elf_hash_table (info)->strtabsize = max_sym_count;
11086   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11087   elf_hash_table (info)->strtab
11088     = (struct elf_sym_strtab *) bfd_malloc (amt);
11089   if (elf_hash_table (info)->strtab == NULL)
11090     goto error_return;
11091   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11092   flinfo.symshndxbuf
11093     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11094        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11095
11096   if (info->strip != strip_all || emit_relocs)
11097     {
11098       file_ptr off = elf_next_file_pos (abfd);
11099
11100       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11101
11102       /* Note that at this point elf_next_file_pos (abfd) is
11103          incorrect.  We do not yet know the size of the .symtab section.
11104          We correct next_file_pos below, after we do know the size.  */
11105
11106       /* Start writing out the symbol table.  The first symbol is always a
11107          dummy symbol.  */
11108       elfsym.st_value = 0;
11109       elfsym.st_size = 0;
11110       elfsym.st_info = 0;
11111       elfsym.st_other = 0;
11112       elfsym.st_shndx = SHN_UNDEF;
11113       elfsym.st_target_internal = 0;
11114       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11115                                      bfd_und_section_ptr, NULL) != 1)
11116         goto error_return;
11117
11118       /* Output a symbol for each section.  We output these even if we are
11119          discarding local symbols, since they are used for relocs.  These
11120          symbols have no names.  We store the index of each one in the
11121          index field of the section, so that we can find it again when
11122          outputting relocs.  */
11123
11124       elfsym.st_size = 0;
11125       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11126       elfsym.st_other = 0;
11127       elfsym.st_value = 0;
11128       elfsym.st_target_internal = 0;
11129       for (i = 1; i < elf_numsections (abfd); i++)
11130         {
11131           o = bfd_section_from_elf_index (abfd, i);
11132           if (o != NULL)
11133             {
11134               o->target_index = bfd_get_symcount (abfd);
11135               elfsym.st_shndx = i;
11136               if (!info->relocatable)
11137                 elfsym.st_value = o->vma;
11138               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11139                                              NULL) != 1)
11140                 goto error_return;
11141             }
11142         }
11143     }
11144
11145   /* Allocate some memory to hold information read in from the input
11146      files.  */
11147   if (max_contents_size != 0)
11148     {
11149       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11150       if (flinfo.contents == NULL)
11151         goto error_return;
11152     }
11153
11154   if (max_external_reloc_size != 0)
11155     {
11156       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11157       if (flinfo.external_relocs == NULL)
11158         goto error_return;
11159     }
11160
11161   if (max_internal_reloc_count != 0)
11162     {
11163       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11164       amt *= sizeof (Elf_Internal_Rela);
11165       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11166       if (flinfo.internal_relocs == NULL)
11167         goto error_return;
11168     }
11169
11170   if (max_sym_count != 0)
11171     {
11172       amt = max_sym_count * bed->s->sizeof_sym;
11173       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11174       if (flinfo.external_syms == NULL)
11175         goto error_return;
11176
11177       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11178       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11179       if (flinfo.internal_syms == NULL)
11180         goto error_return;
11181
11182       amt = max_sym_count * sizeof (long);
11183       flinfo.indices = (long int *) bfd_malloc (amt);
11184       if (flinfo.indices == NULL)
11185         goto error_return;
11186
11187       amt = max_sym_count * sizeof (asection *);
11188       flinfo.sections = (asection **) bfd_malloc (amt);
11189       if (flinfo.sections == NULL)
11190         goto error_return;
11191     }
11192
11193   if (max_sym_shndx_count != 0)
11194     {
11195       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11196       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11197       if (flinfo.locsym_shndx == NULL)
11198         goto error_return;
11199     }
11200
11201   if (elf_hash_table (info)->tls_sec)
11202     {
11203       bfd_vma base, end = 0;
11204       asection *sec;
11205
11206       for (sec = elf_hash_table (info)->tls_sec;
11207            sec && (sec->flags & SEC_THREAD_LOCAL);
11208            sec = sec->next)
11209         {
11210           bfd_size_type size = sec->size;
11211
11212           if (size == 0
11213               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11214             {
11215               struct bfd_link_order *ord = sec->map_tail.link_order;
11216
11217               if (ord != NULL)
11218                 size = ord->offset + ord->size;
11219             }
11220           end = sec->vma + size;
11221         }
11222       base = elf_hash_table (info)->tls_sec->vma;
11223       /* Only align end of TLS section if static TLS doesn't have special
11224          alignment requirements.  */
11225       if (bed->static_tls_alignment == 1)
11226         end = align_power (end,
11227                            elf_hash_table (info)->tls_sec->alignment_power);
11228       elf_hash_table (info)->tls_size = end - base;
11229     }
11230
11231   /* Reorder SHF_LINK_ORDER sections.  */
11232   for (o = abfd->sections; o != NULL; o = o->next)
11233     {
11234       if (!elf_fixup_link_order (abfd, o))
11235         return FALSE;
11236     }
11237
11238   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11239     return FALSE;
11240
11241   /* Since ELF permits relocations to be against local symbols, we
11242      must have the local symbols available when we do the relocations.
11243      Since we would rather only read the local symbols once, and we
11244      would rather not keep them in memory, we handle all the
11245      relocations for a single input file at the same time.
11246
11247      Unfortunately, there is no way to know the total number of local
11248      symbols until we have seen all of them, and the local symbol
11249      indices precede the global symbol indices.  This means that when
11250      we are generating relocatable output, and we see a reloc against
11251      a global symbol, we can not know the symbol index until we have
11252      finished examining all the local symbols to see which ones we are
11253      going to output.  To deal with this, we keep the relocations in
11254      memory, and don't output them until the end of the link.  This is
11255      an unfortunate waste of memory, but I don't see a good way around
11256      it.  Fortunately, it only happens when performing a relocatable
11257      link, which is not the common case.  FIXME: If keep_memory is set
11258      we could write the relocs out and then read them again; I don't
11259      know how bad the memory loss will be.  */
11260
11261   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11262     sub->output_has_begun = FALSE;
11263   for (o = abfd->sections; o != NULL; o = o->next)
11264     {
11265       for (p = o->map_head.link_order; p != NULL; p = p->next)
11266         {
11267           if (p->type == bfd_indirect_link_order
11268               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11269                   == bfd_target_elf_flavour)
11270               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11271             {
11272               if (! sub->output_has_begun)
11273                 {
11274                   if (! elf_link_input_bfd (&flinfo, sub))
11275                     goto error_return;
11276                   sub->output_has_begun = TRUE;
11277                 }
11278             }
11279           else if (p->type == bfd_section_reloc_link_order
11280                    || p->type == bfd_symbol_reloc_link_order)
11281             {
11282               if (! elf_reloc_link_order (abfd, info, o, p))
11283                 goto error_return;
11284             }
11285           else
11286             {
11287               if (! _bfd_default_link_order (abfd, info, o, p))
11288                 {
11289                   if (p->type == bfd_indirect_link_order
11290                       && (bfd_get_flavour (sub)
11291                           == bfd_target_elf_flavour)
11292                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11293                           != bed->s->elfclass))
11294                     {
11295                       const char *iclass, *oclass;
11296
11297                       if (bed->s->elfclass == ELFCLASS64)
11298                         {
11299                           iclass = "ELFCLASS32";
11300                           oclass = "ELFCLASS64";
11301                         }
11302                       else
11303                         {
11304                           iclass = "ELFCLASS64";
11305                           oclass = "ELFCLASS32";
11306                         }
11307
11308                       bfd_set_error (bfd_error_wrong_format);
11309                       (*_bfd_error_handler)
11310                         (_("%B: file class %s incompatible with %s"),
11311                          sub, iclass, oclass);
11312                     }
11313
11314                   goto error_return;
11315                 }
11316             }
11317         }
11318     }
11319
11320   /* Free symbol buffer if needed.  */
11321   if (!info->reduce_memory_overheads)
11322     {
11323       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11324         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11325             && elf_tdata (sub)->symbuf)
11326           {
11327             free (elf_tdata (sub)->symbuf);
11328             elf_tdata (sub)->symbuf = NULL;
11329           }
11330     }
11331
11332   /* Output any global symbols that got converted to local in a
11333      version script or due to symbol visibility.  We do this in a
11334      separate step since ELF requires all local symbols to appear
11335      prior to any global symbols.  FIXME: We should only do this if
11336      some global symbols were, in fact, converted to become local.
11337      FIXME: Will this work correctly with the Irix 5 linker?  */
11338   eoinfo.failed = FALSE;
11339   eoinfo.flinfo = &flinfo;
11340   eoinfo.localsyms = TRUE;
11341   eoinfo.file_sym_done = FALSE;
11342   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11343   if (eoinfo.failed)
11344     return FALSE;
11345
11346   /* If backend needs to output some local symbols not present in the hash
11347      table, do it now.  */
11348   if (bed->elf_backend_output_arch_local_syms
11349       && (info->strip != strip_all || emit_relocs))
11350     {
11351       typedef int (*out_sym_func)
11352         (void *, const char *, Elf_Internal_Sym *, asection *,
11353          struct elf_link_hash_entry *);
11354
11355       if (! ((*bed->elf_backend_output_arch_local_syms)
11356              (abfd, info, &flinfo,
11357               (out_sym_func) elf_link_output_symstrtab)))
11358         return FALSE;
11359     }
11360
11361   /* That wrote out all the local symbols.  Finish up the symbol table
11362      with the global symbols. Even if we want to strip everything we
11363      can, we still need to deal with those global symbols that got
11364      converted to local in a version script.  */
11365
11366   /* The sh_info field records the index of the first non local symbol.  */
11367   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11368
11369   if (dynamic
11370       && flinfo.dynsym_sec != NULL
11371       && flinfo.dynsym_sec->output_section != bfd_abs_section_ptr)
11372     {
11373       Elf_Internal_Sym sym;
11374       bfd_byte *dynsym = flinfo.dynsym_sec->contents;
11375       long last_local = 0;
11376
11377       /* Write out the section symbols for the output sections.  */
11378       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
11379         {
11380           asection *s;
11381
11382           sym.st_size = 0;
11383           sym.st_name = 0;
11384           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11385           sym.st_other = 0;
11386           sym.st_target_internal = 0;
11387
11388           for (s = abfd->sections; s != NULL; s = s->next)
11389             {
11390               int indx;
11391               bfd_byte *dest;
11392               long dynindx;
11393
11394               dynindx = elf_section_data (s)->dynindx;
11395               if (dynindx <= 0)
11396                 continue;
11397               indx = elf_section_data (s)->this_idx;
11398               BFD_ASSERT (indx > 0);
11399               sym.st_shndx = indx;
11400               if (! check_dynsym (abfd, &sym))
11401                 return FALSE;
11402               sym.st_value = s->vma;
11403               dest = dynsym + dynindx * bed->s->sizeof_sym;
11404               if (last_local < dynindx)
11405                 last_local = dynindx;
11406               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11407             }
11408         }
11409
11410       /* Write out the local dynsyms.  */
11411       if (elf_hash_table (info)->dynlocal)
11412         {
11413           struct elf_link_local_dynamic_entry *e;
11414           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11415             {
11416               asection *s;
11417               bfd_byte *dest;
11418
11419               /* Copy the internal symbol and turn off visibility.
11420                  Note that we saved a word of storage and overwrote
11421                  the original st_name with the dynstr_index.  */
11422               sym = e->isym;
11423               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11424
11425               s = bfd_section_from_elf_index (e->input_bfd,
11426                                               e->isym.st_shndx);
11427               if (s != NULL)
11428                 {
11429                   sym.st_shndx =
11430                     elf_section_data (s->output_section)->this_idx;
11431                   if (! check_dynsym (abfd, &sym))
11432                     return FALSE;
11433                   sym.st_value = (s->output_section->vma
11434                                   + s->output_offset
11435                                   + e->isym.st_value);
11436                 }
11437
11438               if (last_local < e->dynindx)
11439                 last_local = e->dynindx;
11440
11441               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11442               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11443             }
11444         }
11445
11446       elf_section_data (flinfo.dynsym_sec->output_section)->this_hdr.sh_info =
11447         last_local + 1;
11448     }
11449
11450   /* We get the global symbols from the hash table.  */
11451   eoinfo.failed = FALSE;
11452   eoinfo.localsyms = FALSE;
11453   eoinfo.flinfo = &flinfo;
11454   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11455   if (eoinfo.failed)
11456     return FALSE;
11457
11458   /* If backend needs to output some symbols not present in the hash
11459      table, do it now.  */
11460   if (bed->elf_backend_output_arch_syms
11461       && (info->strip != strip_all || emit_relocs))
11462     {
11463       typedef int (*out_sym_func)
11464         (void *, const char *, Elf_Internal_Sym *, asection *,
11465          struct elf_link_hash_entry *);
11466
11467       if (! ((*bed->elf_backend_output_arch_syms)
11468              (abfd, info, &flinfo,
11469               (out_sym_func) elf_link_output_symstrtab)))
11470         return FALSE;
11471     }
11472
11473   /* Finalize the .strtab section.  */
11474   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11475
11476   /* Swap out the .strtab section. */
11477   if (!elf_link_swap_symbols_out (&flinfo))
11478     return FALSE;
11479
11480   /* Now we know the size of the symtab section.  */
11481   if (bfd_get_symcount (abfd) > 0)
11482     {
11483       /* Finish up and write out the symbol string table (.strtab)
11484          section.  */
11485       Elf_Internal_Shdr *symstrtab_hdr;
11486       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11487
11488       symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
11489       if (symtab_shndx_hdr->sh_name != 0)
11490         {
11491           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11492           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11493           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11494           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11495           symtab_shndx_hdr->sh_size = amt;
11496
11497           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11498                                                            off, TRUE);
11499
11500           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11501               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11502             return FALSE;
11503         }
11504
11505       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11506       /* sh_name was set in prep_headers.  */
11507       symstrtab_hdr->sh_type = SHT_STRTAB;
11508       symstrtab_hdr->sh_flags = 0;
11509       symstrtab_hdr->sh_addr = 0;
11510       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11511       symstrtab_hdr->sh_entsize = 0;
11512       symstrtab_hdr->sh_link = 0;
11513       symstrtab_hdr->sh_info = 0;
11514       /* sh_offset is set just below.  */
11515       symstrtab_hdr->sh_addralign = 1;
11516
11517       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11518                                                        off, TRUE);
11519       elf_next_file_pos (abfd) = off;
11520
11521       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11522           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11523         return FALSE;
11524     }
11525
11526   /* Adjust the relocs to have the correct symbol indices.  */
11527   for (o = abfd->sections; o != NULL; o = o->next)
11528     {
11529       struct bfd_elf_section_data *esdo = elf_section_data (o);
11530       bfd_boolean sort;
11531       if ((o->flags & SEC_RELOC) == 0)
11532         continue;
11533
11534       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11535       if (esdo->rel.hdr != NULL)
11536         elf_link_adjust_relocs (abfd, &esdo->rel, sort);
11537       if (esdo->rela.hdr != NULL)
11538         elf_link_adjust_relocs (abfd, &esdo->rela, sort);
11539
11540       /* Set the reloc_count field to 0 to prevent write_relocs from
11541          trying to swap the relocs out itself.  */
11542       o->reloc_count = 0;
11543     }
11544
11545   if (dynamic && info->combreloc && dynobj != NULL)
11546     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11547
11548   /* If we are linking against a dynamic object, or generating a
11549      shared library, finish up the dynamic linking information.  */
11550   if (dynamic)
11551     {
11552       bfd_byte *dyncon, *dynconend;
11553
11554       /* Fix up .dynamic entries.  */
11555       o = bfd_get_linker_section (dynobj, ".dynamic");
11556       BFD_ASSERT (o != NULL);
11557
11558       dyncon = o->contents;
11559       dynconend = o->contents + o->size;
11560       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11561         {
11562           Elf_Internal_Dyn dyn;
11563           const char *name;
11564           unsigned int type;
11565
11566           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11567
11568           switch (dyn.d_tag)
11569             {
11570             default:
11571               continue;
11572             case DT_NULL:
11573               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11574                 {
11575                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11576                     {
11577                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11578                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11579                     default: continue;
11580                     }
11581                   dyn.d_un.d_val = relativecount;
11582                   relativecount = 0;
11583                   break;
11584                 }
11585               continue;
11586
11587             case DT_INIT:
11588               name = info->init_function;
11589               goto get_sym;
11590             case DT_FINI:
11591               name = info->fini_function;
11592             get_sym:
11593               {
11594                 struct elf_link_hash_entry *h;
11595
11596                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11597                                           FALSE, FALSE, TRUE);
11598                 if (h != NULL
11599                     && (h->root.type == bfd_link_hash_defined
11600                         || h->root.type == bfd_link_hash_defweak))
11601                   {
11602                     dyn.d_un.d_ptr = h->root.u.def.value;
11603                     o = h->root.u.def.section;
11604                     if (o->output_section != NULL)
11605                       dyn.d_un.d_ptr += (o->output_section->vma
11606                                          + o->output_offset);
11607                     else
11608                       {
11609                         /* The symbol is imported from another shared
11610                            library and does not apply to this one.  */
11611                         dyn.d_un.d_ptr = 0;
11612                       }
11613                     break;
11614                   }
11615               }
11616               continue;
11617
11618             case DT_PREINIT_ARRAYSZ:
11619               name = ".preinit_array";
11620               goto get_size;
11621             case DT_INIT_ARRAYSZ:
11622               name = ".init_array";
11623               goto get_size;
11624             case DT_FINI_ARRAYSZ:
11625               name = ".fini_array";
11626             get_size:
11627               o = bfd_get_section_by_name (abfd, name);
11628               if (o == NULL)
11629                 {
11630                   (*_bfd_error_handler)
11631                     (_("%B: could not find output section %s"), abfd, name);
11632                   goto error_return;
11633                 }
11634               if (o->size == 0)
11635                 (*_bfd_error_handler)
11636                   (_("warning: %s section has zero size"), name);
11637               dyn.d_un.d_val = o->size;
11638               break;
11639
11640             case DT_PREINIT_ARRAY:
11641               name = ".preinit_array";
11642               goto get_vma;
11643             case DT_INIT_ARRAY:
11644               name = ".init_array";
11645               goto get_vma;
11646             case DT_FINI_ARRAY:
11647               name = ".fini_array";
11648               goto get_vma;
11649
11650             case DT_HASH:
11651               name = ".hash";
11652               goto get_vma;
11653             case DT_GNU_HASH:
11654               name = ".gnu.hash";
11655               goto get_vma;
11656             case DT_STRTAB:
11657               name = ".dynstr";
11658               goto get_vma;
11659             case DT_SYMTAB:
11660               name = ".dynsym";
11661               goto get_vma;
11662             case DT_VERDEF:
11663               name = ".gnu.version_d";
11664               goto get_vma;
11665             case DT_VERNEED:
11666               name = ".gnu.version_r";
11667               goto get_vma;
11668             case DT_VERSYM:
11669               name = ".gnu.version";
11670             get_vma:
11671               o = bfd_get_section_by_name (abfd, name);
11672               if (o == NULL)
11673                 {
11674                   (*_bfd_error_handler)
11675                     (_("%B: could not find output section %s"), abfd, name);
11676                   goto error_return;
11677                 }
11678               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11679                 {
11680                   (*_bfd_error_handler)
11681                     (_("warning: section '%s' is being made into a note"), name);
11682                   bfd_set_error (bfd_error_nonrepresentable_section);
11683                   goto error_return;
11684                 }
11685               dyn.d_un.d_ptr = o->vma;
11686               break;
11687
11688             case DT_REL:
11689             case DT_RELA:
11690             case DT_RELSZ:
11691             case DT_RELASZ:
11692               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11693                 type = SHT_REL;
11694               else
11695                 type = SHT_RELA;
11696               dyn.d_un.d_val = 0;
11697               dyn.d_un.d_ptr = 0;
11698               for (i = 1; i < elf_numsections (abfd); i++)
11699                 {
11700                   Elf_Internal_Shdr *hdr;
11701
11702                   hdr = elf_elfsections (abfd)[i];
11703                   if (hdr->sh_type == type
11704                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11705                     {
11706                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11707                         dyn.d_un.d_val += hdr->sh_size;
11708                       else
11709                         {
11710                           if (dyn.d_un.d_ptr == 0
11711                               || hdr->sh_addr < dyn.d_un.d_ptr)
11712                             dyn.d_un.d_ptr = hdr->sh_addr;
11713                         }
11714                     }
11715                 }
11716               break;
11717             }
11718           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11719         }
11720     }
11721
11722   /* If we have created any dynamic sections, then output them.  */
11723   if (dynobj != NULL)
11724     {
11725       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11726         goto error_return;
11727
11728       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11729       if (((info->warn_shared_textrel && info->shared)
11730            || info->error_textrel)
11731           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11732         {
11733           bfd_byte *dyncon, *dynconend;
11734
11735           dyncon = o->contents;
11736           dynconend = o->contents + o->size;
11737           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11738             {
11739               Elf_Internal_Dyn dyn;
11740
11741               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11742
11743               if (dyn.d_tag == DT_TEXTREL)
11744                 {
11745                   if (info->error_textrel)
11746                     info->callbacks->einfo
11747                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11748                   else
11749                     info->callbacks->einfo
11750                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11751                   break;
11752                 }
11753             }
11754         }
11755
11756       for (o = dynobj->sections; o != NULL; o = o->next)
11757         {
11758           if ((o->flags & SEC_HAS_CONTENTS) == 0
11759               || o->size == 0
11760               || o->output_section == bfd_abs_section_ptr)
11761             continue;
11762           if ((o->flags & SEC_LINKER_CREATED) == 0)
11763             {
11764               /* At this point, we are only interested in sections
11765                  created by _bfd_elf_link_create_dynamic_sections.  */
11766               continue;
11767             }
11768           if (elf_hash_table (info)->stab_info.stabstr == o)
11769             continue;
11770           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11771             continue;
11772           if (strcmp (o->name, ".dynstr") != 0)
11773             {
11774               /* FIXME: octets_per_byte.  */
11775               if (! bfd_set_section_contents (abfd, o->output_section,
11776                                               o->contents,
11777                                               (file_ptr) o->output_offset,
11778                                               o->size))
11779                 goto error_return;
11780             }
11781           else
11782             {
11783               /* The contents of the .dynstr section are actually in a
11784                  stringtab.  */
11785               file_ptr off;
11786
11787               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11788               if (bfd_seek (abfd, off, SEEK_SET) != 0
11789                   || ! _bfd_elf_strtab_emit (abfd,
11790                                              elf_hash_table (info)->dynstr))
11791                 goto error_return;
11792             }
11793         }
11794     }
11795
11796   if (info->relocatable)
11797     {
11798       bfd_boolean failed = FALSE;
11799
11800       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11801       if (failed)
11802         goto error_return;
11803     }
11804
11805   /* If we have optimized stabs strings, output them.  */
11806   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11807     {
11808       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11809         goto error_return;
11810     }
11811
11812   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11813     goto error_return;
11814
11815   elf_final_link_free (abfd, &flinfo);
11816
11817   elf_linker (abfd) = TRUE;
11818
11819   if (attr_section)
11820     {
11821       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11822       if (contents == NULL)
11823         return FALSE;   /* Bail out and fail.  */
11824       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11825       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11826       free (contents);
11827     }
11828
11829   return TRUE;
11830
11831  error_return:
11832   elf_final_link_free (abfd, &flinfo);
11833   return FALSE;
11834 }
11835 \f
11836 /* Initialize COOKIE for input bfd ABFD.  */
11837
11838 static bfd_boolean
11839 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11840                    struct bfd_link_info *info, bfd *abfd)
11841 {
11842   Elf_Internal_Shdr *symtab_hdr;
11843   const struct elf_backend_data *bed;
11844
11845   bed = get_elf_backend_data (abfd);
11846   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11847
11848   cookie->abfd = abfd;
11849   cookie->sym_hashes = elf_sym_hashes (abfd);
11850   cookie->bad_symtab = elf_bad_symtab (abfd);
11851   if (cookie->bad_symtab)
11852     {
11853       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11854       cookie->extsymoff = 0;
11855     }
11856   else
11857     {
11858       cookie->locsymcount = symtab_hdr->sh_info;
11859       cookie->extsymoff = symtab_hdr->sh_info;
11860     }
11861
11862   if (bed->s->arch_size == 32)
11863     cookie->r_sym_shift = 8;
11864   else
11865     cookie->r_sym_shift = 32;
11866
11867   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11868   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11869     {
11870       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11871                                               cookie->locsymcount, 0,
11872                                               NULL, NULL, NULL);
11873       if (cookie->locsyms == NULL)
11874         {
11875           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11876           return FALSE;
11877         }
11878       if (info->keep_memory)
11879         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11880     }
11881   return TRUE;
11882 }
11883
11884 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11885
11886 static void
11887 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11888 {
11889   Elf_Internal_Shdr *symtab_hdr;
11890
11891   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11892   if (cookie->locsyms != NULL
11893       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11894     free (cookie->locsyms);
11895 }
11896
11897 /* Initialize the relocation information in COOKIE for input section SEC
11898    of input bfd ABFD.  */
11899
11900 static bfd_boolean
11901 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11902                         struct bfd_link_info *info, bfd *abfd,
11903                         asection *sec)
11904 {
11905   const struct elf_backend_data *bed;
11906
11907   if (sec->reloc_count == 0)
11908     {
11909       cookie->rels = NULL;
11910       cookie->relend = NULL;
11911     }
11912   else
11913     {
11914       bed = get_elf_backend_data (abfd);
11915
11916       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11917                                                 info->keep_memory);
11918       if (cookie->rels == NULL)
11919         return FALSE;
11920       cookie->rel = cookie->rels;
11921       cookie->relend = (cookie->rels
11922                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11923     }
11924   cookie->rel = cookie->rels;
11925   return TRUE;
11926 }
11927
11928 /* Free the memory allocated by init_reloc_cookie_rels,
11929    if appropriate.  */
11930
11931 static void
11932 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11933                         asection *sec)
11934 {
11935   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11936     free (cookie->rels);
11937 }
11938
11939 /* Initialize the whole of COOKIE for input section SEC.  */
11940
11941 static bfd_boolean
11942 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11943                                struct bfd_link_info *info,
11944                                asection *sec)
11945 {
11946   if (!init_reloc_cookie (cookie, info, sec->owner))
11947     goto error1;
11948   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11949     goto error2;
11950   return TRUE;
11951
11952  error2:
11953   fini_reloc_cookie (cookie, sec->owner);
11954  error1:
11955   return FALSE;
11956 }
11957
11958 /* Free the memory allocated by init_reloc_cookie_for_section,
11959    if appropriate.  */
11960
11961 static void
11962 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11963                                asection *sec)
11964 {
11965   fini_reloc_cookie_rels (cookie, sec);
11966   fini_reloc_cookie (cookie, sec->owner);
11967 }
11968 \f
11969 /* Garbage collect unused sections.  */
11970
11971 /* Default gc_mark_hook.  */
11972
11973 asection *
11974 _bfd_elf_gc_mark_hook (asection *sec,
11975                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
11976                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
11977                        struct elf_link_hash_entry *h,
11978                        Elf_Internal_Sym *sym)
11979 {
11980   const char *sec_name;
11981
11982   if (h != NULL)
11983     {
11984       switch (h->root.type)
11985         {
11986         case bfd_link_hash_defined:
11987         case bfd_link_hash_defweak:
11988           return h->root.u.def.section;
11989
11990         case bfd_link_hash_common:
11991           return h->root.u.c.p->section;
11992
11993         case bfd_link_hash_undefined:
11994         case bfd_link_hash_undefweak:
11995           /* To work around a glibc bug, keep all XXX input sections
11996              when there is an as yet undefined reference to __start_XXX
11997              or __stop_XXX symbols.  The linker will later define such
11998              symbols for orphan input sections that have a name
11999              representable as a C identifier.  */
12000           if (strncmp (h->root.root.string, "__start_", 8) == 0)
12001             sec_name = h->root.root.string + 8;
12002           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12003             sec_name = h->root.root.string + 7;
12004           else
12005             sec_name = NULL;
12006
12007           if (sec_name && *sec_name != '\0')
12008             {
12009               bfd *i;
12010
12011               for (i = info->input_bfds; i; i = i->link.next)
12012                 {
12013                   sec = bfd_get_section_by_name (i, sec_name);
12014                   if (sec)
12015                     sec->flags |= SEC_KEEP;
12016                 }
12017             }
12018           break;
12019
12020         default:
12021           break;
12022         }
12023     }
12024   else
12025     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12026
12027   return NULL;
12028 }
12029
12030 /* COOKIE->rel describes a relocation against section SEC, which is
12031    a section we've decided to keep.  Return the section that contains
12032    the relocation symbol, or NULL if no section contains it.  */
12033
12034 asection *
12035 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12036                        elf_gc_mark_hook_fn gc_mark_hook,
12037                        struct elf_reloc_cookie *cookie)
12038 {
12039   unsigned long r_symndx;
12040   struct elf_link_hash_entry *h;
12041
12042   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12043   if (r_symndx == STN_UNDEF)
12044     return NULL;
12045
12046   if (r_symndx >= cookie->locsymcount
12047       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12048     {
12049       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12050       if (h == NULL)
12051         {
12052           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12053                                   sec->owner);
12054           return NULL;
12055         }
12056       while (h->root.type == bfd_link_hash_indirect
12057              || h->root.type == bfd_link_hash_warning)
12058         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12059       h->mark = 1;
12060       /* If this symbol is weak and there is a non-weak definition, we
12061          keep the non-weak definition because many backends put
12062          dynamic reloc info on the non-weak definition for code
12063          handling copy relocs.  */
12064       if (h->u.weakdef != NULL)
12065         h->u.weakdef->mark = 1;
12066       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12067     }
12068
12069   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12070                           &cookie->locsyms[r_symndx]);
12071 }
12072
12073 /* COOKIE->rel describes a relocation against section SEC, which is
12074    a section we've decided to keep.  Mark the section that contains
12075    the relocation symbol.  */
12076
12077 bfd_boolean
12078 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12079                         asection *sec,
12080                         elf_gc_mark_hook_fn gc_mark_hook,
12081                         struct elf_reloc_cookie *cookie)
12082 {
12083   asection *rsec;
12084
12085   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
12086   if (rsec && !rsec->gc_mark)
12087     {
12088       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12089           || (rsec->owner->flags & DYNAMIC) != 0)
12090         rsec->gc_mark = 1;
12091       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12092         return FALSE;
12093     }
12094   return TRUE;
12095 }
12096
12097 /* The mark phase of garbage collection.  For a given section, mark
12098    it and any sections in this section's group, and all the sections
12099    which define symbols to which it refers.  */
12100
12101 bfd_boolean
12102 _bfd_elf_gc_mark (struct bfd_link_info *info,
12103                   asection *sec,
12104                   elf_gc_mark_hook_fn gc_mark_hook)
12105 {
12106   bfd_boolean ret;
12107   asection *group_sec, *eh_frame;
12108
12109   sec->gc_mark = 1;
12110
12111   /* Mark all the sections in the group.  */
12112   group_sec = elf_section_data (sec)->next_in_group;
12113   if (group_sec && !group_sec->gc_mark)
12114     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12115       return FALSE;
12116
12117   /* Look through the section relocs.  */
12118   ret = TRUE;
12119   eh_frame = elf_eh_frame_section (sec->owner);
12120   if ((sec->flags & SEC_RELOC) != 0
12121       && sec->reloc_count > 0
12122       && sec != eh_frame)
12123     {
12124       struct elf_reloc_cookie cookie;
12125
12126       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12127         ret = FALSE;
12128       else
12129         {
12130           for (; cookie.rel < cookie.relend; cookie.rel++)
12131             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12132               {
12133                 ret = FALSE;
12134                 break;
12135               }
12136           fini_reloc_cookie_for_section (&cookie, sec);
12137         }
12138     }
12139
12140   if (ret && eh_frame && elf_fde_list (sec))
12141     {
12142       struct elf_reloc_cookie cookie;
12143
12144       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12145         ret = FALSE;
12146       else
12147         {
12148           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12149                                       gc_mark_hook, &cookie))
12150             ret = FALSE;
12151           fini_reloc_cookie_for_section (&cookie, eh_frame);
12152         }
12153     }
12154
12155   eh_frame = elf_section_eh_frame_entry (sec);
12156   if (ret && eh_frame && !eh_frame->gc_mark)
12157     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12158       ret = FALSE;
12159
12160   return ret;
12161 }
12162
12163 /* Scan and mark sections in a special or debug section group.  */
12164
12165 static void
12166 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12167 {
12168   /* Point to first section of section group.  */
12169   asection *ssec;
12170   /* Used to iterate the section group.  */
12171   asection *msec;
12172
12173   bfd_boolean is_special_grp = TRUE;
12174   bfd_boolean is_debug_grp = TRUE;
12175
12176   /* First scan to see if group contains any section other than debug
12177      and special section.  */
12178   ssec = msec = elf_next_in_group (grp);
12179   do
12180     {
12181       if ((msec->flags & SEC_DEBUGGING) == 0)
12182         is_debug_grp = FALSE;
12183
12184       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12185         is_special_grp = FALSE;
12186
12187       msec = elf_next_in_group (msec);
12188     }
12189   while (msec != ssec);
12190
12191   /* If this is a pure debug section group or pure special section group,
12192      keep all sections in this group.  */
12193   if (is_debug_grp || is_special_grp)
12194     {
12195       do
12196         {
12197           msec->gc_mark = 1;
12198           msec = elf_next_in_group (msec);
12199         }
12200       while (msec != ssec);
12201     }
12202 }
12203
12204 /* Keep debug and special sections.  */
12205
12206 bfd_boolean
12207 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12208                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12209 {
12210   bfd *ibfd;
12211
12212   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12213     {
12214       asection *isec;
12215       bfd_boolean some_kept;
12216       bfd_boolean debug_frag_seen;
12217
12218       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12219         continue;
12220
12221       /* Ensure all linker created sections are kept,
12222          see if any other section is already marked,
12223          and note if we have any fragmented debug sections.  */
12224       debug_frag_seen = some_kept = FALSE;
12225       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12226         {
12227           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12228             isec->gc_mark = 1;
12229           else if (isec->gc_mark)
12230             some_kept = TRUE;
12231
12232           if (debug_frag_seen == FALSE
12233               && (isec->flags & SEC_DEBUGGING)
12234               && CONST_STRNEQ (isec->name, ".debug_line."))
12235             debug_frag_seen = TRUE;
12236         }
12237
12238       /* If no section in this file will be kept, then we can
12239          toss out the debug and special sections.  */
12240       if (!some_kept)
12241         continue;
12242
12243       /* Keep debug and special sections like .comment when they are
12244          not part of a group.  Also keep section groups that contain
12245          just debug sections or special sections.  */
12246       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12247         {
12248           if ((isec->flags & SEC_GROUP) != 0)
12249             _bfd_elf_gc_mark_debug_special_section_group (isec);
12250           else if (((isec->flags & SEC_DEBUGGING) != 0
12251                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12252                    && elf_next_in_group (isec) == NULL)
12253             isec->gc_mark = 1;
12254         }
12255
12256       if (! debug_frag_seen)
12257         continue;
12258
12259       /* Look for CODE sections which are going to be discarded,
12260          and find and discard any fragmented debug sections which
12261          are associated with that code section.  */
12262       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12263         if ((isec->flags & SEC_CODE) != 0
12264             && isec->gc_mark == 0)
12265           {
12266             unsigned int ilen;
12267             asection *dsec;
12268
12269             ilen = strlen (isec->name);
12270
12271             /* Association is determined by the name of the debug section
12272                containing the name of the code section as a suffix.  For
12273                example .debug_line.text.foo is a debug section associated
12274                with .text.foo.  */
12275             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12276               {
12277                 unsigned int dlen;
12278
12279                 if (dsec->gc_mark == 0
12280                     || (dsec->flags & SEC_DEBUGGING) == 0)
12281                   continue;
12282
12283                 dlen = strlen (dsec->name);
12284
12285                 if (dlen > ilen
12286                     && strncmp (dsec->name + (dlen - ilen),
12287                                 isec->name, ilen) == 0)
12288                   {
12289                     dsec->gc_mark = 0;
12290                   }
12291               }
12292           }
12293     }
12294   return TRUE;
12295 }
12296
12297 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12298
12299 struct elf_gc_sweep_symbol_info
12300 {
12301   struct bfd_link_info *info;
12302   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12303                        bfd_boolean);
12304 };
12305
12306 static bfd_boolean
12307 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12308 {
12309   if (!h->mark
12310       && (((h->root.type == bfd_link_hash_defined
12311             || h->root.type == bfd_link_hash_defweak)
12312            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12313                 && h->root.u.def.section->gc_mark))
12314           || h->root.type == bfd_link_hash_undefined
12315           || h->root.type == bfd_link_hash_undefweak))
12316     {
12317       struct elf_gc_sweep_symbol_info *inf;
12318
12319       inf = (struct elf_gc_sweep_symbol_info *) data;
12320       (*inf->hide_symbol) (inf->info, h, TRUE);
12321       h->def_regular = 0;
12322       h->ref_regular = 0;
12323       h->ref_regular_nonweak = 0;
12324     }
12325
12326   return TRUE;
12327 }
12328
12329 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12330
12331 typedef bfd_boolean (*gc_sweep_hook_fn)
12332   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12333
12334 static bfd_boolean
12335 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12336 {
12337   bfd *sub;
12338   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12339   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12340   unsigned long section_sym_count;
12341   struct elf_gc_sweep_symbol_info sweep_info;
12342
12343   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12344     {
12345       asection *o;
12346
12347       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12348           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12349         continue;
12350
12351       for (o = sub->sections; o != NULL; o = o->next)
12352         {
12353           /* When any section in a section group is kept, we keep all
12354              sections in the section group.  If the first member of
12355              the section group is excluded, we will also exclude the
12356              group section.  */
12357           if (o->flags & SEC_GROUP)
12358             {
12359               asection *first = elf_next_in_group (o);
12360               o->gc_mark = first->gc_mark;
12361             }
12362
12363           if (o->gc_mark)
12364             continue;
12365
12366           /* Skip sweeping sections already excluded.  */
12367           if (o->flags & SEC_EXCLUDE)
12368             continue;
12369
12370           /* Since this is early in the link process, it is simple
12371              to remove a section from the output.  */
12372           o->flags |= SEC_EXCLUDE;
12373
12374           if (info->print_gc_sections && o->size != 0)
12375             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12376
12377           /* But we also have to update some of the relocation
12378              info we collected before.  */
12379           if (gc_sweep_hook
12380               && (o->flags & SEC_RELOC) != 0
12381               && o->reloc_count != 0
12382               && !((info->strip == strip_all || info->strip == strip_debugger)
12383                    && (o->flags & SEC_DEBUGGING) != 0)
12384               && !bfd_is_abs_section (o->output_section))
12385             {
12386               Elf_Internal_Rela *internal_relocs;
12387               bfd_boolean r;
12388
12389               internal_relocs
12390                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12391                                              info->keep_memory);
12392               if (internal_relocs == NULL)
12393                 return FALSE;
12394
12395               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12396
12397               if (elf_section_data (o)->relocs != internal_relocs)
12398                 free (internal_relocs);
12399
12400               if (!r)
12401                 return FALSE;
12402             }
12403         }
12404     }
12405
12406   /* Remove the symbols that were in the swept sections from the dynamic
12407      symbol table.  GCFIXME: Anyone know how to get them out of the
12408      static symbol table as well?  */
12409   sweep_info.info = info;
12410   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12411   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12412                           &sweep_info);
12413
12414   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12415   return TRUE;
12416 }
12417
12418 /* Propagate collected vtable information.  This is called through
12419    elf_link_hash_traverse.  */
12420
12421 static bfd_boolean
12422 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12423 {
12424   /* Those that are not vtables.  */
12425   if (h->vtable == NULL || h->vtable->parent == NULL)
12426     return TRUE;
12427
12428   /* Those vtables that do not have parents, we cannot merge.  */
12429   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12430     return TRUE;
12431
12432   /* If we've already been done, exit.  */
12433   if (h->vtable->used && h->vtable->used[-1])
12434     return TRUE;
12435
12436   /* Make sure the parent's table is up to date.  */
12437   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12438
12439   if (h->vtable->used == NULL)
12440     {
12441       /* None of this table's entries were referenced.  Re-use the
12442          parent's table.  */
12443       h->vtable->used = h->vtable->parent->vtable->used;
12444       h->vtable->size = h->vtable->parent->vtable->size;
12445     }
12446   else
12447     {
12448       size_t n;
12449       bfd_boolean *cu, *pu;
12450
12451       /* Or the parent's entries into ours.  */
12452       cu = h->vtable->used;
12453       cu[-1] = TRUE;
12454       pu = h->vtable->parent->vtable->used;
12455       if (pu != NULL)
12456         {
12457           const struct elf_backend_data *bed;
12458           unsigned int log_file_align;
12459
12460           bed = get_elf_backend_data (h->root.u.def.section->owner);
12461           log_file_align = bed->s->log_file_align;
12462           n = h->vtable->parent->vtable->size >> log_file_align;
12463           while (n--)
12464             {
12465               if (*pu)
12466                 *cu = TRUE;
12467               pu++;
12468               cu++;
12469             }
12470         }
12471     }
12472
12473   return TRUE;
12474 }
12475
12476 static bfd_boolean
12477 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12478 {
12479   asection *sec;
12480   bfd_vma hstart, hend;
12481   Elf_Internal_Rela *relstart, *relend, *rel;
12482   const struct elf_backend_data *bed;
12483   unsigned int log_file_align;
12484
12485   /* Take care of both those symbols that do not describe vtables as
12486      well as those that are not loaded.  */
12487   if (h->vtable == NULL || h->vtable->parent == NULL)
12488     return TRUE;
12489
12490   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12491               || h->root.type == bfd_link_hash_defweak);
12492
12493   sec = h->root.u.def.section;
12494   hstart = h->root.u.def.value;
12495   hend = hstart + h->size;
12496
12497   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12498   if (!relstart)
12499     return *(bfd_boolean *) okp = FALSE;
12500   bed = get_elf_backend_data (sec->owner);
12501   log_file_align = bed->s->log_file_align;
12502
12503   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12504
12505   for (rel = relstart; rel < relend; ++rel)
12506     if (rel->r_offset >= hstart && rel->r_offset < hend)
12507       {
12508         /* If the entry is in use, do nothing.  */
12509         if (h->vtable->used
12510             && (rel->r_offset - hstart) < h->vtable->size)
12511           {
12512             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12513             if (h->vtable->used[entry])
12514               continue;
12515           }
12516         /* Otherwise, kill it.  */
12517         rel->r_offset = rel->r_info = rel->r_addend = 0;
12518       }
12519
12520   return TRUE;
12521 }
12522
12523 /* Mark sections containing dynamically referenced symbols.  When
12524    building shared libraries, we must assume that any visible symbol is
12525    referenced.  */
12526
12527 bfd_boolean
12528 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12529 {
12530   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12531   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12532
12533   if ((h->root.type == bfd_link_hash_defined
12534        || h->root.type == bfd_link_hash_defweak)
12535       && (h->ref_dynamic
12536           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12537               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12538               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12539               && (!info->executable
12540                   || info->export_dynamic
12541                   || (h->dynamic
12542                       && d != NULL
12543                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12544               && (strchr (h->root.root.string, ELF_VER_CHR) != NULL
12545                   || !bfd_hide_sym_by_version (info->version_info,
12546                                                h->root.root.string)))))
12547     h->root.u.def.section->flags |= SEC_KEEP;
12548
12549   return TRUE;
12550 }
12551
12552 /* Keep all sections containing symbols undefined on the command-line,
12553    and the section containing the entry symbol.  */
12554
12555 void
12556 _bfd_elf_gc_keep (struct bfd_link_info *info)
12557 {
12558   struct bfd_sym_chain *sym;
12559
12560   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12561     {
12562       struct elf_link_hash_entry *h;
12563
12564       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12565                                 FALSE, FALSE, FALSE);
12566
12567       if (h != NULL
12568           && (h->root.type == bfd_link_hash_defined
12569               || h->root.type == bfd_link_hash_defweak)
12570           && !bfd_is_abs_section (h->root.u.def.section))
12571         h->root.u.def.section->flags |= SEC_KEEP;
12572     }
12573 }
12574
12575 bfd_boolean
12576 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
12577                                 struct bfd_link_info *info)
12578 {
12579   bfd *ibfd = info->input_bfds;
12580
12581   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12582     {
12583       asection *sec;
12584       struct elf_reloc_cookie cookie;
12585
12586       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12587         continue;
12588
12589       if (!init_reloc_cookie (&cookie, info, ibfd))
12590         return FALSE;
12591
12592       for (sec = ibfd->sections; sec; sec = sec->next)
12593         {
12594           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
12595               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
12596             {
12597               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
12598               fini_reloc_cookie_rels (&cookie, sec);
12599             }
12600         }
12601     }
12602   return TRUE;
12603 }
12604
12605 /* Do mark and sweep of unused sections.  */
12606
12607 bfd_boolean
12608 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12609 {
12610   bfd_boolean ok = TRUE;
12611   bfd *sub;
12612   elf_gc_mark_hook_fn gc_mark_hook;
12613   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12614   struct elf_link_hash_table *htab;
12615
12616   if (!bed->can_gc_sections
12617       || !is_elf_hash_table (info->hash))
12618     {
12619       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12620       return TRUE;
12621     }
12622
12623   bed->gc_keep (info);
12624   htab = elf_hash_table (info);
12625
12626   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12627      at the .eh_frame section if we can mark the FDEs individually.  */
12628   for (sub = info->input_bfds;
12629        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
12630        sub = sub->link.next)
12631     {
12632       asection *sec;
12633       struct elf_reloc_cookie cookie;
12634
12635       sec = bfd_get_section_by_name (sub, ".eh_frame");
12636       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12637         {
12638           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12639           if (elf_section_data (sec)->sec_info
12640               && (sec->flags & SEC_LINKER_CREATED) == 0)
12641             elf_eh_frame_section (sub) = sec;
12642           fini_reloc_cookie_for_section (&cookie, sec);
12643           sec = bfd_get_next_section_by_name (sec);
12644         }
12645     }
12646
12647   /* Apply transitive closure to the vtable entry usage info.  */
12648   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12649   if (!ok)
12650     return FALSE;
12651
12652   /* Kill the vtable relocations that were not used.  */
12653   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12654   if (!ok)
12655     return FALSE;
12656
12657   /* Mark dynamically referenced symbols.  */
12658   if (htab->dynamic_sections_created)
12659     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12660
12661   /* Grovel through relocs to find out who stays ...  */
12662   gc_mark_hook = bed->gc_mark_hook;
12663   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12664     {
12665       asection *o;
12666
12667       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12668           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12669         continue;
12670
12671       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12672          Also treat note sections as a root, if the section is not part
12673          of a group.  */
12674       for (o = sub->sections; o != NULL; o = o->next)
12675         if (!o->gc_mark
12676             && (o->flags & SEC_EXCLUDE) == 0
12677             && ((o->flags & SEC_KEEP) != 0
12678                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12679                     && elf_next_in_group (o) == NULL )))
12680           {
12681             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12682               return FALSE;
12683           }
12684     }
12685
12686   /* Allow the backend to mark additional target specific sections.  */
12687   bed->gc_mark_extra_sections (info, gc_mark_hook);
12688
12689   /* ... and mark SEC_EXCLUDE for those that go.  */
12690   return elf_gc_sweep (abfd, info);
12691 }
12692 \f
12693 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12694
12695 bfd_boolean
12696 bfd_elf_gc_record_vtinherit (bfd *abfd,
12697                              asection *sec,
12698                              struct elf_link_hash_entry *h,
12699                              bfd_vma offset)
12700 {
12701   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12702   struct elf_link_hash_entry **search, *child;
12703   bfd_size_type extsymcount;
12704   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12705
12706   /* The sh_info field of the symtab header tells us where the
12707      external symbols start.  We don't care about the local symbols at
12708      this point.  */
12709   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12710   if (!elf_bad_symtab (abfd))
12711     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12712
12713   sym_hashes = elf_sym_hashes (abfd);
12714   sym_hashes_end = sym_hashes + extsymcount;
12715
12716   /* Hunt down the child symbol, which is in this section at the same
12717      offset as the relocation.  */
12718   for (search = sym_hashes; search != sym_hashes_end; ++search)
12719     {
12720       if ((child = *search) != NULL
12721           && (child->root.type == bfd_link_hash_defined
12722               || child->root.type == bfd_link_hash_defweak)
12723           && child->root.u.def.section == sec
12724           && child->root.u.def.value == offset)
12725         goto win;
12726     }
12727
12728   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12729                          abfd, sec, (unsigned long) offset);
12730   bfd_set_error (bfd_error_invalid_operation);
12731   return FALSE;
12732
12733  win:
12734   if (!child->vtable)
12735     {
12736       child->vtable = ((struct elf_link_virtual_table_entry *)
12737                        bfd_zalloc (abfd, sizeof (*child->vtable)));
12738       if (!child->vtable)
12739         return FALSE;
12740     }
12741   if (!h)
12742     {
12743       /* This *should* only be the absolute section.  It could potentially
12744          be that someone has defined a non-global vtable though, which
12745          would be bad.  It isn't worth paging in the local symbols to be
12746          sure though; that case should simply be handled by the assembler.  */
12747
12748       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12749     }
12750   else
12751     child->vtable->parent = h;
12752
12753   return TRUE;
12754 }
12755
12756 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12757
12758 bfd_boolean
12759 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12760                            asection *sec ATTRIBUTE_UNUSED,
12761                            struct elf_link_hash_entry *h,
12762                            bfd_vma addend)
12763 {
12764   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12765   unsigned int log_file_align = bed->s->log_file_align;
12766
12767   if (!h->vtable)
12768     {
12769       h->vtable = ((struct elf_link_virtual_table_entry *)
12770                    bfd_zalloc (abfd, sizeof (*h->vtable)));
12771       if (!h->vtable)
12772         return FALSE;
12773     }
12774
12775   if (addend >= h->vtable->size)
12776     {
12777       size_t size, bytes, file_align;
12778       bfd_boolean *ptr = h->vtable->used;
12779
12780       /* While the symbol is undefined, we have to be prepared to handle
12781          a zero size.  */
12782       file_align = 1 << log_file_align;
12783       if (h->root.type == bfd_link_hash_undefined)
12784         size = addend + file_align;
12785       else
12786         {
12787           size = h->size;
12788           if (addend >= size)
12789             {
12790               /* Oops!  We've got a reference past the defined end of
12791                  the table.  This is probably a bug -- shall we warn?  */
12792               size = addend + file_align;
12793             }
12794         }
12795       size = (size + file_align - 1) & -file_align;
12796
12797       /* Allocate one extra entry for use as a "done" flag for the
12798          consolidation pass.  */
12799       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12800
12801       if (ptr)
12802         {
12803           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12804
12805           if (ptr != NULL)
12806             {
12807               size_t oldbytes;
12808
12809               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12810                           * sizeof (bfd_boolean));
12811               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12812             }
12813         }
12814       else
12815         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12816
12817       if (ptr == NULL)
12818         return FALSE;
12819
12820       /* And arrange for that done flag to be at index -1.  */
12821       h->vtable->used = ptr + 1;
12822       h->vtable->size = size;
12823     }
12824
12825   h->vtable->used[addend >> log_file_align] = TRUE;
12826
12827   return TRUE;
12828 }
12829
12830 /* Map an ELF section header flag to its corresponding string.  */
12831 typedef struct
12832 {
12833   char *flag_name;
12834   flagword flag_value;
12835 } elf_flags_to_name_table;
12836
12837 static elf_flags_to_name_table elf_flags_to_names [] =
12838 {
12839   { "SHF_WRITE", SHF_WRITE },
12840   { "SHF_ALLOC", SHF_ALLOC },
12841   { "SHF_EXECINSTR", SHF_EXECINSTR },
12842   { "SHF_MERGE", SHF_MERGE },
12843   { "SHF_STRINGS", SHF_STRINGS },
12844   { "SHF_INFO_LINK", SHF_INFO_LINK},
12845   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12846   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12847   { "SHF_GROUP", SHF_GROUP },
12848   { "SHF_TLS", SHF_TLS },
12849   { "SHF_MASKOS", SHF_MASKOS },
12850   { "SHF_EXCLUDE", SHF_EXCLUDE },
12851 };
12852
12853 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
12854 bfd_boolean
12855 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12856                               struct flag_info *flaginfo,
12857                               asection *section)
12858 {
12859   const bfd_vma sh_flags = elf_section_flags (section);
12860
12861   if (!flaginfo->flags_initialized)
12862     {
12863       bfd *obfd = info->output_bfd;
12864       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12865       struct flag_info_list *tf = flaginfo->flag_list;
12866       int with_hex = 0;
12867       int without_hex = 0;
12868
12869       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
12870         {
12871           unsigned i;
12872           flagword (*lookup) (char *);
12873
12874           lookup = bed->elf_backend_lookup_section_flags_hook;
12875           if (lookup != NULL)
12876             {
12877               flagword hexval = (*lookup) ((char *) tf->name);
12878
12879               if (hexval != 0)
12880                 {
12881                   if (tf->with == with_flags)
12882                     with_hex |= hexval;
12883                   else if (tf->with == without_flags)
12884                     without_hex |= hexval;
12885                   tf->valid = TRUE;
12886                   continue;
12887                 }
12888             }
12889           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
12890             {
12891               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
12892                 {
12893                   if (tf->with == with_flags)
12894                     with_hex |= elf_flags_to_names[i].flag_value;
12895                   else if (tf->with == without_flags)
12896                     without_hex |= elf_flags_to_names[i].flag_value;
12897                   tf->valid = TRUE;
12898                   break;
12899                 }
12900             }
12901           if (!tf->valid)
12902             {
12903               info->callbacks->einfo
12904                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12905               return FALSE;
12906             }
12907         }
12908       flaginfo->flags_initialized = TRUE;
12909       flaginfo->only_with_flags |= with_hex;
12910       flaginfo->not_with_flags |= without_hex;
12911     }
12912
12913   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
12914     return FALSE;
12915
12916   if ((flaginfo->not_with_flags & sh_flags) != 0)
12917     return FALSE;
12918
12919   return TRUE;
12920 }
12921
12922 struct alloc_got_off_arg {
12923   bfd_vma gotoff;
12924   struct bfd_link_info *info;
12925 };
12926
12927 /* We need a special top-level link routine to convert got reference counts
12928    to real got offsets.  */
12929
12930 static bfd_boolean
12931 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12932 {
12933   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12934   bfd *obfd = gofarg->info->output_bfd;
12935   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12936
12937   if (h->got.refcount > 0)
12938     {
12939       h->got.offset = gofarg->gotoff;
12940       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12941     }
12942   else
12943     h->got.offset = (bfd_vma) -1;
12944
12945   return TRUE;
12946 }
12947
12948 /* And an accompanying bit to work out final got entry offsets once
12949    we're done.  Should be called from final_link.  */
12950
12951 bfd_boolean
12952 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12953                                         struct bfd_link_info *info)
12954 {
12955   bfd *i;
12956   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12957   bfd_vma gotoff;
12958   struct alloc_got_off_arg gofarg;
12959
12960   BFD_ASSERT (abfd == info->output_bfd);
12961
12962   if (! is_elf_hash_table (info->hash))
12963     return FALSE;
12964
12965   /* The GOT offset is relative to the .got section, but the GOT header is
12966      put into the .got.plt section, if the backend uses it.  */
12967   if (bed->want_got_plt)
12968     gotoff = 0;
12969   else
12970     gotoff = bed->got_header_size;
12971
12972   /* Do the local .got entries first.  */
12973   for (i = info->input_bfds; i; i = i->link.next)
12974     {
12975       bfd_signed_vma *local_got;
12976       bfd_size_type j, locsymcount;
12977       Elf_Internal_Shdr *symtab_hdr;
12978
12979       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
12980         continue;
12981
12982       local_got = elf_local_got_refcounts (i);
12983       if (!local_got)
12984         continue;
12985
12986       symtab_hdr = &elf_tdata (i)->symtab_hdr;
12987       if (elf_bad_symtab (i))
12988         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12989       else
12990         locsymcount = symtab_hdr->sh_info;
12991
12992       for (j = 0; j < locsymcount; ++j)
12993         {
12994           if (local_got[j] > 0)
12995             {
12996               local_got[j] = gotoff;
12997               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
12998             }
12999           else
13000             local_got[j] = (bfd_vma) -1;
13001         }
13002     }
13003
13004   /* Then the global .got entries.  .plt refcounts are handled by
13005      adjust_dynamic_symbol  */
13006   gofarg.gotoff = gotoff;
13007   gofarg.info = info;
13008   elf_link_hash_traverse (elf_hash_table (info),
13009                           elf_gc_allocate_got_offsets,
13010                           &gofarg);
13011   return TRUE;
13012 }
13013
13014 /* Many folk need no more in the way of final link than this, once
13015    got entry reference counting is enabled.  */
13016
13017 bfd_boolean
13018 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13019 {
13020   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13021     return FALSE;
13022
13023   /* Invoke the regular ELF backend linker to do all the work.  */
13024   return bfd_elf_final_link (abfd, info);
13025 }
13026
13027 bfd_boolean
13028 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13029 {
13030   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13031
13032   if (rcookie->bad_symtab)
13033     rcookie->rel = rcookie->rels;
13034
13035   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13036     {
13037       unsigned long r_symndx;
13038
13039       if (! rcookie->bad_symtab)
13040         if (rcookie->rel->r_offset > offset)
13041           return FALSE;
13042       if (rcookie->rel->r_offset != offset)
13043         continue;
13044
13045       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13046       if (r_symndx == STN_UNDEF)
13047         return TRUE;
13048
13049       if (r_symndx >= rcookie->locsymcount
13050           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13051         {
13052           struct elf_link_hash_entry *h;
13053
13054           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13055
13056           while (h->root.type == bfd_link_hash_indirect
13057                  || h->root.type == bfd_link_hash_warning)
13058             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13059
13060           if ((h->root.type == bfd_link_hash_defined
13061                || h->root.type == bfd_link_hash_defweak)
13062               && (h->root.u.def.section->owner != rcookie->abfd
13063                   || h->root.u.def.section->kept_section != NULL
13064                   || discarded_section (h->root.u.def.section)))
13065             return TRUE;
13066         }
13067       else
13068         {
13069           /* It's not a relocation against a global symbol,
13070              but it could be a relocation against a local
13071              symbol for a discarded section.  */
13072           asection *isec;
13073           Elf_Internal_Sym *isym;
13074
13075           /* Need to: get the symbol; get the section.  */
13076           isym = &rcookie->locsyms[r_symndx];
13077           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13078           if (isec != NULL
13079               && (isec->kept_section != NULL
13080                   || discarded_section (isec)))
13081             return TRUE;
13082         }
13083       return FALSE;
13084     }
13085   return FALSE;
13086 }
13087
13088 /* Discard unneeded references to discarded sections.
13089    Returns -1 on error, 1 if any section's size was changed, 0 if
13090    nothing changed.  This function assumes that the relocations are in
13091    sorted order, which is true for all known assemblers.  */
13092
13093 int
13094 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13095 {
13096   struct elf_reloc_cookie cookie;
13097   asection *o;
13098   bfd *abfd;
13099   int changed = 0;
13100
13101   if (info->traditional_format
13102       || !is_elf_hash_table (info->hash))
13103     return 0;
13104
13105   o = bfd_get_section_by_name (output_bfd, ".stab");
13106   if (o != NULL)
13107     {
13108       asection *i;
13109
13110       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13111         {
13112           if (i->size == 0
13113               || i->reloc_count == 0
13114               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13115             continue;
13116
13117           abfd = i->owner;
13118           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13119             continue;
13120
13121           if (!init_reloc_cookie_for_section (&cookie, info, i))
13122             return -1;
13123
13124           if (_bfd_discard_section_stabs (abfd, i,
13125                                           elf_section_data (i)->sec_info,
13126                                           bfd_elf_reloc_symbol_deleted_p,
13127                                           &cookie))
13128             changed = 1;
13129
13130           fini_reloc_cookie_for_section (&cookie, i);
13131         }
13132     }
13133
13134   o = NULL;
13135   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13136     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13137   if (o != NULL)
13138     {
13139       asection *i;
13140
13141       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13142         {
13143           if (i->size == 0)
13144             continue;
13145
13146           abfd = i->owner;
13147           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13148             continue;
13149
13150           if (!init_reloc_cookie_for_section (&cookie, info, i))
13151             return -1;
13152
13153           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13154           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13155                                                  bfd_elf_reloc_symbol_deleted_p,
13156                                                  &cookie))
13157             changed = 1;
13158
13159           fini_reloc_cookie_for_section (&cookie, i);
13160         }
13161     }
13162
13163   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13164     {
13165       const struct elf_backend_data *bed;
13166
13167       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13168         continue;
13169
13170       bed = get_elf_backend_data (abfd);
13171
13172       if (bed->elf_backend_discard_info != NULL)
13173         {
13174           if (!init_reloc_cookie (&cookie, info, abfd))
13175             return -1;
13176
13177           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13178             changed = 1;
13179
13180           fini_reloc_cookie (&cookie, abfd);
13181         }
13182     }
13183
13184   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13185     _bfd_elf_end_eh_frame_parsing (info);
13186
13187   if (info->eh_frame_hdr_type
13188       && !info->relocatable
13189       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13190     changed = 1;
13191
13192   return changed;
13193 }
13194
13195 bfd_boolean
13196 _bfd_elf_section_already_linked (bfd *abfd,
13197                                  asection *sec,
13198                                  struct bfd_link_info *info)
13199 {
13200   flagword flags;
13201   const char *name, *key;
13202   struct bfd_section_already_linked *l;
13203   struct bfd_section_already_linked_hash_entry *already_linked_list;
13204
13205   if (sec->output_section == bfd_abs_section_ptr)
13206     return FALSE;
13207
13208   flags = sec->flags;
13209
13210   /* Return if it isn't a linkonce section.  A comdat group section
13211      also has SEC_LINK_ONCE set.  */
13212   if ((flags & SEC_LINK_ONCE) == 0)
13213     return FALSE;
13214
13215   /* Don't put group member sections on our list of already linked
13216      sections.  They are handled as a group via their group section.  */
13217   if (elf_sec_group (sec) != NULL)
13218     return FALSE;
13219
13220   /* For a SHT_GROUP section, use the group signature as the key.  */
13221   name = sec->name;
13222   if ((flags & SEC_GROUP) != 0
13223       && elf_next_in_group (sec) != NULL
13224       && elf_group_name (elf_next_in_group (sec)) != NULL)
13225     key = elf_group_name (elf_next_in_group (sec));
13226   else
13227     {
13228       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13229       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13230           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13231         key++;
13232       else
13233         /* Must be a user linkonce section that doesn't follow gcc's
13234            naming convention.  In this case we won't be matching
13235            single member groups.  */
13236         key = name;
13237     }
13238
13239   already_linked_list = bfd_section_already_linked_table_lookup (key);
13240
13241   for (l = already_linked_list->entry; l != NULL; l = l->next)
13242     {
13243       /* We may have 2 different types of sections on the list: group
13244          sections with a signature of <key> (<key> is some string),
13245          and linkonce sections named .gnu.linkonce.<type>.<key>.
13246          Match like sections.  LTO plugin sections are an exception.
13247          They are always named .gnu.linkonce.t.<key> and match either
13248          type of section.  */
13249       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13250            && ((flags & SEC_GROUP) != 0
13251                || strcmp (name, l->sec->name) == 0))
13252           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13253         {
13254           /* The section has already been linked.  See if we should
13255              issue a warning.  */
13256           if (!_bfd_handle_already_linked (sec, l, info))
13257             return FALSE;
13258
13259           if (flags & SEC_GROUP)
13260             {
13261               asection *first = elf_next_in_group (sec);
13262               asection *s = first;
13263
13264               while (s != NULL)
13265                 {
13266                   s->output_section = bfd_abs_section_ptr;
13267                   /* Record which group discards it.  */
13268                   s->kept_section = l->sec;
13269                   s = elf_next_in_group (s);
13270                   /* These lists are circular.  */
13271                   if (s == first)
13272                     break;
13273                 }
13274             }
13275
13276           return TRUE;
13277         }
13278     }
13279
13280   /* A single member comdat group section may be discarded by a
13281      linkonce section and vice versa.  */
13282   if ((flags & SEC_GROUP) != 0)
13283     {
13284       asection *first = elf_next_in_group (sec);
13285
13286       if (first != NULL && elf_next_in_group (first) == first)
13287         /* Check this single member group against linkonce sections.  */
13288         for (l = already_linked_list->entry; l != NULL; l = l->next)
13289           if ((l->sec->flags & SEC_GROUP) == 0
13290               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13291             {
13292               first->output_section = bfd_abs_section_ptr;
13293               first->kept_section = l->sec;
13294               sec->output_section = bfd_abs_section_ptr;
13295               break;
13296             }
13297     }
13298   else
13299     /* Check this linkonce section against single member groups.  */
13300     for (l = already_linked_list->entry; l != NULL; l = l->next)
13301       if (l->sec->flags & SEC_GROUP)
13302         {
13303           asection *first = elf_next_in_group (l->sec);
13304
13305           if (first != NULL
13306               && elf_next_in_group (first) == first
13307               && bfd_elf_match_symbols_in_sections (first, sec, info))
13308             {
13309               sec->output_section = bfd_abs_section_ptr;
13310               sec->kept_section = first;
13311               break;
13312             }
13313         }
13314
13315   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13316      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13317      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13318      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13319      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13320      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13321      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13322      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13323      The reverse order cannot happen as there is never a bfd with only the
13324      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13325      matter as here were are looking only for cross-bfd sections.  */
13326
13327   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13328     for (l = already_linked_list->entry; l != NULL; l = l->next)
13329       if ((l->sec->flags & SEC_GROUP) == 0
13330           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13331         {
13332           if (abfd != l->sec->owner)
13333             sec->output_section = bfd_abs_section_ptr;
13334           break;
13335         }
13336
13337   /* This is the first section with this name.  Record it.  */
13338   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13339     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13340   return sec->output_section == bfd_abs_section_ptr;
13341 }
13342
13343 bfd_boolean
13344 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13345 {
13346   return sym->st_shndx == SHN_COMMON;
13347 }
13348
13349 unsigned int
13350 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13351 {
13352   return SHN_COMMON;
13353 }
13354
13355 asection *
13356 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13357 {
13358   return bfd_com_section_ptr;
13359 }
13360
13361 bfd_vma
13362 _bfd_elf_default_got_elt_size (bfd *abfd,
13363                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13364                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13365                                bfd *ibfd ATTRIBUTE_UNUSED,
13366                                unsigned long symndx ATTRIBUTE_UNUSED)
13367 {
13368   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13369   return bed->s->arch_size / 8;
13370 }
13371
13372 /* Routines to support the creation of dynamic relocs.  */
13373
13374 /* Returns the name of the dynamic reloc section associated with SEC.  */
13375
13376 static const char *
13377 get_dynamic_reloc_section_name (bfd *       abfd,
13378                                 asection *  sec,
13379                                 bfd_boolean is_rela)
13380 {
13381   char *name;
13382   const char *old_name = bfd_get_section_name (NULL, sec);
13383   const char *prefix = is_rela ? ".rela" : ".rel";
13384
13385   if (old_name == NULL)
13386     return NULL;
13387
13388   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13389   sprintf (name, "%s%s", prefix, old_name);
13390
13391   return name;
13392 }
13393
13394 /* Returns the dynamic reloc section associated with SEC.
13395    If necessary compute the name of the dynamic reloc section based
13396    on SEC's name (looked up in ABFD's string table) and the setting
13397    of IS_RELA.  */
13398
13399 asection *
13400 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13401                                     asection *  sec,
13402                                     bfd_boolean is_rela)
13403 {
13404   asection * reloc_sec = elf_section_data (sec)->sreloc;
13405
13406   if (reloc_sec == NULL)
13407     {
13408       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13409
13410       if (name != NULL)
13411         {
13412           reloc_sec = bfd_get_linker_section (abfd, name);
13413
13414           if (reloc_sec != NULL)
13415             elf_section_data (sec)->sreloc = reloc_sec;
13416         }
13417     }
13418
13419   return reloc_sec;
13420 }
13421
13422 /* Returns the dynamic reloc section associated with SEC.  If the
13423    section does not exist it is created and attached to the DYNOBJ
13424    bfd and stored in the SRELOC field of SEC's elf_section_data
13425    structure.
13426
13427    ALIGNMENT is the alignment for the newly created section and
13428    IS_RELA defines whether the name should be .rela.<SEC's name>
13429    or .rel.<SEC's name>.  The section name is looked up in the
13430    string table associated with ABFD.  */
13431
13432 asection *
13433 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13434                                      bfd *dynobj,
13435                                      unsigned int alignment,
13436                                      bfd *abfd,
13437                                      bfd_boolean is_rela)
13438 {
13439   asection * reloc_sec = elf_section_data (sec)->sreloc;
13440
13441   if (reloc_sec == NULL)
13442     {
13443       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13444
13445       if (name == NULL)
13446         return NULL;
13447
13448       reloc_sec = bfd_get_linker_section (dynobj, name);
13449
13450       if (reloc_sec == NULL)
13451         {
13452           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13453                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13454           if ((sec->flags & SEC_ALLOC) != 0)
13455             flags |= SEC_ALLOC | SEC_LOAD;
13456
13457           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13458           if (reloc_sec != NULL)
13459             {
13460               /* _bfd_elf_get_sec_type_attr chooses a section type by
13461                  name.  Override as it may be wrong, eg. for a user
13462                  section named "auto" we'll get ".relauto" which is
13463                  seen to be a .rela section.  */
13464               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13465               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13466                 reloc_sec = NULL;
13467             }
13468         }
13469
13470       elf_section_data (sec)->sreloc = reloc_sec;
13471     }
13472
13473   return reloc_sec;
13474 }
13475
13476 /* Copy the ELF symbol type and other attributes for a linker script
13477    assignment from HSRC to HDEST.  Generally this should be treated as
13478    if we found a strong non-dynamic definition for HDEST (except that
13479    ld ignores multiple definition errors).  */
13480 void
13481 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13482                                      struct bfd_link_hash_entry *hdest,
13483                                      struct bfd_link_hash_entry *hsrc)
13484 {
13485   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13486   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13487   Elf_Internal_Sym isym;
13488
13489   ehdest->type = ehsrc->type;
13490   ehdest->target_internal = ehsrc->target_internal;
13491
13492   isym.st_other = ehsrc->other;
13493   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13494 }
13495
13496 /* Append a RELA relocation REL to section S in BFD.  */
13497
13498 void
13499 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13500 {
13501   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13502   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13503   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13504   bed->s->swap_reloca_out (abfd, rel, loc);
13505 }
13506
13507 /* Append a REL relocation REL to section S in BFD.  */
13508
13509 void
13510 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13511 {
13512   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13513   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13514   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13515   bed->s->swap_reloc_out (abfd, rel, loc);
13516 }