Fix implib test failures
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2016 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 #if BFD_SUPPORTS_PLUGINS
32 #include "plugin-api.h"
33 #include "plugin.h"
34 #endif
35
36 /* This struct is used to pass information to routines called via
37    elf_link_hash_traverse which must return failure.  */
38
39 struct elf_info_failed
40 {
41   struct bfd_link_info *info;
42   bfd_boolean failed;
43 };
44
45 /* This structure is used to pass information to
46    _bfd_elf_link_find_version_dependencies.  */
47
48 struct elf_find_verdep_info
49 {
50   /* General link information.  */
51   struct bfd_link_info *info;
52   /* The number of dependencies.  */
53   unsigned int vers;
54   /* Whether we had a failure.  */
55   bfd_boolean failed;
56 };
57
58 static bfd_boolean _bfd_elf_fix_symbol_flags
59   (struct elf_link_hash_entry *, struct elf_info_failed *);
60
61 asection *
62 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
63                              unsigned long r_symndx,
64                              bfd_boolean discard)
65 {
66   if (r_symndx >= cookie->locsymcount
67       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
68     {
69       struct elf_link_hash_entry *h;
70
71       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
72
73       while (h->root.type == bfd_link_hash_indirect
74              || h->root.type == bfd_link_hash_warning)
75         h = (struct elf_link_hash_entry *) h->root.u.i.link;
76
77       if ((h->root.type == bfd_link_hash_defined
78            || h->root.type == bfd_link_hash_defweak)
79            && discarded_section (h->root.u.def.section))
80         return h->root.u.def.section;
81       else
82         return NULL;
83     }
84   else
85     {
86       /* It's not a relocation against a global symbol,
87          but it could be a relocation against a local
88          symbol for a discarded section.  */
89       asection *isec;
90       Elf_Internal_Sym *isym;
91
92       /* Need to: get the symbol; get the section.  */
93       isym = &cookie->locsyms[r_symndx];
94       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
95       if (isec != NULL
96           && discard ? discarded_section (isec) : 1)
97         return isec;
98      }
99   return NULL;
100 }
101
102 /* Define a symbol in a dynamic linkage section.  */
103
104 struct elf_link_hash_entry *
105 _bfd_elf_define_linkage_sym (bfd *abfd,
106                              struct bfd_link_info *info,
107                              asection *sec,
108                              const char *name)
109 {
110   struct elf_link_hash_entry *h;
111   struct bfd_link_hash_entry *bh;
112   const struct elf_backend_data *bed;
113
114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
115   if (h != NULL)
116     {
117       /* Zap symbol defined in an as-needed lib that wasn't linked.
118          This is a symptom of a larger problem:  Absolute symbols
119          defined in shared libraries can't be overridden, because we
120          lose the link to the bfd which is via the symbol section.  */
121       h->root.type = bfd_link_hash_new;
122     }
123
124   bh = &h->root;
125   bed = get_elf_backend_data (abfd);
126   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
127                                          sec, 0, NULL, FALSE, bed->collect,
128                                          &bh))
129     return NULL;
130   h = (struct elf_link_hash_entry *) bh;
131   h->def_regular = 1;
132   h->non_elf = 0;
133   h->root.linker_def = 1;
134   h->type = STT_OBJECT;
135   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
136     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
137
138   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
139   return h;
140 }
141
142 bfd_boolean
143 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
144 {
145   flagword flags;
146   asection *s;
147   struct elf_link_hash_entry *h;
148   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
149   struct elf_link_hash_table *htab = elf_hash_table (info);
150
151   /* This function may be called more than once.  */
152   s = bfd_get_linker_section (abfd, ".got");
153   if (s != NULL)
154     return TRUE;
155
156   flags = bed->dynamic_sec_flags;
157
158   s = bfd_make_section_anyway_with_flags (abfd,
159                                           (bed->rela_plts_and_copies_p
160                                            ? ".rela.got" : ".rel.got"),
161                                           (bed->dynamic_sec_flags
162                                            | SEC_READONLY));
163   if (s == NULL
164       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
165     return FALSE;
166   htab->srelgot = s;
167
168   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
169   if (s == NULL
170       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
171     return FALSE;
172   htab->sgot = s;
173
174   if (bed->want_got_plt)
175     {
176       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
177       if (s == NULL
178           || !bfd_set_section_alignment (abfd, s,
179                                          bed->s->log_file_align))
180         return FALSE;
181       htab->sgotplt = s;
182     }
183
184   /* The first bit of the global offset table is the header.  */
185   s->size += bed->got_header_size;
186
187   if (bed->want_got_sym)
188     {
189       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
190          (or .got.plt) section.  We don't do this in the linker script
191          because we don't want to define the symbol if we are not creating
192          a global offset table.  */
193       h = _bfd_elf_define_linkage_sym (abfd, info, s,
194                                        "_GLOBAL_OFFSET_TABLE_");
195       elf_hash_table (info)->hgot = h;
196       if (h == NULL)
197         return FALSE;
198     }
199
200   return TRUE;
201 }
202 \f
203 /* Create a strtab to hold the dynamic symbol names.  */
204 static bfd_boolean
205 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
206 {
207   struct elf_link_hash_table *hash_table;
208
209   hash_table = elf_hash_table (info);
210   if (hash_table->dynobj == NULL)
211     {
212       /* We may not set dynobj, an input file holding linker created
213          dynamic sections to abfd, which may be a dynamic object with
214          its own dynamic sections.  We need to find a normal input file
215          to hold linker created sections if possible.  */
216       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
217         {
218           bfd *ibfd;
219           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
220             if ((ibfd->flags
221                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0)
222               {
223                 abfd = ibfd;
224                 break;
225               }
226         }
227       hash_table->dynobj = abfd;
228     }
229
230   if (hash_table->dynstr == NULL)
231     {
232       hash_table->dynstr = _bfd_elf_strtab_init ();
233       if (hash_table->dynstr == NULL)
234         return FALSE;
235     }
236   return TRUE;
237 }
238
239 /* Create some sections which will be filled in with dynamic linking
240    information.  ABFD is an input file which requires dynamic sections
241    to be created.  The dynamic sections take up virtual memory space
242    when the final executable is run, so we need to create them before
243    addresses are assigned to the output sections.  We work out the
244    actual contents and size of these sections later.  */
245
246 bfd_boolean
247 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
248 {
249   flagword flags;
250   asection *s;
251   const struct elf_backend_data *bed;
252   struct elf_link_hash_entry *h;
253
254   if (! is_elf_hash_table (info->hash))
255     return FALSE;
256
257   if (elf_hash_table (info)->dynamic_sections_created)
258     return TRUE;
259
260   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
261     return FALSE;
262
263   abfd = elf_hash_table (info)->dynobj;
264   bed = get_elf_backend_data (abfd);
265
266   flags = bed->dynamic_sec_flags;
267
268   /* A dynamically linked executable has a .interp section, but a
269      shared library does not.  */
270   if (bfd_link_executable (info) && !info->nointerp)
271     {
272       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
273                                               flags | SEC_READONLY);
274       if (s == NULL)
275         return FALSE;
276     }
277
278   /* Create sections to hold version informations.  These are removed
279      if they are not needed.  */
280   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
281                                           flags | SEC_READONLY);
282   if (s == NULL
283       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
284     return FALSE;
285
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, 1))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303   elf_hash_table (info)->dynsym = s;
304
305   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
306                                           flags | SEC_READONLY);
307   if (s == NULL)
308     return FALSE;
309
310   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
311   if (s == NULL
312       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
313     return FALSE;
314
315   /* The special symbol _DYNAMIC is always set to the start of the
316      .dynamic section.  We could set _DYNAMIC in a linker script, but we
317      only want to define it if we are, in fact, creating a .dynamic
318      section.  We don't want to define it if there is no .dynamic
319      section, since on some ELF platforms the start up code examines it
320      to decide how to initialize the process.  */
321   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
322   elf_hash_table (info)->hdynamic = h;
323   if (h == NULL)
324     return FALSE;
325
326   if (info->emit_hash)
327     {
328       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
329                                               flags | SEC_READONLY);
330       if (s == NULL
331           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
332         return FALSE;
333       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
334     }
335
336   if (info->emit_gnu_hash)
337     {
338       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
339                                               flags | SEC_READONLY);
340       if (s == NULL
341           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
342         return FALSE;
343       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
344          4 32-bit words followed by variable count of 64-bit words, then
345          variable count of 32-bit words.  */
346       if (bed->s->arch_size == 64)
347         elf_section_data (s)->this_hdr.sh_entsize = 0;
348       else
349         elf_section_data (s)->this_hdr.sh_entsize = 4;
350     }
351
352   /* Let the backend create the rest of the sections.  This lets the
353      backend set the right flags.  The backend will normally create
354      the .got and .plt sections.  */
355   if (bed->elf_backend_create_dynamic_sections == NULL
356       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
357     return FALSE;
358
359   elf_hash_table (info)->dynamic_sections_created = TRUE;
360
361   return TRUE;
362 }
363
364 /* Create dynamic sections when linking against a dynamic object.  */
365
366 bfd_boolean
367 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
368 {
369   flagword flags, pltflags;
370   struct elf_link_hash_entry *h;
371   asection *s;
372   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
373   struct elf_link_hash_table *htab = elf_hash_table (info);
374
375   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
376      .rel[a].bss sections.  */
377   flags = bed->dynamic_sec_flags;
378
379   pltflags = flags;
380   if (bed->plt_not_loaded)
381     /* We do not clear SEC_ALLOC here because we still want the OS to
382        allocate space for the section; it's just that there's nothing
383        to read in from the object file.  */
384     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
385   else
386     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
387   if (bed->plt_readonly)
388     pltflags |= SEC_READONLY;
389
390   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
391   if (s == NULL
392       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
393     return FALSE;
394   htab->splt = s;
395
396   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
397      .plt section.  */
398   if (bed->want_plt_sym)
399     {
400       h = _bfd_elf_define_linkage_sym (abfd, info, s,
401                                        "_PROCEDURE_LINKAGE_TABLE_");
402       elf_hash_table (info)->hplt = h;
403       if (h == NULL)
404         return FALSE;
405     }
406
407   s = bfd_make_section_anyway_with_flags (abfd,
408                                           (bed->rela_plts_and_copies_p
409                                            ? ".rela.plt" : ".rel.plt"),
410                                           flags | SEC_READONLY);
411   if (s == NULL
412       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
413     return FALSE;
414   htab->srelplt = s;
415
416   if (! _bfd_elf_create_got_section (abfd, info))
417     return FALSE;
418
419   if (bed->want_dynbss)
420     {
421       /* The .dynbss section is a place to put symbols which are defined
422          by dynamic objects, are referenced by regular objects, and are
423          not functions.  We must allocate space for them in the process
424          image and use a R_*_COPY reloc to tell the dynamic linker to
425          initialize them at run time.  The linker script puts the .dynbss
426          section into the .bss section of the final image.  */
427       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
428                                               (SEC_ALLOC | SEC_LINKER_CREATED));
429       if (s == NULL)
430         return FALSE;
431
432       /* The .rel[a].bss section holds copy relocs.  This section is not
433          normally needed.  We need to create it here, though, so that the
434          linker will map it to an output section.  We can't just create it
435          only if we need it, because we will not know whether we need it
436          until we have seen all the input files, and the first time the
437          main linker code calls BFD after examining all the input files
438          (size_dynamic_sections) the input sections have already been
439          mapped to the output sections.  If the section turns out not to
440          be needed, we can discard it later.  We will never need this
441          section when generating a shared object, since they do not use
442          copy relocs.  */
443       if (! bfd_link_pic (info))
444         {
445           s = bfd_make_section_anyway_with_flags (abfd,
446                                                   (bed->rela_plts_and_copies_p
447                                                    ? ".rela.bss" : ".rel.bss"),
448                                                   flags | SEC_READONLY);
449           if (s == NULL
450               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
451             return FALSE;
452         }
453     }
454
455   return TRUE;
456 }
457 \f
458 /* Record a new dynamic symbol.  We record the dynamic symbols as we
459    read the input files, since we need to have a list of all of them
460    before we can determine the final sizes of the output sections.
461    Note that we may actually call this function even though we are not
462    going to output any dynamic symbols; in some cases we know that a
463    symbol should be in the dynamic symbol table, but only if there is
464    one.  */
465
466 bfd_boolean
467 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
468                                     struct elf_link_hash_entry *h)
469 {
470   if (h->dynindx == -1)
471     {
472       struct elf_strtab_hash *dynstr;
473       char *p;
474       const char *name;
475       size_t indx;
476
477       /* XXX: The ABI draft says the linker must turn hidden and
478          internal symbols into STB_LOCAL symbols when producing the
479          DSO. However, if ld.so honors st_other in the dynamic table,
480          this would not be necessary.  */
481       switch (ELF_ST_VISIBILITY (h->other))
482         {
483         case STV_INTERNAL:
484         case STV_HIDDEN:
485           if (h->root.type != bfd_link_hash_undefined
486               && h->root.type != bfd_link_hash_undefweak)
487             {
488               h->forced_local = 1;
489               if (!elf_hash_table (info)->is_relocatable_executable)
490                 return TRUE;
491             }
492
493         default:
494           break;
495         }
496
497       h->dynindx = elf_hash_table (info)->dynsymcount;
498       ++elf_hash_table (info)->dynsymcount;
499
500       dynstr = elf_hash_table (info)->dynstr;
501       if (dynstr == NULL)
502         {
503           /* Create a strtab to hold the dynamic symbol names.  */
504           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
505           if (dynstr == NULL)
506             return FALSE;
507         }
508
509       /* We don't put any version information in the dynamic string
510          table.  */
511       name = h->root.root.string;
512       p = strchr (name, ELF_VER_CHR);
513       if (p != NULL)
514         /* We know that the p points into writable memory.  In fact,
515            there are only a few symbols that have read-only names, being
516            those like _GLOBAL_OFFSET_TABLE_ that are created specially
517            by the backends.  Most symbols will have names pointing into
518            an ELF string table read from a file, or to objalloc memory.  */
519         *p = 0;
520
521       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
522
523       if (p != NULL)
524         *p = ELF_VER_CHR;
525
526       if (indx == (size_t) -1)
527         return FALSE;
528       h->dynstr_index = indx;
529     }
530
531   return TRUE;
532 }
533 \f
534 /* Mark a symbol dynamic.  */
535
536 static void
537 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
538                                   struct elf_link_hash_entry *h,
539                                   Elf_Internal_Sym *sym)
540 {
541   struct bfd_elf_dynamic_list *d = info->dynamic_list;
542
543   /* It may be called more than once on the same H.  */
544   if(h->dynamic || bfd_link_relocatable (info))
545     return;
546
547   if ((info->dynamic_data
548        && (h->type == STT_OBJECT
549            || h->type == STT_COMMON
550            || (sym != NULL
551                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
552                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
553       || (d != NULL
554           && h->root.type == bfd_link_hash_new
555           && (*d->match) (&d->head, NULL, h->root.root.string)))
556     h->dynamic = 1;
557 }
558
559 /* Record an assignment to a symbol made by a linker script.  We need
560    this in case some dynamic object refers to this symbol.  */
561
562 bfd_boolean
563 bfd_elf_record_link_assignment (bfd *output_bfd,
564                                 struct bfd_link_info *info,
565                                 const char *name,
566                                 bfd_boolean provide,
567                                 bfd_boolean hidden)
568 {
569   struct elf_link_hash_entry *h, *hv;
570   struct elf_link_hash_table *htab;
571   const struct elf_backend_data *bed;
572
573   if (!is_elf_hash_table (info->hash))
574     return TRUE;
575
576   htab = elf_hash_table (info);
577   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
578   if (h == NULL)
579     return provide;
580
581   if (h->versioned == unknown)
582     {
583       /* Set versioned if symbol version is unknown.  */
584       char *version = strrchr (name, ELF_VER_CHR);
585       if (version)
586         {
587           if (version > name && version[-1] != ELF_VER_CHR)
588             h->versioned = versioned_hidden;
589           else
590             h->versioned = versioned;
591         }
592     }
593
594   switch (h->root.type)
595     {
596     case bfd_link_hash_defined:
597     case bfd_link_hash_defweak:
598     case bfd_link_hash_common:
599       break;
600     case bfd_link_hash_undefweak:
601     case bfd_link_hash_undefined:
602       /* Since we're defining the symbol, don't let it seem to have not
603          been defined.  record_dynamic_symbol and size_dynamic_sections
604          may depend on this.  */
605       h->root.type = bfd_link_hash_new;
606       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
607         bfd_link_repair_undef_list (&htab->root);
608       break;
609     case bfd_link_hash_new:
610       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
611       h->non_elf = 0;
612       break;
613     case bfd_link_hash_indirect:
614       /* We had a versioned symbol in a dynamic library.  We make the
615          the versioned symbol point to this one.  */
616       bed = get_elf_backend_data (output_bfd);
617       hv = h;
618       while (hv->root.type == bfd_link_hash_indirect
619              || hv->root.type == bfd_link_hash_warning)
620         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
621       /* We don't need to update h->root.u since linker will set them
622          later.  */
623       h->root.type = bfd_link_hash_undefined;
624       hv->root.type = bfd_link_hash_indirect;
625       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
626       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
627       break;
628     case bfd_link_hash_warning:
629       abort ();
630       break;
631     }
632
633   /* If this symbol is being provided by the linker script, and it is
634      currently defined by a dynamic object, but not by a regular
635      object, then mark it as undefined so that the generic linker will
636      force the correct value.  */
637   if (provide
638       && h->def_dynamic
639       && !h->def_regular)
640     h->root.type = bfd_link_hash_undefined;
641
642   /* If this symbol is not being provided by the linker script, and it is
643      currently defined by a dynamic object, but not by a regular object,
644      then clear out any version information because the symbol will not be
645      associated with the dynamic object any more.  */
646   if (!provide
647       && h->def_dynamic
648       && !h->def_regular)
649     h->verinfo.verdef = NULL;
650
651   h->def_regular = 1;
652
653   if (hidden)
654     {
655       bed = get_elf_backend_data (output_bfd);
656       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
657         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
658       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
659     }
660
661   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
662      and executables.  */
663   if (!bfd_link_relocatable (info)
664       && h->dynindx != -1
665       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
666           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
667     h->forced_local = 1;
668
669   if ((h->def_dynamic
670        || h->ref_dynamic
671        || bfd_link_dll (info)
672        || elf_hash_table (info)->is_relocatable_executable)
673       && h->dynindx == -1)
674     {
675       if (! bfd_elf_link_record_dynamic_symbol (info, h))
676         return FALSE;
677
678       /* If this is a weak defined symbol, and we know a corresponding
679          real symbol from the same dynamic object, make sure the real
680          symbol is also made into a dynamic symbol.  */
681       if (h->u.weakdef != NULL
682           && h->u.weakdef->dynindx == -1)
683         {
684           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
685             return FALSE;
686         }
687     }
688
689   return TRUE;
690 }
691
692 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
693    success, and 2 on a failure caused by attempting to record a symbol
694    in a discarded section, eg. a discarded link-once section symbol.  */
695
696 int
697 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
698                                           bfd *input_bfd,
699                                           long input_indx)
700 {
701   bfd_size_type amt;
702   struct elf_link_local_dynamic_entry *entry;
703   struct elf_link_hash_table *eht;
704   struct elf_strtab_hash *dynstr;
705   size_t dynstr_index;
706   char *name;
707   Elf_External_Sym_Shndx eshndx;
708   char esym[sizeof (Elf64_External_Sym)];
709
710   if (! is_elf_hash_table (info->hash))
711     return 0;
712
713   /* See if the entry exists already.  */
714   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
715     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
716       return 1;
717
718   amt = sizeof (*entry);
719   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
720   if (entry == NULL)
721     return 0;
722
723   /* Go find the symbol, so that we can find it's name.  */
724   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
725                              1, input_indx, &entry->isym, esym, &eshndx))
726     {
727       bfd_release (input_bfd, entry);
728       return 0;
729     }
730
731   if (entry->isym.st_shndx != SHN_UNDEF
732       && entry->isym.st_shndx < SHN_LORESERVE)
733     {
734       asection *s;
735
736       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
737       if (s == NULL || bfd_is_abs_section (s->output_section))
738         {
739           /* We can still bfd_release here as nothing has done another
740              bfd_alloc.  We can't do this later in this function.  */
741           bfd_release (input_bfd, entry);
742           return 2;
743         }
744     }
745
746   name = (bfd_elf_string_from_elf_section
747           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
748            entry->isym.st_name));
749
750   dynstr = elf_hash_table (info)->dynstr;
751   if (dynstr == NULL)
752     {
753       /* Create a strtab to hold the dynamic symbol names.  */
754       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
755       if (dynstr == NULL)
756         return 0;
757     }
758
759   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
760   if (dynstr_index == (size_t) -1)
761     return 0;
762   entry->isym.st_name = dynstr_index;
763
764   eht = elf_hash_table (info);
765
766   entry->next = eht->dynlocal;
767   eht->dynlocal = entry;
768   entry->input_bfd = input_bfd;
769   entry->input_indx = input_indx;
770   eht->dynsymcount++;
771
772   /* Whatever binding the symbol had before, it's now local.  */
773   entry->isym.st_info
774     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
775
776   /* The dynindx will be set at the end of size_dynamic_sections.  */
777
778   return 1;
779 }
780
781 /* Return the dynindex of a local dynamic symbol.  */
782
783 long
784 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
785                                     bfd *input_bfd,
786                                     long input_indx)
787 {
788   struct elf_link_local_dynamic_entry *e;
789
790   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
791     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
792       return e->dynindx;
793   return -1;
794 }
795
796 /* This function is used to renumber the dynamic symbols, if some of
797    them are removed because they are marked as local.  This is called
798    via elf_link_hash_traverse.  */
799
800 static bfd_boolean
801 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
802                                       void *data)
803 {
804   size_t *count = (size_t *) data;
805
806   if (h->forced_local)
807     return TRUE;
808
809   if (h->dynindx != -1)
810     h->dynindx = ++(*count);
811
812   return TRUE;
813 }
814
815
816 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
817    STB_LOCAL binding.  */
818
819 static bfd_boolean
820 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
821                                             void *data)
822 {
823   size_t *count = (size_t *) data;
824
825   if (!h->forced_local)
826     return TRUE;
827
828   if (h->dynindx != -1)
829     h->dynindx = ++(*count);
830
831   return TRUE;
832 }
833
834 /* Return true if the dynamic symbol for a given section should be
835    omitted when creating a shared library.  */
836 bfd_boolean
837 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
838                                    struct bfd_link_info *info,
839                                    asection *p)
840 {
841   struct elf_link_hash_table *htab;
842   asection *ip;
843
844   switch (elf_section_data (p)->this_hdr.sh_type)
845     {
846     case SHT_PROGBITS:
847     case SHT_NOBITS:
848       /* If sh_type is yet undecided, assume it could be
849          SHT_PROGBITS/SHT_NOBITS.  */
850     case SHT_NULL:
851       htab = elf_hash_table (info);
852       if (p == htab->tls_sec)
853         return FALSE;
854
855       if (htab->text_index_section != NULL)
856         return p != htab->text_index_section && p != htab->data_index_section;
857
858       return (htab->dynobj != NULL
859               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
860               && ip->output_section == p);
861
862       /* There shouldn't be section relative relocations
863          against any other section.  */
864     default:
865       return TRUE;
866     }
867 }
868
869 /* Assign dynsym indices.  In a shared library we generate a section
870    symbol for each output section, which come first.  Next come symbols
871    which have been forced to local binding.  Then all of the back-end
872    allocated local dynamic syms, followed by the rest of the global
873    symbols.  */
874
875 static unsigned long
876 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
877                                 struct bfd_link_info *info,
878                                 unsigned long *section_sym_count)
879 {
880   unsigned long dynsymcount = 0;
881
882   if (bfd_link_pic (info)
883       || elf_hash_table (info)->is_relocatable_executable)
884     {
885       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
886       asection *p;
887       for (p = output_bfd->sections; p ; p = p->next)
888         if ((p->flags & SEC_EXCLUDE) == 0
889             && (p->flags & SEC_ALLOC) != 0
890             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
891           elf_section_data (p)->dynindx = ++dynsymcount;
892         else
893           elf_section_data (p)->dynindx = 0;
894     }
895   *section_sym_count = dynsymcount;
896
897   elf_link_hash_traverse (elf_hash_table (info),
898                           elf_link_renumber_local_hash_table_dynsyms,
899                           &dynsymcount);
900
901   if (elf_hash_table (info)->dynlocal)
902     {
903       struct elf_link_local_dynamic_entry *p;
904       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
905         p->dynindx = ++dynsymcount;
906     }
907
908   elf_link_hash_traverse (elf_hash_table (info),
909                           elf_link_renumber_hash_table_dynsyms,
910                           &dynsymcount);
911
912   /* There is an unused NULL entry at the head of the table which we
913      must account for in our count even if the table is empty since it
914      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
915      .dynamic section.  */
916   dynsymcount++;
917
918   elf_hash_table (info)->dynsymcount = dynsymcount;
919   return dynsymcount;
920 }
921
922 /* Merge st_other field.  */
923
924 static void
925 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
926                     const Elf_Internal_Sym *isym, asection *sec,
927                     bfd_boolean definition, bfd_boolean dynamic)
928 {
929   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
930
931   /* If st_other has a processor-specific meaning, specific
932      code might be needed here.  */
933   if (bed->elf_backend_merge_symbol_attribute)
934     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
935                                                 dynamic);
936
937   if (!dynamic)
938     {
939       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
940       unsigned hvis = ELF_ST_VISIBILITY (h->other);
941
942       /* Keep the most constraining visibility.  Leave the remainder
943          of the st_other field to elf_backend_merge_symbol_attribute.  */
944       if (symvis - 1 < hvis - 1)
945         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
946     }
947   else if (definition
948            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
949            && (sec->flags & SEC_READONLY) == 0)
950     h->protected_def = 1;
951 }
952
953 /* This function is called when we want to merge a new symbol with an
954    existing symbol.  It handles the various cases which arise when we
955    find a definition in a dynamic object, or when there is already a
956    definition in a dynamic object.  The new symbol is described by
957    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
958    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
959    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
960    of an old common symbol.  We set OVERRIDE if the old symbol is
961    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
962    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
963    to change.  By OK to change, we mean that we shouldn't warn if the
964    type or size does change.  */
965
966 static bfd_boolean
967 _bfd_elf_merge_symbol (bfd *abfd,
968                        struct bfd_link_info *info,
969                        const char *name,
970                        Elf_Internal_Sym *sym,
971                        asection **psec,
972                        bfd_vma *pvalue,
973                        struct elf_link_hash_entry **sym_hash,
974                        bfd **poldbfd,
975                        bfd_boolean *pold_weak,
976                        unsigned int *pold_alignment,
977                        bfd_boolean *skip,
978                        bfd_boolean *override,
979                        bfd_boolean *type_change_ok,
980                        bfd_boolean *size_change_ok,
981                        bfd_boolean *matched)
982 {
983   asection *sec, *oldsec;
984   struct elf_link_hash_entry *h;
985   struct elf_link_hash_entry *hi;
986   struct elf_link_hash_entry *flip;
987   int bind;
988   bfd *oldbfd;
989   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
990   bfd_boolean newweak, oldweak, newfunc, oldfunc;
991   const struct elf_backend_data *bed;
992   char *new_version;
993
994   *skip = FALSE;
995   *override = FALSE;
996
997   sec = *psec;
998   bind = ELF_ST_BIND (sym->st_info);
999
1000   if (! bfd_is_und_section (sec))
1001     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1002   else
1003     h = ((struct elf_link_hash_entry *)
1004          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1005   if (h == NULL)
1006     return FALSE;
1007   *sym_hash = h;
1008
1009   bed = get_elf_backend_data (abfd);
1010
1011   /* NEW_VERSION is the symbol version of the new symbol.  */
1012   if (h->versioned != unversioned)
1013     {
1014       /* Symbol version is unknown or versioned.  */
1015       new_version = strrchr (name, ELF_VER_CHR);
1016       if (new_version)
1017         {
1018           if (h->versioned == unknown)
1019             {
1020               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1021                 h->versioned = versioned_hidden;
1022               else
1023                 h->versioned = versioned;
1024             }
1025           new_version += 1;
1026           if (new_version[0] == '\0')
1027             new_version = NULL;
1028         }
1029       else
1030         h->versioned = unversioned;
1031     }
1032   else
1033     new_version = NULL;
1034
1035   /* For merging, we only care about real symbols.  But we need to make
1036      sure that indirect symbol dynamic flags are updated.  */
1037   hi = h;
1038   while (h->root.type == bfd_link_hash_indirect
1039          || h->root.type == bfd_link_hash_warning)
1040     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1041
1042   if (!*matched)
1043     {
1044       if (hi == h || h->root.type == bfd_link_hash_new)
1045         *matched = TRUE;
1046       else
1047         {
1048           /* OLD_HIDDEN is true if the existing symbol is only visible
1049              to the symbol with the same symbol version.  NEW_HIDDEN is
1050              true if the new symbol is only visible to the symbol with
1051              the same symbol version.  */
1052           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1053           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1054           if (!old_hidden && !new_hidden)
1055             /* The new symbol matches the existing symbol if both
1056                aren't hidden.  */
1057             *matched = TRUE;
1058           else
1059             {
1060               /* OLD_VERSION is the symbol version of the existing
1061                  symbol. */
1062               char *old_version;
1063
1064               if (h->versioned >= versioned)
1065                 old_version = strrchr (h->root.root.string,
1066                                        ELF_VER_CHR) + 1;
1067               else
1068                  old_version = NULL;
1069
1070               /* The new symbol matches the existing symbol if they
1071                  have the same symbol version.  */
1072               *matched = (old_version == new_version
1073                           || (old_version != NULL
1074                               && new_version != NULL
1075                               && strcmp (old_version, new_version) == 0));
1076             }
1077         }
1078     }
1079
1080   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1081      existing symbol.  */
1082
1083   oldbfd = NULL;
1084   oldsec = NULL;
1085   switch (h->root.type)
1086     {
1087     default:
1088       break;
1089
1090     case bfd_link_hash_undefined:
1091     case bfd_link_hash_undefweak:
1092       oldbfd = h->root.u.undef.abfd;
1093       break;
1094
1095     case bfd_link_hash_defined:
1096     case bfd_link_hash_defweak:
1097       oldbfd = h->root.u.def.section->owner;
1098       oldsec = h->root.u.def.section;
1099       break;
1100
1101     case bfd_link_hash_common:
1102       oldbfd = h->root.u.c.p->section->owner;
1103       oldsec = h->root.u.c.p->section;
1104       if (pold_alignment)
1105         *pold_alignment = h->root.u.c.p->alignment_power;
1106       break;
1107     }
1108   if (poldbfd && *poldbfd == NULL)
1109     *poldbfd = oldbfd;
1110
1111   /* Differentiate strong and weak symbols.  */
1112   newweak = bind == STB_WEAK;
1113   oldweak = (h->root.type == bfd_link_hash_defweak
1114              || h->root.type == bfd_link_hash_undefweak);
1115   if (pold_weak)
1116     *pold_weak = oldweak;
1117
1118   /* This code is for coping with dynamic objects, and is only useful
1119      if we are doing an ELF link.  */
1120   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1121     return TRUE;
1122
1123   /* We have to check it for every instance since the first few may be
1124      references and not all compilers emit symbol type for undefined
1125      symbols.  */
1126   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1127
1128   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1129      respectively, is from a dynamic object.  */
1130
1131   newdyn = (abfd->flags & DYNAMIC) != 0;
1132
1133   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1134      syms and defined syms in dynamic libraries respectively.
1135      ref_dynamic on the other hand can be set for a symbol defined in
1136      a dynamic library, and def_dynamic may not be set;  When the
1137      definition in a dynamic lib is overridden by a definition in the
1138      executable use of the symbol in the dynamic lib becomes a
1139      reference to the executable symbol.  */
1140   if (newdyn)
1141     {
1142       if (bfd_is_und_section (sec))
1143         {
1144           if (bind != STB_WEAK)
1145             {
1146               h->ref_dynamic_nonweak = 1;
1147               hi->ref_dynamic_nonweak = 1;
1148             }
1149         }
1150       else
1151         {
1152           /* Update the existing symbol only if they match. */
1153           if (*matched)
1154             h->dynamic_def = 1;
1155           hi->dynamic_def = 1;
1156         }
1157     }
1158
1159   /* If we just created the symbol, mark it as being an ELF symbol.
1160      Other than that, there is nothing to do--there is no merge issue
1161      with a newly defined symbol--so we just return.  */
1162
1163   if (h->root.type == bfd_link_hash_new)
1164     {
1165       h->non_elf = 0;
1166       return TRUE;
1167     }
1168
1169   /* In cases involving weak versioned symbols, we may wind up trying
1170      to merge a symbol with itself.  Catch that here, to avoid the
1171      confusion that results if we try to override a symbol with
1172      itself.  The additional tests catch cases like
1173      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1174      dynamic object, which we do want to handle here.  */
1175   if (abfd == oldbfd
1176       && (newweak || oldweak)
1177       && ((abfd->flags & DYNAMIC) == 0
1178           || !h->def_regular))
1179     return TRUE;
1180
1181   olddyn = FALSE;
1182   if (oldbfd != NULL)
1183     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1184   else if (oldsec != NULL)
1185     {
1186       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1187          indices used by MIPS ELF.  */
1188       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1189     }
1190
1191   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1192      respectively, appear to be a definition rather than reference.  */
1193
1194   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1195
1196   olddef = (h->root.type != bfd_link_hash_undefined
1197             && h->root.type != bfd_link_hash_undefweak
1198             && h->root.type != bfd_link_hash_common);
1199
1200   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1201      respectively, appear to be a function.  */
1202
1203   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1204              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1205
1206   oldfunc = (h->type != STT_NOTYPE
1207              && bed->is_function_type (h->type));
1208
1209   /* If creating a default indirect symbol ("foo" or "foo@") from a
1210      dynamic versioned definition ("foo@@") skip doing so if there is
1211      an existing regular definition with a different type.  We don't
1212      want, for example, a "time" variable in the executable overriding
1213      a "time" function in a shared library.  */
1214   if (pold_alignment == NULL
1215       && newdyn
1216       && newdef
1217       && !olddyn
1218       && (olddef || h->root.type == bfd_link_hash_common)
1219       && ELF_ST_TYPE (sym->st_info) != h->type
1220       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1221       && h->type != STT_NOTYPE
1222       && !(newfunc && oldfunc))
1223     {
1224       *skip = TRUE;
1225       return TRUE;
1226     }
1227
1228   /* Check TLS symbols.  We don't check undefined symbols introduced
1229      by "ld -u" which have no type (and oldbfd NULL), and we don't
1230      check symbols from plugins because they also have no type.  */
1231   if (oldbfd != NULL
1232       && (oldbfd->flags & BFD_PLUGIN) == 0
1233       && (abfd->flags & BFD_PLUGIN) == 0
1234       && ELF_ST_TYPE (sym->st_info) != h->type
1235       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1236     {
1237       bfd *ntbfd, *tbfd;
1238       bfd_boolean ntdef, tdef;
1239       asection *ntsec, *tsec;
1240
1241       if (h->type == STT_TLS)
1242         {
1243           ntbfd = abfd;
1244           ntsec = sec;
1245           ntdef = newdef;
1246           tbfd = oldbfd;
1247           tsec = oldsec;
1248           tdef = olddef;
1249         }
1250       else
1251         {
1252           ntbfd = oldbfd;
1253           ntsec = oldsec;
1254           ntdef = olddef;
1255           tbfd = abfd;
1256           tsec = sec;
1257           tdef = newdef;
1258         }
1259
1260       if (tdef && ntdef)
1261         (*_bfd_error_handler)
1262           (_("%s: TLS definition in %B section %A "
1263              "mismatches non-TLS definition in %B section %A"),
1264            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1265       else if (!tdef && !ntdef)
1266         (*_bfd_error_handler)
1267           (_("%s: TLS reference in %B "
1268              "mismatches non-TLS reference in %B"),
1269            tbfd, ntbfd, h->root.root.string);
1270       else if (tdef)
1271         (*_bfd_error_handler)
1272           (_("%s: TLS definition in %B section %A "
1273              "mismatches non-TLS reference in %B"),
1274            tbfd, tsec, ntbfd, h->root.root.string);
1275       else
1276         (*_bfd_error_handler)
1277           (_("%s: TLS reference in %B "
1278              "mismatches non-TLS definition in %B section %A"),
1279            tbfd, ntbfd, ntsec, h->root.root.string);
1280
1281       bfd_set_error (bfd_error_bad_value);
1282       return FALSE;
1283     }
1284
1285   /* If the old symbol has non-default visibility, we ignore the new
1286      definition from a dynamic object.  */
1287   if (newdyn
1288       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1289       && !bfd_is_und_section (sec))
1290     {
1291       *skip = TRUE;
1292       /* Make sure this symbol is dynamic.  */
1293       h->ref_dynamic = 1;
1294       hi->ref_dynamic = 1;
1295       /* A protected symbol has external availability. Make sure it is
1296          recorded as dynamic.
1297
1298          FIXME: Should we check type and size for protected symbol?  */
1299       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1300         return bfd_elf_link_record_dynamic_symbol (info, h);
1301       else
1302         return TRUE;
1303     }
1304   else if (!newdyn
1305            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1306            && h->def_dynamic)
1307     {
1308       /* If the new symbol with non-default visibility comes from a
1309          relocatable file and the old definition comes from a dynamic
1310          object, we remove the old definition.  */
1311       if (hi->root.type == bfd_link_hash_indirect)
1312         {
1313           /* Handle the case where the old dynamic definition is
1314              default versioned.  We need to copy the symbol info from
1315              the symbol with default version to the normal one if it
1316              was referenced before.  */
1317           if (h->ref_regular)
1318             {
1319               hi->root.type = h->root.type;
1320               h->root.type = bfd_link_hash_indirect;
1321               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1322
1323               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1324               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1325                 {
1326                   /* If the new symbol is hidden or internal, completely undo
1327                      any dynamic link state.  */
1328                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1329                   h->forced_local = 0;
1330                   h->ref_dynamic = 0;
1331                 }
1332               else
1333                 h->ref_dynamic = 1;
1334
1335               h->def_dynamic = 0;
1336               /* FIXME: Should we check type and size for protected symbol?  */
1337               h->size = 0;
1338               h->type = 0;
1339
1340               h = hi;
1341             }
1342           else
1343             h = hi;
1344         }
1345
1346       /* If the old symbol was undefined before, then it will still be
1347          on the undefs list.  If the new symbol is undefined or
1348          common, we can't make it bfd_link_hash_new here, because new
1349          undefined or common symbols will be added to the undefs list
1350          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1351          added twice to the undefs list.  Also, if the new symbol is
1352          undefweak then we don't want to lose the strong undef.  */
1353       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1354         {
1355           h->root.type = bfd_link_hash_undefined;
1356           h->root.u.undef.abfd = abfd;
1357         }
1358       else
1359         {
1360           h->root.type = bfd_link_hash_new;
1361           h->root.u.undef.abfd = NULL;
1362         }
1363
1364       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1365         {
1366           /* If the new symbol is hidden or internal, completely undo
1367              any dynamic link state.  */
1368           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1369           h->forced_local = 0;
1370           h->ref_dynamic = 0;
1371         }
1372       else
1373         h->ref_dynamic = 1;
1374       h->def_dynamic = 0;
1375       /* FIXME: Should we check type and size for protected symbol?  */
1376       h->size = 0;
1377       h->type = 0;
1378       return TRUE;
1379     }
1380
1381   /* If a new weak symbol definition comes from a regular file and the
1382      old symbol comes from a dynamic library, we treat the new one as
1383      strong.  Similarly, an old weak symbol definition from a regular
1384      file is treated as strong when the new symbol comes from a dynamic
1385      library.  Further, an old weak symbol from a dynamic library is
1386      treated as strong if the new symbol is from a dynamic library.
1387      This reflects the way glibc's ld.so works.
1388
1389      Do this before setting *type_change_ok or *size_change_ok so that
1390      we warn properly when dynamic library symbols are overridden.  */
1391
1392   if (newdef && !newdyn && olddyn)
1393     newweak = FALSE;
1394   if (olddef && newdyn)
1395     oldweak = FALSE;
1396
1397   /* Allow changes between different types of function symbol.  */
1398   if (newfunc && oldfunc)
1399     *type_change_ok = TRUE;
1400
1401   /* It's OK to change the type if either the existing symbol or the
1402      new symbol is weak.  A type change is also OK if the old symbol
1403      is undefined and the new symbol is defined.  */
1404
1405   if (oldweak
1406       || newweak
1407       || (newdef
1408           && h->root.type == bfd_link_hash_undefined))
1409     *type_change_ok = TRUE;
1410
1411   /* It's OK to change the size if either the existing symbol or the
1412      new symbol is weak, or if the old symbol is undefined.  */
1413
1414   if (*type_change_ok
1415       || h->root.type == bfd_link_hash_undefined)
1416     *size_change_ok = TRUE;
1417
1418   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1419      symbol, respectively, appears to be a common symbol in a dynamic
1420      object.  If a symbol appears in an uninitialized section, and is
1421      not weak, and is not a function, then it may be a common symbol
1422      which was resolved when the dynamic object was created.  We want
1423      to treat such symbols specially, because they raise special
1424      considerations when setting the symbol size: if the symbol
1425      appears as a common symbol in a regular object, and the size in
1426      the regular object is larger, we must make sure that we use the
1427      larger size.  This problematic case can always be avoided in C,
1428      but it must be handled correctly when using Fortran shared
1429      libraries.
1430
1431      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1432      likewise for OLDDYNCOMMON and OLDDEF.
1433
1434      Note that this test is just a heuristic, and that it is quite
1435      possible to have an uninitialized symbol in a shared object which
1436      is really a definition, rather than a common symbol.  This could
1437      lead to some minor confusion when the symbol really is a common
1438      symbol in some regular object.  However, I think it will be
1439      harmless.  */
1440
1441   if (newdyn
1442       && newdef
1443       && !newweak
1444       && (sec->flags & SEC_ALLOC) != 0
1445       && (sec->flags & SEC_LOAD) == 0
1446       && sym->st_size > 0
1447       && !newfunc)
1448     newdyncommon = TRUE;
1449   else
1450     newdyncommon = FALSE;
1451
1452   if (olddyn
1453       && olddef
1454       && h->root.type == bfd_link_hash_defined
1455       && h->def_dynamic
1456       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1457       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1458       && h->size > 0
1459       && !oldfunc)
1460     olddyncommon = TRUE;
1461   else
1462     olddyncommon = FALSE;
1463
1464   /* We now know everything about the old and new symbols.  We ask the
1465      backend to check if we can merge them.  */
1466   if (bed->merge_symbol != NULL)
1467     {
1468       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1469         return FALSE;
1470       sec = *psec;
1471     }
1472
1473   /* If both the old and the new symbols look like common symbols in a
1474      dynamic object, set the size of the symbol to the larger of the
1475      two.  */
1476
1477   if (olddyncommon
1478       && newdyncommon
1479       && sym->st_size != h->size)
1480     {
1481       /* Since we think we have two common symbols, issue a multiple
1482          common warning if desired.  Note that we only warn if the
1483          size is different.  If the size is the same, we simply let
1484          the old symbol override the new one as normally happens with
1485          symbols defined in dynamic objects.  */
1486
1487       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1488                                            bfd_link_hash_common, sym->st_size);
1489       if (sym->st_size > h->size)
1490         h->size = sym->st_size;
1491
1492       *size_change_ok = TRUE;
1493     }
1494
1495   /* If we are looking at a dynamic object, and we have found a
1496      definition, we need to see if the symbol was already defined by
1497      some other object.  If so, we want to use the existing
1498      definition, and we do not want to report a multiple symbol
1499      definition error; we do this by clobbering *PSEC to be
1500      bfd_und_section_ptr.
1501
1502      We treat a common symbol as a definition if the symbol in the
1503      shared library is a function, since common symbols always
1504      represent variables; this can cause confusion in principle, but
1505      any such confusion would seem to indicate an erroneous program or
1506      shared library.  We also permit a common symbol in a regular
1507      object to override a weak symbol in a shared object.  A common
1508      symbol in executable also overrides a symbol in a shared object.  */
1509
1510   if (newdyn
1511       && newdef
1512       && (olddef
1513           || (h->root.type == bfd_link_hash_common
1514               && (newweak
1515                   || newfunc
1516                   || (!olddyn && bfd_link_executable (info))))))
1517     {
1518       *override = TRUE;
1519       newdef = FALSE;
1520       newdyncommon = FALSE;
1521
1522       *psec = sec = bfd_und_section_ptr;
1523       *size_change_ok = TRUE;
1524
1525       /* If we get here when the old symbol is a common symbol, then
1526          we are explicitly letting it override a weak symbol or
1527          function in a dynamic object, and we don't want to warn about
1528          a type change.  If the old symbol is a defined symbol, a type
1529          change warning may still be appropriate.  */
1530
1531       if (h->root.type == bfd_link_hash_common)
1532         *type_change_ok = TRUE;
1533     }
1534
1535   /* Handle the special case of an old common symbol merging with a
1536      new symbol which looks like a common symbol in a shared object.
1537      We change *PSEC and *PVALUE to make the new symbol look like a
1538      common symbol, and let _bfd_generic_link_add_one_symbol do the
1539      right thing.  */
1540
1541   if (newdyncommon
1542       && h->root.type == bfd_link_hash_common)
1543     {
1544       *override = TRUE;
1545       newdef = FALSE;
1546       newdyncommon = FALSE;
1547       *pvalue = sym->st_size;
1548       *psec = sec = bed->common_section (oldsec);
1549       *size_change_ok = TRUE;
1550     }
1551
1552   /* Skip weak definitions of symbols that are already defined.  */
1553   if (newdef && olddef && newweak)
1554     {
1555       /* Don't skip new non-IR weak syms.  */
1556       if (!(oldbfd != NULL
1557             && (oldbfd->flags & BFD_PLUGIN) != 0
1558             && (abfd->flags & BFD_PLUGIN) == 0))
1559         {
1560           newdef = FALSE;
1561           *skip = TRUE;
1562         }
1563
1564       /* Merge st_other.  If the symbol already has a dynamic index,
1565          but visibility says it should not be visible, turn it into a
1566          local symbol.  */
1567       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1568       if (h->dynindx != -1)
1569         switch (ELF_ST_VISIBILITY (h->other))
1570           {
1571           case STV_INTERNAL:
1572           case STV_HIDDEN:
1573             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1574             break;
1575           }
1576     }
1577
1578   /* If the old symbol is from a dynamic object, and the new symbol is
1579      a definition which is not from a dynamic object, then the new
1580      symbol overrides the old symbol.  Symbols from regular files
1581      always take precedence over symbols from dynamic objects, even if
1582      they are defined after the dynamic object in the link.
1583
1584      As above, we again permit a common symbol in a regular object to
1585      override a definition in a shared object if the shared object
1586      symbol is a function or is weak.  */
1587
1588   flip = NULL;
1589   if (!newdyn
1590       && (newdef
1591           || (bfd_is_com_section (sec)
1592               && (oldweak || oldfunc)))
1593       && olddyn
1594       && olddef
1595       && h->def_dynamic)
1596     {
1597       /* Change the hash table entry to undefined, and let
1598          _bfd_generic_link_add_one_symbol do the right thing with the
1599          new definition.  */
1600
1601       h->root.type = bfd_link_hash_undefined;
1602       h->root.u.undef.abfd = h->root.u.def.section->owner;
1603       *size_change_ok = TRUE;
1604
1605       olddef = FALSE;
1606       olddyncommon = FALSE;
1607
1608       /* We again permit a type change when a common symbol may be
1609          overriding a function.  */
1610
1611       if (bfd_is_com_section (sec))
1612         {
1613           if (oldfunc)
1614             {
1615               /* If a common symbol overrides a function, make sure
1616                  that it isn't defined dynamically nor has type
1617                  function.  */
1618               h->def_dynamic = 0;
1619               h->type = STT_NOTYPE;
1620             }
1621           *type_change_ok = TRUE;
1622         }
1623
1624       if (hi->root.type == bfd_link_hash_indirect)
1625         flip = hi;
1626       else
1627         /* This union may have been set to be non-NULL when this symbol
1628            was seen in a dynamic object.  We must force the union to be
1629            NULL, so that it is correct for a regular symbol.  */
1630         h->verinfo.vertree = NULL;
1631     }
1632
1633   /* Handle the special case of a new common symbol merging with an
1634      old symbol that looks like it might be a common symbol defined in
1635      a shared object.  Note that we have already handled the case in
1636      which a new common symbol should simply override the definition
1637      in the shared library.  */
1638
1639   if (! newdyn
1640       && bfd_is_com_section (sec)
1641       && olddyncommon)
1642     {
1643       /* It would be best if we could set the hash table entry to a
1644          common symbol, but we don't know what to use for the section
1645          or the alignment.  */
1646       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1647                                            bfd_link_hash_common, sym->st_size);
1648
1649       /* If the presumed common symbol in the dynamic object is
1650          larger, pretend that the new symbol has its size.  */
1651
1652       if (h->size > *pvalue)
1653         *pvalue = h->size;
1654
1655       /* We need to remember the alignment required by the symbol
1656          in the dynamic object.  */
1657       BFD_ASSERT (pold_alignment);
1658       *pold_alignment = h->root.u.def.section->alignment_power;
1659
1660       olddef = FALSE;
1661       olddyncommon = FALSE;
1662
1663       h->root.type = bfd_link_hash_undefined;
1664       h->root.u.undef.abfd = h->root.u.def.section->owner;
1665
1666       *size_change_ok = TRUE;
1667       *type_change_ok = TRUE;
1668
1669       if (hi->root.type == bfd_link_hash_indirect)
1670         flip = hi;
1671       else
1672         h->verinfo.vertree = NULL;
1673     }
1674
1675   if (flip != NULL)
1676     {
1677       /* Handle the case where we had a versioned symbol in a dynamic
1678          library and now find a definition in a normal object.  In this
1679          case, we make the versioned symbol point to the normal one.  */
1680       flip->root.type = h->root.type;
1681       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1682       h->root.type = bfd_link_hash_indirect;
1683       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1684       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1685       if (h->def_dynamic)
1686         {
1687           h->def_dynamic = 0;
1688           flip->ref_dynamic = 1;
1689         }
1690     }
1691
1692   return TRUE;
1693 }
1694
1695 /* This function is called to create an indirect symbol from the
1696    default for the symbol with the default version if needed. The
1697    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1698    set DYNSYM if the new indirect symbol is dynamic.  */
1699
1700 static bfd_boolean
1701 _bfd_elf_add_default_symbol (bfd *abfd,
1702                              struct bfd_link_info *info,
1703                              struct elf_link_hash_entry *h,
1704                              const char *name,
1705                              Elf_Internal_Sym *sym,
1706                              asection *sec,
1707                              bfd_vma value,
1708                              bfd **poldbfd,
1709                              bfd_boolean *dynsym)
1710 {
1711   bfd_boolean type_change_ok;
1712   bfd_boolean size_change_ok;
1713   bfd_boolean skip;
1714   char *shortname;
1715   struct elf_link_hash_entry *hi;
1716   struct bfd_link_hash_entry *bh;
1717   const struct elf_backend_data *bed;
1718   bfd_boolean collect;
1719   bfd_boolean dynamic;
1720   bfd_boolean override;
1721   char *p;
1722   size_t len, shortlen;
1723   asection *tmp_sec;
1724   bfd_boolean matched;
1725
1726   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1727     return TRUE;
1728
1729   /* If this symbol has a version, and it is the default version, we
1730      create an indirect symbol from the default name to the fully
1731      decorated name.  This will cause external references which do not
1732      specify a version to be bound to this version of the symbol.  */
1733   p = strchr (name, ELF_VER_CHR);
1734   if (h->versioned == unknown)
1735     {
1736       if (p == NULL)
1737         {
1738           h->versioned = unversioned;
1739           return TRUE;
1740         }
1741       else
1742         {
1743           if (p[1] != ELF_VER_CHR)
1744             {
1745               h->versioned = versioned_hidden;
1746               return TRUE;
1747             }
1748           else
1749             h->versioned = versioned;
1750         }
1751     }
1752   else
1753     {
1754       /* PR ld/19073: We may see an unversioned definition after the
1755          default version.  */
1756       if (p == NULL)
1757         return TRUE;
1758     }
1759
1760   bed = get_elf_backend_data (abfd);
1761   collect = bed->collect;
1762   dynamic = (abfd->flags & DYNAMIC) != 0;
1763
1764   shortlen = p - name;
1765   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1766   if (shortname == NULL)
1767     return FALSE;
1768   memcpy (shortname, name, shortlen);
1769   shortname[shortlen] = '\0';
1770
1771   /* We are going to create a new symbol.  Merge it with any existing
1772      symbol with this name.  For the purposes of the merge, act as
1773      though we were defining the symbol we just defined, although we
1774      actually going to define an indirect symbol.  */
1775   type_change_ok = FALSE;
1776   size_change_ok = FALSE;
1777   matched = TRUE;
1778   tmp_sec = sec;
1779   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1780                               &hi, poldbfd, NULL, NULL, &skip, &override,
1781                               &type_change_ok, &size_change_ok, &matched))
1782     return FALSE;
1783
1784   if (skip)
1785     goto nondefault;
1786
1787   if (hi->def_regular)
1788     {
1789       /* If the undecorated symbol will have a version added by a
1790          script different to H, then don't indirect to/from the
1791          undecorated symbol.  This isn't ideal because we may not yet
1792          have seen symbol versions, if given by a script on the
1793          command line rather than via --version-script.  */
1794       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1795         {
1796           bfd_boolean hide;
1797
1798           hi->verinfo.vertree
1799             = bfd_find_version_for_sym (info->version_info,
1800                                         hi->root.root.string, &hide);
1801           if (hi->verinfo.vertree != NULL && hide)
1802             {
1803               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1804               goto nondefault;
1805             }
1806         }
1807       if (hi->verinfo.vertree != NULL
1808           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1809         goto nondefault;
1810     }
1811
1812   if (! override)
1813     {
1814       /* Add the default symbol if not performing a relocatable link.  */
1815       if (! bfd_link_relocatable (info))
1816         {
1817           bh = &hi->root;
1818           if (! (_bfd_generic_link_add_one_symbol
1819                  (info, abfd, shortname, BSF_INDIRECT,
1820                   bfd_ind_section_ptr,
1821                   0, name, FALSE, collect, &bh)))
1822             return FALSE;
1823           hi = (struct elf_link_hash_entry *) bh;
1824         }
1825     }
1826   else
1827     {
1828       /* In this case the symbol named SHORTNAME is overriding the
1829          indirect symbol we want to add.  We were planning on making
1830          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1831          is the name without a version.  NAME is the fully versioned
1832          name, and it is the default version.
1833
1834          Overriding means that we already saw a definition for the
1835          symbol SHORTNAME in a regular object, and it is overriding
1836          the symbol defined in the dynamic object.
1837
1838          When this happens, we actually want to change NAME, the
1839          symbol we just added, to refer to SHORTNAME.  This will cause
1840          references to NAME in the shared object to become references
1841          to SHORTNAME in the regular object.  This is what we expect
1842          when we override a function in a shared object: that the
1843          references in the shared object will be mapped to the
1844          definition in the regular object.  */
1845
1846       while (hi->root.type == bfd_link_hash_indirect
1847              || hi->root.type == bfd_link_hash_warning)
1848         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1849
1850       h->root.type = bfd_link_hash_indirect;
1851       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1852       if (h->def_dynamic)
1853         {
1854           h->def_dynamic = 0;
1855           hi->ref_dynamic = 1;
1856           if (hi->ref_regular
1857               || hi->def_regular)
1858             {
1859               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1860                 return FALSE;
1861             }
1862         }
1863
1864       /* Now set HI to H, so that the following code will set the
1865          other fields correctly.  */
1866       hi = h;
1867     }
1868
1869   /* Check if HI is a warning symbol.  */
1870   if (hi->root.type == bfd_link_hash_warning)
1871     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1872
1873   /* If there is a duplicate definition somewhere, then HI may not
1874      point to an indirect symbol.  We will have reported an error to
1875      the user in that case.  */
1876
1877   if (hi->root.type == bfd_link_hash_indirect)
1878     {
1879       struct elf_link_hash_entry *ht;
1880
1881       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1882       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1883
1884       /* A reference to the SHORTNAME symbol from a dynamic library
1885          will be satisfied by the versioned symbol at runtime.  In
1886          effect, we have a reference to the versioned symbol.  */
1887       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1888       hi->dynamic_def |= ht->dynamic_def;
1889
1890       /* See if the new flags lead us to realize that the symbol must
1891          be dynamic.  */
1892       if (! *dynsym)
1893         {
1894           if (! dynamic)
1895             {
1896               if (! bfd_link_executable (info)
1897                   || hi->def_dynamic
1898                   || hi->ref_dynamic)
1899                 *dynsym = TRUE;
1900             }
1901           else
1902             {
1903               if (hi->ref_regular)
1904                 *dynsym = TRUE;
1905             }
1906         }
1907     }
1908
1909   /* We also need to define an indirection from the nondefault version
1910      of the symbol.  */
1911
1912 nondefault:
1913   len = strlen (name);
1914   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1915   if (shortname == NULL)
1916     return FALSE;
1917   memcpy (shortname, name, shortlen);
1918   memcpy (shortname + shortlen, p + 1, len - shortlen);
1919
1920   /* Once again, merge with any existing symbol.  */
1921   type_change_ok = FALSE;
1922   size_change_ok = FALSE;
1923   tmp_sec = sec;
1924   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1925                               &hi, poldbfd, NULL, NULL, &skip, &override,
1926                               &type_change_ok, &size_change_ok, &matched))
1927     return FALSE;
1928
1929   if (skip)
1930     return TRUE;
1931
1932   if (override)
1933     {
1934       /* Here SHORTNAME is a versioned name, so we don't expect to see
1935          the type of override we do in the case above unless it is
1936          overridden by a versioned definition.  */
1937       if (hi->root.type != bfd_link_hash_defined
1938           && hi->root.type != bfd_link_hash_defweak)
1939         (*_bfd_error_handler)
1940           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1941            abfd, shortname);
1942     }
1943   else
1944     {
1945       bh = &hi->root;
1946       if (! (_bfd_generic_link_add_one_symbol
1947              (info, abfd, shortname, BSF_INDIRECT,
1948               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1949         return FALSE;
1950       hi = (struct elf_link_hash_entry *) bh;
1951
1952       /* If there is a duplicate definition somewhere, then HI may not
1953          point to an indirect symbol.  We will have reported an error
1954          to the user in that case.  */
1955
1956       if (hi->root.type == bfd_link_hash_indirect)
1957         {
1958           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1959           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1960           hi->dynamic_def |= h->dynamic_def;
1961
1962           /* See if the new flags lead us to realize that the symbol
1963              must be dynamic.  */
1964           if (! *dynsym)
1965             {
1966               if (! dynamic)
1967                 {
1968                   if (! bfd_link_executable (info)
1969                       || hi->ref_dynamic)
1970                     *dynsym = TRUE;
1971                 }
1972               else
1973                 {
1974                   if (hi->ref_regular)
1975                     *dynsym = TRUE;
1976                 }
1977             }
1978         }
1979     }
1980
1981   return TRUE;
1982 }
1983 \f
1984 /* This routine is used to export all defined symbols into the dynamic
1985    symbol table.  It is called via elf_link_hash_traverse.  */
1986
1987 static bfd_boolean
1988 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1989 {
1990   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1991
1992   /* Ignore indirect symbols.  These are added by the versioning code.  */
1993   if (h->root.type == bfd_link_hash_indirect)
1994     return TRUE;
1995
1996   /* Ignore this if we won't export it.  */
1997   if (!eif->info->export_dynamic && !h->dynamic)
1998     return TRUE;
1999
2000   if (h->dynindx == -1
2001       && (h->def_regular || h->ref_regular)
2002       && ! bfd_hide_sym_by_version (eif->info->version_info,
2003                                     h->root.root.string))
2004     {
2005       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2006         {
2007           eif->failed = TRUE;
2008           return FALSE;
2009         }
2010     }
2011
2012   return TRUE;
2013 }
2014 \f
2015 /* Look through the symbols which are defined in other shared
2016    libraries and referenced here.  Update the list of version
2017    dependencies.  This will be put into the .gnu.version_r section.
2018    This function is called via elf_link_hash_traverse.  */
2019
2020 static bfd_boolean
2021 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2022                                          void *data)
2023 {
2024   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2025   Elf_Internal_Verneed *t;
2026   Elf_Internal_Vernaux *a;
2027   bfd_size_type amt;
2028
2029   /* We only care about symbols defined in shared objects with version
2030      information.  */
2031   if (!h->def_dynamic
2032       || h->def_regular
2033       || h->dynindx == -1
2034       || h->verinfo.verdef == NULL
2035       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2036           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2037     return TRUE;
2038
2039   /* See if we already know about this version.  */
2040   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2041        t != NULL;
2042        t = t->vn_nextref)
2043     {
2044       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2045         continue;
2046
2047       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2048         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2049           return TRUE;
2050
2051       break;
2052     }
2053
2054   /* This is a new version.  Add it to tree we are building.  */
2055
2056   if (t == NULL)
2057     {
2058       amt = sizeof *t;
2059       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2060       if (t == NULL)
2061         {
2062           rinfo->failed = TRUE;
2063           return FALSE;
2064         }
2065
2066       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2067       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2068       elf_tdata (rinfo->info->output_bfd)->verref = t;
2069     }
2070
2071   amt = sizeof *a;
2072   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2073   if (a == NULL)
2074     {
2075       rinfo->failed = TRUE;
2076       return FALSE;
2077     }
2078
2079   /* Note that we are copying a string pointer here, and testing it
2080      above.  If bfd_elf_string_from_elf_section is ever changed to
2081      discard the string data when low in memory, this will have to be
2082      fixed.  */
2083   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2084
2085   a->vna_flags = h->verinfo.verdef->vd_flags;
2086   a->vna_nextptr = t->vn_auxptr;
2087
2088   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2089   ++rinfo->vers;
2090
2091   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2092
2093   t->vn_auxptr = a;
2094
2095   return TRUE;
2096 }
2097
2098 /* Figure out appropriate versions for all the symbols.  We may not
2099    have the version number script until we have read all of the input
2100    files, so until that point we don't know which symbols should be
2101    local.  This function is called via elf_link_hash_traverse.  */
2102
2103 static bfd_boolean
2104 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2105 {
2106   struct elf_info_failed *sinfo;
2107   struct bfd_link_info *info;
2108   const struct elf_backend_data *bed;
2109   struct elf_info_failed eif;
2110   char *p;
2111
2112   sinfo = (struct elf_info_failed *) data;
2113   info = sinfo->info;
2114
2115   /* Fix the symbol flags.  */
2116   eif.failed = FALSE;
2117   eif.info = info;
2118   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2119     {
2120       if (eif.failed)
2121         sinfo->failed = TRUE;
2122       return FALSE;
2123     }
2124
2125   /* We only need version numbers for symbols defined in regular
2126      objects.  */
2127   if (!h->def_regular)
2128     return TRUE;
2129
2130   bed = get_elf_backend_data (info->output_bfd);
2131   p = strchr (h->root.root.string, ELF_VER_CHR);
2132   if (p != NULL && h->verinfo.vertree == NULL)
2133     {
2134       struct bfd_elf_version_tree *t;
2135
2136       ++p;
2137       if (*p == ELF_VER_CHR)
2138         ++p;
2139
2140       /* If there is no version string, we can just return out.  */
2141       if (*p == '\0')
2142         return TRUE;
2143
2144       /* Look for the version.  If we find it, it is no longer weak.  */
2145       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2146         {
2147           if (strcmp (t->name, p) == 0)
2148             {
2149               size_t len;
2150               char *alc;
2151               struct bfd_elf_version_expr *d;
2152
2153               len = p - h->root.root.string;
2154               alc = (char *) bfd_malloc (len);
2155               if (alc == NULL)
2156                 {
2157                   sinfo->failed = TRUE;
2158                   return FALSE;
2159                 }
2160               memcpy (alc, h->root.root.string, len - 1);
2161               alc[len - 1] = '\0';
2162               if (alc[len - 2] == ELF_VER_CHR)
2163                 alc[len - 2] = '\0';
2164
2165               h->verinfo.vertree = t;
2166               t->used = TRUE;
2167               d = NULL;
2168
2169               if (t->globals.list != NULL)
2170                 d = (*t->match) (&t->globals, NULL, alc);
2171
2172               /* See if there is anything to force this symbol to
2173                  local scope.  */
2174               if (d == NULL && t->locals.list != NULL)
2175                 {
2176                   d = (*t->match) (&t->locals, NULL, alc);
2177                   if (d != NULL
2178                       && h->dynindx != -1
2179                       && ! info->export_dynamic)
2180                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2181                 }
2182
2183               free (alc);
2184               break;
2185             }
2186         }
2187
2188       /* If we are building an application, we need to create a
2189          version node for this version.  */
2190       if (t == NULL && bfd_link_executable (info))
2191         {
2192           struct bfd_elf_version_tree **pp;
2193           int version_index;
2194
2195           /* If we aren't going to export this symbol, we don't need
2196              to worry about it.  */
2197           if (h->dynindx == -1)
2198             return TRUE;
2199
2200           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2201                                                           sizeof *t);
2202           if (t == NULL)
2203             {
2204               sinfo->failed = TRUE;
2205               return FALSE;
2206             }
2207
2208           t->name = p;
2209           t->name_indx = (unsigned int) -1;
2210           t->used = TRUE;
2211
2212           version_index = 1;
2213           /* Don't count anonymous version tag.  */
2214           if (sinfo->info->version_info != NULL
2215               && sinfo->info->version_info->vernum == 0)
2216             version_index = 0;
2217           for (pp = &sinfo->info->version_info;
2218                *pp != NULL;
2219                pp = &(*pp)->next)
2220             ++version_index;
2221           t->vernum = version_index;
2222
2223           *pp = t;
2224
2225           h->verinfo.vertree = t;
2226         }
2227       else if (t == NULL)
2228         {
2229           /* We could not find the version for a symbol when
2230              generating a shared archive.  Return an error.  */
2231           (*_bfd_error_handler)
2232             (_("%B: version node not found for symbol %s"),
2233              info->output_bfd, h->root.root.string);
2234           bfd_set_error (bfd_error_bad_value);
2235           sinfo->failed = TRUE;
2236           return FALSE;
2237         }
2238     }
2239
2240   /* If we don't have a version for this symbol, see if we can find
2241      something.  */
2242   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2243     {
2244       bfd_boolean hide;
2245
2246       h->verinfo.vertree
2247         = bfd_find_version_for_sym (sinfo->info->version_info,
2248                                     h->root.root.string, &hide);
2249       if (h->verinfo.vertree != NULL && hide)
2250         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2251     }
2252
2253   return TRUE;
2254 }
2255 \f
2256 /* Read and swap the relocs from the section indicated by SHDR.  This
2257    may be either a REL or a RELA section.  The relocations are
2258    translated into RELA relocations and stored in INTERNAL_RELOCS,
2259    which should have already been allocated to contain enough space.
2260    The EXTERNAL_RELOCS are a buffer where the external form of the
2261    relocations should be stored.
2262
2263    Returns FALSE if something goes wrong.  */
2264
2265 static bfd_boolean
2266 elf_link_read_relocs_from_section (bfd *abfd,
2267                                    asection *sec,
2268                                    Elf_Internal_Shdr *shdr,
2269                                    void *external_relocs,
2270                                    Elf_Internal_Rela *internal_relocs)
2271 {
2272   const struct elf_backend_data *bed;
2273   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2274   const bfd_byte *erela;
2275   const bfd_byte *erelaend;
2276   Elf_Internal_Rela *irela;
2277   Elf_Internal_Shdr *symtab_hdr;
2278   size_t nsyms;
2279
2280   /* Position ourselves at the start of the section.  */
2281   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2282     return FALSE;
2283
2284   /* Read the relocations.  */
2285   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2286     return FALSE;
2287
2288   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2289   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2290
2291   bed = get_elf_backend_data (abfd);
2292
2293   /* Convert the external relocations to the internal format.  */
2294   if (shdr->sh_entsize == bed->s->sizeof_rel)
2295     swap_in = bed->s->swap_reloc_in;
2296   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2297     swap_in = bed->s->swap_reloca_in;
2298   else
2299     {
2300       bfd_set_error (bfd_error_wrong_format);
2301       return FALSE;
2302     }
2303
2304   erela = (const bfd_byte *) external_relocs;
2305   erelaend = erela + shdr->sh_size;
2306   irela = internal_relocs;
2307   while (erela < erelaend)
2308     {
2309       bfd_vma r_symndx;
2310
2311       (*swap_in) (abfd, erela, irela);
2312       r_symndx = ELF32_R_SYM (irela->r_info);
2313       if (bed->s->arch_size == 64)
2314         r_symndx >>= 24;
2315       if (nsyms > 0)
2316         {
2317           if ((size_t) r_symndx >= nsyms)
2318             {
2319               (*_bfd_error_handler)
2320                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2321                    " for offset 0x%lx in section `%A'"),
2322                  abfd, sec,
2323                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2324               bfd_set_error (bfd_error_bad_value);
2325               return FALSE;
2326             }
2327         }
2328       else if (r_symndx != STN_UNDEF)
2329         {
2330           (*_bfd_error_handler)
2331             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2332                " when the object file has no symbol table"),
2333              abfd, sec,
2334              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2335           bfd_set_error (bfd_error_bad_value);
2336           return FALSE;
2337         }
2338       irela += bed->s->int_rels_per_ext_rel;
2339       erela += shdr->sh_entsize;
2340     }
2341
2342   return TRUE;
2343 }
2344
2345 /* Read and swap the relocs for a section O.  They may have been
2346    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2347    not NULL, they are used as buffers to read into.  They are known to
2348    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2349    the return value is allocated using either malloc or bfd_alloc,
2350    according to the KEEP_MEMORY argument.  If O has two relocation
2351    sections (both REL and RELA relocations), then the REL_HDR
2352    relocations will appear first in INTERNAL_RELOCS, followed by the
2353    RELA_HDR relocations.  */
2354
2355 Elf_Internal_Rela *
2356 _bfd_elf_link_read_relocs (bfd *abfd,
2357                            asection *o,
2358                            void *external_relocs,
2359                            Elf_Internal_Rela *internal_relocs,
2360                            bfd_boolean keep_memory)
2361 {
2362   void *alloc1 = NULL;
2363   Elf_Internal_Rela *alloc2 = NULL;
2364   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2365   struct bfd_elf_section_data *esdo = elf_section_data (o);
2366   Elf_Internal_Rela *internal_rela_relocs;
2367
2368   if (esdo->relocs != NULL)
2369     return esdo->relocs;
2370
2371   if (o->reloc_count == 0)
2372     return NULL;
2373
2374   if (internal_relocs == NULL)
2375     {
2376       bfd_size_type size;
2377
2378       size = o->reloc_count;
2379       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2380       if (keep_memory)
2381         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2382       else
2383         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2384       if (internal_relocs == NULL)
2385         goto error_return;
2386     }
2387
2388   if (external_relocs == NULL)
2389     {
2390       bfd_size_type size = 0;
2391
2392       if (esdo->rel.hdr)
2393         size += esdo->rel.hdr->sh_size;
2394       if (esdo->rela.hdr)
2395         size += esdo->rela.hdr->sh_size;
2396
2397       alloc1 = bfd_malloc (size);
2398       if (alloc1 == NULL)
2399         goto error_return;
2400       external_relocs = alloc1;
2401     }
2402
2403   internal_rela_relocs = internal_relocs;
2404   if (esdo->rel.hdr)
2405     {
2406       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2407                                               external_relocs,
2408                                               internal_relocs))
2409         goto error_return;
2410       external_relocs = (((bfd_byte *) external_relocs)
2411                          + esdo->rel.hdr->sh_size);
2412       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2413                                * bed->s->int_rels_per_ext_rel);
2414     }
2415
2416   if (esdo->rela.hdr
2417       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2418                                               external_relocs,
2419                                               internal_rela_relocs)))
2420     goto error_return;
2421
2422   /* Cache the results for next time, if we can.  */
2423   if (keep_memory)
2424     esdo->relocs = internal_relocs;
2425
2426   if (alloc1 != NULL)
2427     free (alloc1);
2428
2429   /* Don't free alloc2, since if it was allocated we are passing it
2430      back (under the name of internal_relocs).  */
2431
2432   return internal_relocs;
2433
2434  error_return:
2435   if (alloc1 != NULL)
2436     free (alloc1);
2437   if (alloc2 != NULL)
2438     {
2439       if (keep_memory)
2440         bfd_release (abfd, alloc2);
2441       else
2442         free (alloc2);
2443     }
2444   return NULL;
2445 }
2446
2447 /* Compute the size of, and allocate space for, REL_HDR which is the
2448    section header for a section containing relocations for O.  */
2449
2450 static bfd_boolean
2451 _bfd_elf_link_size_reloc_section (bfd *abfd,
2452                                   struct bfd_elf_section_reloc_data *reldata)
2453 {
2454   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2455
2456   /* That allows us to calculate the size of the section.  */
2457   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2458
2459   /* The contents field must last into write_object_contents, so we
2460      allocate it with bfd_alloc rather than malloc.  Also since we
2461      cannot be sure that the contents will actually be filled in,
2462      we zero the allocated space.  */
2463   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2464   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2465     return FALSE;
2466
2467   if (reldata->hashes == NULL && reldata->count)
2468     {
2469       struct elf_link_hash_entry **p;
2470
2471       p = ((struct elf_link_hash_entry **)
2472            bfd_zmalloc (reldata->count * sizeof (*p)));
2473       if (p == NULL)
2474         return FALSE;
2475
2476       reldata->hashes = p;
2477     }
2478
2479   return TRUE;
2480 }
2481
2482 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2483    originated from the section given by INPUT_REL_HDR) to the
2484    OUTPUT_BFD.  */
2485
2486 bfd_boolean
2487 _bfd_elf_link_output_relocs (bfd *output_bfd,
2488                              asection *input_section,
2489                              Elf_Internal_Shdr *input_rel_hdr,
2490                              Elf_Internal_Rela *internal_relocs,
2491                              struct elf_link_hash_entry **rel_hash
2492                                ATTRIBUTE_UNUSED)
2493 {
2494   Elf_Internal_Rela *irela;
2495   Elf_Internal_Rela *irelaend;
2496   bfd_byte *erel;
2497   struct bfd_elf_section_reloc_data *output_reldata;
2498   asection *output_section;
2499   const struct elf_backend_data *bed;
2500   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2501   struct bfd_elf_section_data *esdo;
2502
2503   output_section = input_section->output_section;
2504
2505   bed = get_elf_backend_data (output_bfd);
2506   esdo = elf_section_data (output_section);
2507   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2508     {
2509       output_reldata = &esdo->rel;
2510       swap_out = bed->s->swap_reloc_out;
2511     }
2512   else if (esdo->rela.hdr
2513            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2514     {
2515       output_reldata = &esdo->rela;
2516       swap_out = bed->s->swap_reloca_out;
2517     }
2518   else
2519     {
2520       (*_bfd_error_handler)
2521         (_("%B: relocation size mismatch in %B section %A"),
2522          output_bfd, input_section->owner, input_section);
2523       bfd_set_error (bfd_error_wrong_format);
2524       return FALSE;
2525     }
2526
2527   erel = output_reldata->hdr->contents;
2528   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2529   irela = internal_relocs;
2530   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2531                       * bed->s->int_rels_per_ext_rel);
2532   while (irela < irelaend)
2533     {
2534       (*swap_out) (output_bfd, irela, erel);
2535       irela += bed->s->int_rels_per_ext_rel;
2536       erel += input_rel_hdr->sh_entsize;
2537     }
2538
2539   /* Bump the counter, so that we know where to add the next set of
2540      relocations.  */
2541   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2542
2543   return TRUE;
2544 }
2545 \f
2546 /* Make weak undefined symbols in PIE dynamic.  */
2547
2548 bfd_boolean
2549 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2550                                  struct elf_link_hash_entry *h)
2551 {
2552   if (bfd_link_pie (info)
2553       && h->dynindx == -1
2554       && h->root.type == bfd_link_hash_undefweak)
2555     return bfd_elf_link_record_dynamic_symbol (info, h);
2556
2557   return TRUE;
2558 }
2559
2560 /* Fix up the flags for a symbol.  This handles various cases which
2561    can only be fixed after all the input files are seen.  This is
2562    currently called by both adjust_dynamic_symbol and
2563    assign_sym_version, which is unnecessary but perhaps more robust in
2564    the face of future changes.  */
2565
2566 static bfd_boolean
2567 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2568                            struct elf_info_failed *eif)
2569 {
2570   const struct elf_backend_data *bed;
2571
2572   /* If this symbol was mentioned in a non-ELF file, try to set
2573      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2574      permit a non-ELF file to correctly refer to a symbol defined in
2575      an ELF dynamic object.  */
2576   if (h->non_elf)
2577     {
2578       while (h->root.type == bfd_link_hash_indirect)
2579         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2580
2581       if (h->root.type != bfd_link_hash_defined
2582           && h->root.type != bfd_link_hash_defweak)
2583         {
2584           h->ref_regular = 1;
2585           h->ref_regular_nonweak = 1;
2586         }
2587       else
2588         {
2589           if (h->root.u.def.section->owner != NULL
2590               && (bfd_get_flavour (h->root.u.def.section->owner)
2591                   == bfd_target_elf_flavour))
2592             {
2593               h->ref_regular = 1;
2594               h->ref_regular_nonweak = 1;
2595             }
2596           else
2597             h->def_regular = 1;
2598         }
2599
2600       if (h->dynindx == -1
2601           && (h->def_dynamic
2602               || h->ref_dynamic))
2603         {
2604           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2605             {
2606               eif->failed = TRUE;
2607               return FALSE;
2608             }
2609         }
2610     }
2611   else
2612     {
2613       /* Unfortunately, NON_ELF is only correct if the symbol
2614          was first seen in a non-ELF file.  Fortunately, if the symbol
2615          was first seen in an ELF file, we're probably OK unless the
2616          symbol was defined in a non-ELF file.  Catch that case here.
2617          FIXME: We're still in trouble if the symbol was first seen in
2618          a dynamic object, and then later in a non-ELF regular object.  */
2619       if ((h->root.type == bfd_link_hash_defined
2620            || h->root.type == bfd_link_hash_defweak)
2621           && !h->def_regular
2622           && (h->root.u.def.section->owner != NULL
2623               ? (bfd_get_flavour (h->root.u.def.section->owner)
2624                  != bfd_target_elf_flavour)
2625               : (bfd_is_abs_section (h->root.u.def.section)
2626                  && !h->def_dynamic)))
2627         h->def_regular = 1;
2628     }
2629
2630   /* Backend specific symbol fixup.  */
2631   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2632   if (bed->elf_backend_fixup_symbol
2633       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2634     return FALSE;
2635
2636   /* If this is a final link, and the symbol was defined as a common
2637      symbol in a regular object file, and there was no definition in
2638      any dynamic object, then the linker will have allocated space for
2639      the symbol in a common section but the DEF_REGULAR
2640      flag will not have been set.  */
2641   if (h->root.type == bfd_link_hash_defined
2642       && !h->def_regular
2643       && h->ref_regular
2644       && !h->def_dynamic
2645       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2646     h->def_regular = 1;
2647
2648   /* If -Bsymbolic was used (which means to bind references to global
2649      symbols to the definition within the shared object), and this
2650      symbol was defined in a regular object, then it actually doesn't
2651      need a PLT entry.  Likewise, if the symbol has non-default
2652      visibility.  If the symbol has hidden or internal visibility, we
2653      will force it local.  */
2654   if (h->needs_plt
2655       && bfd_link_pic (eif->info)
2656       && is_elf_hash_table (eif->info->hash)
2657       && (SYMBOLIC_BIND (eif->info, h)
2658           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2659       && h->def_regular)
2660     {
2661       bfd_boolean force_local;
2662
2663       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2664                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2665       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2666     }
2667
2668   /* If a weak undefined symbol has non-default visibility, we also
2669      hide it from the dynamic linker.  */
2670   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2671       && h->root.type == bfd_link_hash_undefweak)
2672     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2673
2674   /* If this is a weak defined symbol in a dynamic object, and we know
2675      the real definition in the dynamic object, copy interesting flags
2676      over to the real definition.  */
2677   if (h->u.weakdef != NULL)
2678     {
2679       /* If the real definition is defined by a regular object file,
2680          don't do anything special.  See the longer description in
2681          _bfd_elf_adjust_dynamic_symbol, below.  */
2682       if (h->u.weakdef->def_regular)
2683         h->u.weakdef = NULL;
2684       else
2685         {
2686           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2687
2688           while (h->root.type == bfd_link_hash_indirect)
2689             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2690
2691           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2692                       || h->root.type == bfd_link_hash_defweak);
2693           BFD_ASSERT (weakdef->def_dynamic);
2694           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2695                       || weakdef->root.type == bfd_link_hash_defweak);
2696           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2697         }
2698     }
2699
2700   return TRUE;
2701 }
2702
2703 /* Make the backend pick a good value for a dynamic symbol.  This is
2704    called via elf_link_hash_traverse, and also calls itself
2705    recursively.  */
2706
2707 static bfd_boolean
2708 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2709 {
2710   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2711   bfd *dynobj;
2712   const struct elf_backend_data *bed;
2713
2714   if (! is_elf_hash_table (eif->info->hash))
2715     return FALSE;
2716
2717   /* Ignore indirect symbols.  These are added by the versioning code.  */
2718   if (h->root.type == bfd_link_hash_indirect)
2719     return TRUE;
2720
2721   /* Fix the symbol flags.  */
2722   if (! _bfd_elf_fix_symbol_flags (h, eif))
2723     return FALSE;
2724
2725   /* If this symbol does not require a PLT entry, and it is not
2726      defined by a dynamic object, or is not referenced by a regular
2727      object, ignore it.  We do have to handle a weak defined symbol,
2728      even if no regular object refers to it, if we decided to add it
2729      to the dynamic symbol table.  FIXME: Do we normally need to worry
2730      about symbols which are defined by one dynamic object and
2731      referenced by another one?  */
2732   if (!h->needs_plt
2733       && h->type != STT_GNU_IFUNC
2734       && (h->def_regular
2735           || !h->def_dynamic
2736           || (!h->ref_regular
2737               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2738     {
2739       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2740       return TRUE;
2741     }
2742
2743   /* If we've already adjusted this symbol, don't do it again.  This
2744      can happen via a recursive call.  */
2745   if (h->dynamic_adjusted)
2746     return TRUE;
2747
2748   /* Don't look at this symbol again.  Note that we must set this
2749      after checking the above conditions, because we may look at a
2750      symbol once, decide not to do anything, and then get called
2751      recursively later after REF_REGULAR is set below.  */
2752   h->dynamic_adjusted = 1;
2753
2754   /* If this is a weak definition, and we know a real definition, and
2755      the real symbol is not itself defined by a regular object file,
2756      then get a good value for the real definition.  We handle the
2757      real symbol first, for the convenience of the backend routine.
2758
2759      Note that there is a confusing case here.  If the real definition
2760      is defined by a regular object file, we don't get the real symbol
2761      from the dynamic object, but we do get the weak symbol.  If the
2762      processor backend uses a COPY reloc, then if some routine in the
2763      dynamic object changes the real symbol, we will not see that
2764      change in the corresponding weak symbol.  This is the way other
2765      ELF linkers work as well, and seems to be a result of the shared
2766      library model.
2767
2768      I will clarify this issue.  Most SVR4 shared libraries define the
2769      variable _timezone and define timezone as a weak synonym.  The
2770      tzset call changes _timezone.  If you write
2771        extern int timezone;
2772        int _timezone = 5;
2773        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2774      you might expect that, since timezone is a synonym for _timezone,
2775      the same number will print both times.  However, if the processor
2776      backend uses a COPY reloc, then actually timezone will be copied
2777      into your process image, and, since you define _timezone
2778      yourself, _timezone will not.  Thus timezone and _timezone will
2779      wind up at different memory locations.  The tzset call will set
2780      _timezone, leaving timezone unchanged.  */
2781
2782   if (h->u.weakdef != NULL)
2783     {
2784       /* If we get to this point, there is an implicit reference to
2785          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2786       h->u.weakdef->ref_regular = 1;
2787
2788       /* Ensure that the backend adjust_dynamic_symbol function sees
2789          H->U.WEAKDEF before H by recursively calling ourselves.  */
2790       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2791         return FALSE;
2792     }
2793
2794   /* If a symbol has no type and no size and does not require a PLT
2795      entry, then we are probably about to do the wrong thing here: we
2796      are probably going to create a COPY reloc for an empty object.
2797      This case can arise when a shared object is built with assembly
2798      code, and the assembly code fails to set the symbol type.  */
2799   if (h->size == 0
2800       && h->type == STT_NOTYPE
2801       && !h->needs_plt)
2802     (*_bfd_error_handler)
2803       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2804        h->root.root.string);
2805
2806   dynobj = elf_hash_table (eif->info)->dynobj;
2807   bed = get_elf_backend_data (dynobj);
2808
2809   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2810     {
2811       eif->failed = TRUE;
2812       return FALSE;
2813     }
2814
2815   return TRUE;
2816 }
2817
2818 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2819    DYNBSS.  */
2820
2821 bfd_boolean
2822 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2823                               struct elf_link_hash_entry *h,
2824                               asection *dynbss)
2825 {
2826   unsigned int power_of_two;
2827   bfd_vma mask;
2828   asection *sec = h->root.u.def.section;
2829
2830   /* The section aligment of definition is the maximum alignment
2831      requirement of symbols defined in the section.  Since we don't
2832      know the symbol alignment requirement, we start with the
2833      maximum alignment and check low bits of the symbol address
2834      for the minimum alignment.  */
2835   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2836   mask = ((bfd_vma) 1 << power_of_two) - 1;
2837   while ((h->root.u.def.value & mask) != 0)
2838     {
2839        mask >>= 1;
2840        --power_of_two;
2841     }
2842
2843   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2844                                                 dynbss))
2845     {
2846       /* Adjust the section alignment if needed.  */
2847       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2848                                        power_of_two))
2849         return FALSE;
2850     }
2851
2852   /* We make sure that the symbol will be aligned properly.  */
2853   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2854
2855   /* Define the symbol as being at this point in DYNBSS.  */
2856   h->root.u.def.section = dynbss;
2857   h->root.u.def.value = dynbss->size;
2858
2859   /* Increment the size of DYNBSS to make room for the symbol.  */
2860   dynbss->size += h->size;
2861
2862   /* No error if extern_protected_data is true.  */
2863   if (h->protected_def
2864       && (!info->extern_protected_data
2865           || (info->extern_protected_data < 0
2866               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2867     info->callbacks->einfo
2868       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2869        h->root.root.string);
2870
2871   return TRUE;
2872 }
2873
2874 /* Adjust all external symbols pointing into SEC_MERGE sections
2875    to reflect the object merging within the sections.  */
2876
2877 static bfd_boolean
2878 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2879 {
2880   asection *sec;
2881
2882   if ((h->root.type == bfd_link_hash_defined
2883        || h->root.type == bfd_link_hash_defweak)
2884       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2885       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2886     {
2887       bfd *output_bfd = (bfd *) data;
2888
2889       h->root.u.def.value =
2890         _bfd_merged_section_offset (output_bfd,
2891                                     &h->root.u.def.section,
2892                                     elf_section_data (sec)->sec_info,
2893                                     h->root.u.def.value);
2894     }
2895
2896   return TRUE;
2897 }
2898
2899 /* Returns false if the symbol referred to by H should be considered
2900    to resolve local to the current module, and true if it should be
2901    considered to bind dynamically.  */
2902
2903 bfd_boolean
2904 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2905                            struct bfd_link_info *info,
2906                            bfd_boolean not_local_protected)
2907 {
2908   bfd_boolean binding_stays_local_p;
2909   const struct elf_backend_data *bed;
2910   struct elf_link_hash_table *hash_table;
2911
2912   if (h == NULL)
2913     return FALSE;
2914
2915   while (h->root.type == bfd_link_hash_indirect
2916          || h->root.type == bfd_link_hash_warning)
2917     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2918
2919   /* If it was forced local, then clearly it's not dynamic.  */
2920   if (h->dynindx == -1)
2921     return FALSE;
2922   if (h->forced_local)
2923     return FALSE;
2924
2925   /* Identify the cases where name binding rules say that a
2926      visible symbol resolves locally.  */
2927   binding_stays_local_p = (bfd_link_executable (info)
2928                            || SYMBOLIC_BIND (info, h));
2929
2930   switch (ELF_ST_VISIBILITY (h->other))
2931     {
2932     case STV_INTERNAL:
2933     case STV_HIDDEN:
2934       return FALSE;
2935
2936     case STV_PROTECTED:
2937       hash_table = elf_hash_table (info);
2938       if (!is_elf_hash_table (hash_table))
2939         return FALSE;
2940
2941       bed = get_elf_backend_data (hash_table->dynobj);
2942
2943       /* Proper resolution for function pointer equality may require
2944          that these symbols perhaps be resolved dynamically, even though
2945          we should be resolving them to the current module.  */
2946       if (!not_local_protected || !bed->is_function_type (h->type))
2947         binding_stays_local_p = TRUE;
2948       break;
2949
2950     default:
2951       break;
2952     }
2953
2954   /* If it isn't defined locally, then clearly it's dynamic.  */
2955   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2956     return TRUE;
2957
2958   /* Otherwise, the symbol is dynamic if binding rules don't tell
2959      us that it remains local.  */
2960   return !binding_stays_local_p;
2961 }
2962
2963 /* Return true if the symbol referred to by H should be considered
2964    to resolve local to the current module, and false otherwise.  Differs
2965    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2966    undefined symbols.  The two functions are virtually identical except
2967    for the place where forced_local and dynindx == -1 are tested.  If
2968    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2969    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2970    the symbol is local only for defined symbols.
2971    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2972    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2973    treatment of undefined weak symbols.  For those that do not make
2974    undefined weak symbols dynamic, both functions may return false.  */
2975
2976 bfd_boolean
2977 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2978                               struct bfd_link_info *info,
2979                               bfd_boolean local_protected)
2980 {
2981   const struct elf_backend_data *bed;
2982   struct elf_link_hash_table *hash_table;
2983
2984   /* If it's a local sym, of course we resolve locally.  */
2985   if (h == NULL)
2986     return TRUE;
2987
2988   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2989   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2990       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2991     return TRUE;
2992
2993   /* Common symbols that become definitions don't get the DEF_REGULAR
2994      flag set, so test it first, and don't bail out.  */
2995   if (ELF_COMMON_DEF_P (h))
2996     /* Do nothing.  */;
2997   /* If we don't have a definition in a regular file, then we can't
2998      resolve locally.  The sym is either undefined or dynamic.  */
2999   else if (!h->def_regular)
3000     return FALSE;
3001
3002   /* Forced local symbols resolve locally.  */
3003   if (h->forced_local)
3004     return TRUE;
3005
3006   /* As do non-dynamic symbols.  */
3007   if (h->dynindx == -1)
3008     return TRUE;
3009
3010   /* At this point, we know the symbol is defined and dynamic.  In an
3011      executable it must resolve locally, likewise when building symbolic
3012      shared libraries.  */
3013   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3014     return TRUE;
3015
3016   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3017      with default visibility might not resolve locally.  */
3018   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3019     return FALSE;
3020
3021   hash_table = elf_hash_table (info);
3022   if (!is_elf_hash_table (hash_table))
3023     return TRUE;
3024
3025   bed = get_elf_backend_data (hash_table->dynobj);
3026
3027   /* If extern_protected_data is false, STV_PROTECTED non-function
3028      symbols are local.  */
3029   if ((!info->extern_protected_data
3030        || (info->extern_protected_data < 0
3031            && !bed->extern_protected_data))
3032       && !bed->is_function_type (h->type))
3033     return TRUE;
3034
3035   /* Function pointer equality tests may require that STV_PROTECTED
3036      symbols be treated as dynamic symbols.  If the address of a
3037      function not defined in an executable is set to that function's
3038      plt entry in the executable, then the address of the function in
3039      a shared library must also be the plt entry in the executable.  */
3040   return local_protected;
3041 }
3042
3043 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3044    aligned.  Returns the first TLS output section.  */
3045
3046 struct bfd_section *
3047 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3048 {
3049   struct bfd_section *sec, *tls;
3050   unsigned int align = 0;
3051
3052   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3053     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3054       break;
3055   tls = sec;
3056
3057   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3058     if (sec->alignment_power > align)
3059       align = sec->alignment_power;
3060
3061   elf_hash_table (info)->tls_sec = tls;
3062
3063   /* Ensure the alignment of the first section is the largest alignment,
3064      so that the tls segment starts aligned.  */
3065   if (tls != NULL)
3066     tls->alignment_power = align;
3067
3068   return tls;
3069 }
3070
3071 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3072 static bfd_boolean
3073 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3074                                   Elf_Internal_Sym *sym)
3075 {
3076   const struct elf_backend_data *bed;
3077
3078   /* Local symbols do not count, but target specific ones might.  */
3079   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3080       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3081     return FALSE;
3082
3083   bed = get_elf_backend_data (abfd);
3084   /* Function symbols do not count.  */
3085   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3086     return FALSE;
3087
3088   /* If the section is undefined, then so is the symbol.  */
3089   if (sym->st_shndx == SHN_UNDEF)
3090     return FALSE;
3091
3092   /* If the symbol is defined in the common section, then
3093      it is a common definition and so does not count.  */
3094   if (bed->common_definition (sym))
3095     return FALSE;
3096
3097   /* If the symbol is in a target specific section then we
3098      must rely upon the backend to tell us what it is.  */
3099   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3100     /* FIXME - this function is not coded yet:
3101
3102        return _bfd_is_global_symbol_definition (abfd, sym);
3103
3104        Instead for now assume that the definition is not global,
3105        Even if this is wrong, at least the linker will behave
3106        in the same way that it used to do.  */
3107     return FALSE;
3108
3109   return TRUE;
3110 }
3111
3112 /* Search the symbol table of the archive element of the archive ABFD
3113    whose archive map contains a mention of SYMDEF, and determine if
3114    the symbol is defined in this element.  */
3115 static bfd_boolean
3116 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3117 {
3118   Elf_Internal_Shdr * hdr;
3119   size_t symcount;
3120   size_t extsymcount;
3121   size_t extsymoff;
3122   Elf_Internal_Sym *isymbuf;
3123   Elf_Internal_Sym *isym;
3124   Elf_Internal_Sym *isymend;
3125   bfd_boolean result;
3126
3127   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3128   if (abfd == NULL)
3129     return FALSE;
3130
3131   if (! bfd_check_format (abfd, bfd_object))
3132     return FALSE;
3133
3134   /* Select the appropriate symbol table.  If we don't know if the
3135      object file is an IR object, give linker LTO plugin a chance to
3136      get the correct symbol table.  */
3137   if (abfd->plugin_format == bfd_plugin_yes
3138 #if BFD_SUPPORTS_PLUGINS
3139       || (abfd->plugin_format == bfd_plugin_unknown
3140           && bfd_link_plugin_object_p (abfd))
3141 #endif
3142       )
3143     {
3144       /* Use the IR symbol table if the object has been claimed by
3145          plugin.  */
3146       abfd = abfd->plugin_dummy_bfd;
3147       hdr = &elf_tdata (abfd)->symtab_hdr;
3148     }
3149   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3150     hdr = &elf_tdata (abfd)->symtab_hdr;
3151   else
3152     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3153
3154   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3155
3156   /* The sh_info field of the symtab header tells us where the
3157      external symbols start.  We don't care about the local symbols.  */
3158   if (elf_bad_symtab (abfd))
3159     {
3160       extsymcount = symcount;
3161       extsymoff = 0;
3162     }
3163   else
3164     {
3165       extsymcount = symcount - hdr->sh_info;
3166       extsymoff = hdr->sh_info;
3167     }
3168
3169   if (extsymcount == 0)
3170     return FALSE;
3171
3172   /* Read in the symbol table.  */
3173   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3174                                   NULL, NULL, NULL);
3175   if (isymbuf == NULL)
3176     return FALSE;
3177
3178   /* Scan the symbol table looking for SYMDEF.  */
3179   result = FALSE;
3180   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3181     {
3182       const char *name;
3183
3184       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3185                                               isym->st_name);
3186       if (name == NULL)
3187         break;
3188
3189       if (strcmp (name, symdef->name) == 0)
3190         {
3191           result = is_global_data_symbol_definition (abfd, isym);
3192           break;
3193         }
3194     }
3195
3196   free (isymbuf);
3197
3198   return result;
3199 }
3200 \f
3201 /* Add an entry to the .dynamic table.  */
3202
3203 bfd_boolean
3204 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3205                             bfd_vma tag,
3206                             bfd_vma val)
3207 {
3208   struct elf_link_hash_table *hash_table;
3209   const struct elf_backend_data *bed;
3210   asection *s;
3211   bfd_size_type newsize;
3212   bfd_byte *newcontents;
3213   Elf_Internal_Dyn dyn;
3214
3215   hash_table = elf_hash_table (info);
3216   if (! is_elf_hash_table (hash_table))
3217     return FALSE;
3218
3219   bed = get_elf_backend_data (hash_table->dynobj);
3220   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3221   BFD_ASSERT (s != NULL);
3222
3223   newsize = s->size + bed->s->sizeof_dyn;
3224   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3225   if (newcontents == NULL)
3226     return FALSE;
3227
3228   dyn.d_tag = tag;
3229   dyn.d_un.d_val = val;
3230   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3231
3232   s->size = newsize;
3233   s->contents = newcontents;
3234
3235   return TRUE;
3236 }
3237
3238 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3239    otherwise just check whether one already exists.  Returns -1 on error,
3240    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3241
3242 static int
3243 elf_add_dt_needed_tag (bfd *abfd,
3244                        struct bfd_link_info *info,
3245                        const char *soname,
3246                        bfd_boolean do_it)
3247 {
3248   struct elf_link_hash_table *hash_table;
3249   size_t strindex;
3250
3251   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3252     return -1;
3253
3254   hash_table = elf_hash_table (info);
3255   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3256   if (strindex == (size_t) -1)
3257     return -1;
3258
3259   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3260     {
3261       asection *sdyn;
3262       const struct elf_backend_data *bed;
3263       bfd_byte *extdyn;
3264
3265       bed = get_elf_backend_data (hash_table->dynobj);
3266       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3267       if (sdyn != NULL)
3268         for (extdyn = sdyn->contents;
3269              extdyn < sdyn->contents + sdyn->size;
3270              extdyn += bed->s->sizeof_dyn)
3271           {
3272             Elf_Internal_Dyn dyn;
3273
3274             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3275             if (dyn.d_tag == DT_NEEDED
3276                 && dyn.d_un.d_val == strindex)
3277               {
3278                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3279                 return 1;
3280               }
3281           }
3282     }
3283
3284   if (do_it)
3285     {
3286       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3287         return -1;
3288
3289       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3290         return -1;
3291     }
3292   else
3293     /* We were just checking for existence of the tag.  */
3294     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3295
3296   return 0;
3297 }
3298
3299 /* Return true if SONAME is on the needed list between NEEDED and STOP
3300    (or the end of list if STOP is NULL), and needed by a library that
3301    will be loaded.  */
3302
3303 static bfd_boolean
3304 on_needed_list (const char *soname,
3305                 struct bfd_link_needed_list *needed,
3306                 struct bfd_link_needed_list *stop)
3307 {
3308   struct bfd_link_needed_list *look;
3309   for (look = needed; look != stop; look = look->next)
3310     if (strcmp (soname, look->name) == 0
3311         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3312             /* If needed by a library that itself is not directly
3313                needed, recursively check whether that library is
3314                indirectly needed.  Since we add DT_NEEDED entries to
3315                the end of the list, library dependencies appear after
3316                the library.  Therefore search prior to the current
3317                LOOK, preventing possible infinite recursion.  */
3318             || on_needed_list (elf_dt_name (look->by), needed, look)))
3319       return TRUE;
3320
3321   return FALSE;
3322 }
3323
3324 /* Sort symbol by value, section, and size.  */
3325 static int
3326 elf_sort_symbol (const void *arg1, const void *arg2)
3327 {
3328   const struct elf_link_hash_entry *h1;
3329   const struct elf_link_hash_entry *h2;
3330   bfd_signed_vma vdiff;
3331
3332   h1 = *(const struct elf_link_hash_entry **) arg1;
3333   h2 = *(const struct elf_link_hash_entry **) arg2;
3334   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3335   if (vdiff != 0)
3336     return vdiff > 0 ? 1 : -1;
3337   else
3338     {
3339       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3340       if (sdiff != 0)
3341         return sdiff > 0 ? 1 : -1;
3342     }
3343   vdiff = h1->size - h2->size;
3344   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3345 }
3346
3347 /* This function is used to adjust offsets into .dynstr for
3348    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3349
3350 static bfd_boolean
3351 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3352 {
3353   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3354
3355   if (h->dynindx != -1)
3356     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3357   return TRUE;
3358 }
3359
3360 /* Assign string offsets in .dynstr, update all structures referencing
3361    them.  */
3362
3363 static bfd_boolean
3364 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3365 {
3366   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3367   struct elf_link_local_dynamic_entry *entry;
3368   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3369   bfd *dynobj = hash_table->dynobj;
3370   asection *sdyn;
3371   bfd_size_type size;
3372   const struct elf_backend_data *bed;
3373   bfd_byte *extdyn;
3374
3375   _bfd_elf_strtab_finalize (dynstr);
3376   size = _bfd_elf_strtab_size (dynstr);
3377
3378   bed = get_elf_backend_data (dynobj);
3379   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3380   BFD_ASSERT (sdyn != NULL);
3381
3382   /* Update all .dynamic entries referencing .dynstr strings.  */
3383   for (extdyn = sdyn->contents;
3384        extdyn < sdyn->contents + sdyn->size;
3385        extdyn += bed->s->sizeof_dyn)
3386     {
3387       Elf_Internal_Dyn dyn;
3388
3389       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3390       switch (dyn.d_tag)
3391         {
3392         case DT_STRSZ:
3393           dyn.d_un.d_val = size;
3394           break;
3395         case DT_NEEDED:
3396         case DT_SONAME:
3397         case DT_RPATH:
3398         case DT_RUNPATH:
3399         case DT_FILTER:
3400         case DT_AUXILIARY:
3401         case DT_AUDIT:
3402         case DT_DEPAUDIT:
3403           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3404           break;
3405         default:
3406           continue;
3407         }
3408       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3409     }
3410
3411   /* Now update local dynamic symbols.  */
3412   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3413     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3414                                                   entry->isym.st_name);
3415
3416   /* And the rest of dynamic symbols.  */
3417   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3418
3419   /* Adjust version definitions.  */
3420   if (elf_tdata (output_bfd)->cverdefs)
3421     {
3422       asection *s;
3423       bfd_byte *p;
3424       size_t i;
3425       Elf_Internal_Verdef def;
3426       Elf_Internal_Verdaux defaux;
3427
3428       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3429       p = s->contents;
3430       do
3431         {
3432           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3433                                    &def);
3434           p += sizeof (Elf_External_Verdef);
3435           if (def.vd_aux != sizeof (Elf_External_Verdef))
3436             continue;
3437           for (i = 0; i < def.vd_cnt; ++i)
3438             {
3439               _bfd_elf_swap_verdaux_in (output_bfd,
3440                                         (Elf_External_Verdaux *) p, &defaux);
3441               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3442                                                         defaux.vda_name);
3443               _bfd_elf_swap_verdaux_out (output_bfd,
3444                                          &defaux, (Elf_External_Verdaux *) p);
3445               p += sizeof (Elf_External_Verdaux);
3446             }
3447         }
3448       while (def.vd_next);
3449     }
3450
3451   /* Adjust version references.  */
3452   if (elf_tdata (output_bfd)->verref)
3453     {
3454       asection *s;
3455       bfd_byte *p;
3456       size_t i;
3457       Elf_Internal_Verneed need;
3458       Elf_Internal_Vernaux needaux;
3459
3460       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3461       p = s->contents;
3462       do
3463         {
3464           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3465                                     &need);
3466           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3467           _bfd_elf_swap_verneed_out (output_bfd, &need,
3468                                      (Elf_External_Verneed *) p);
3469           p += sizeof (Elf_External_Verneed);
3470           for (i = 0; i < need.vn_cnt; ++i)
3471             {
3472               _bfd_elf_swap_vernaux_in (output_bfd,
3473                                         (Elf_External_Vernaux *) p, &needaux);
3474               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3475                                                          needaux.vna_name);
3476               _bfd_elf_swap_vernaux_out (output_bfd,
3477                                          &needaux,
3478                                          (Elf_External_Vernaux *) p);
3479               p += sizeof (Elf_External_Vernaux);
3480             }
3481         }
3482       while (need.vn_next);
3483     }
3484
3485   return TRUE;
3486 }
3487 \f
3488 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3489    The default is to only match when the INPUT and OUTPUT are exactly
3490    the same target.  */
3491
3492 bfd_boolean
3493 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3494                                     const bfd_target *output)
3495 {
3496   return input == output;
3497 }
3498
3499 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3500    This version is used when different targets for the same architecture
3501    are virtually identical.  */
3502
3503 bfd_boolean
3504 _bfd_elf_relocs_compatible (const bfd_target *input,
3505                             const bfd_target *output)
3506 {
3507   const struct elf_backend_data *obed, *ibed;
3508
3509   if (input == output)
3510     return TRUE;
3511
3512   ibed = xvec_get_elf_backend_data (input);
3513   obed = xvec_get_elf_backend_data (output);
3514
3515   if (ibed->arch != obed->arch)
3516     return FALSE;
3517
3518   /* If both backends are using this function, deem them compatible.  */
3519   return ibed->relocs_compatible == obed->relocs_compatible;
3520 }
3521
3522 /* Make a special call to the linker "notice" function to tell it that
3523    we are about to handle an as-needed lib, or have finished
3524    processing the lib.  */
3525
3526 bfd_boolean
3527 _bfd_elf_notice_as_needed (bfd *ibfd,
3528                            struct bfd_link_info *info,
3529                            enum notice_asneeded_action act)
3530 {
3531   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3532 }
3533
3534 /* Check relocations an ELF object file.  */
3535
3536 bfd_boolean
3537 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3538 {
3539   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3540   struct elf_link_hash_table *htab = elf_hash_table (info);
3541
3542   /* If this object is the same format as the output object, and it is
3543      not a shared library, then let the backend look through the
3544      relocs.
3545
3546      This is required to build global offset table entries and to
3547      arrange for dynamic relocs.  It is not required for the
3548      particular common case of linking non PIC code, even when linking
3549      against shared libraries, but unfortunately there is no way of
3550      knowing whether an object file has been compiled PIC or not.
3551      Looking through the relocs is not particularly time consuming.
3552      The problem is that we must either (1) keep the relocs in memory,
3553      which causes the linker to require additional runtime memory or
3554      (2) read the relocs twice from the input file, which wastes time.
3555      This would be a good case for using mmap.
3556
3557      I have no idea how to handle linking PIC code into a file of a
3558      different format.  It probably can't be done.  */
3559   if ((abfd->flags & DYNAMIC) == 0
3560       && is_elf_hash_table (htab)
3561       && bed->check_relocs != NULL
3562       && elf_object_id (abfd) == elf_hash_table_id (htab)
3563       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3564     {
3565       asection *o;
3566
3567       for (o = abfd->sections; o != NULL; o = o->next)
3568         {
3569           Elf_Internal_Rela *internal_relocs;
3570           bfd_boolean ok;
3571
3572           /* Don't check relocations in excluded sections.  */
3573           if ((o->flags & SEC_RELOC) == 0
3574               || (o->flags & SEC_EXCLUDE) != 0
3575               || o->reloc_count == 0
3576               || ((info->strip == strip_all || info->strip == strip_debugger)
3577                   && (o->flags & SEC_DEBUGGING) != 0)
3578               || bfd_is_abs_section (o->output_section))
3579             continue;
3580
3581           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3582                                                        info->keep_memory);
3583           if (internal_relocs == NULL)
3584             return FALSE;
3585
3586           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3587
3588           if (elf_section_data (o)->relocs != internal_relocs)
3589             free (internal_relocs);
3590
3591           if (! ok)
3592             return FALSE;
3593         }
3594     }
3595
3596   return TRUE;
3597 }
3598
3599 /* Add symbols from an ELF object file to the linker hash table.  */
3600
3601 static bfd_boolean
3602 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3603 {
3604   Elf_Internal_Ehdr *ehdr;
3605   Elf_Internal_Shdr *hdr;
3606   size_t symcount;
3607   size_t extsymcount;
3608   size_t extsymoff;
3609   struct elf_link_hash_entry **sym_hash;
3610   bfd_boolean dynamic;
3611   Elf_External_Versym *extversym = NULL;
3612   Elf_External_Versym *ever;
3613   struct elf_link_hash_entry *weaks;
3614   struct elf_link_hash_entry **nondeflt_vers = NULL;
3615   size_t nondeflt_vers_cnt = 0;
3616   Elf_Internal_Sym *isymbuf = NULL;
3617   Elf_Internal_Sym *isym;
3618   Elf_Internal_Sym *isymend;
3619   const struct elf_backend_data *bed;
3620   bfd_boolean add_needed;
3621   struct elf_link_hash_table *htab;
3622   bfd_size_type amt;
3623   void *alloc_mark = NULL;
3624   struct bfd_hash_entry **old_table = NULL;
3625   unsigned int old_size = 0;
3626   unsigned int old_count = 0;
3627   void *old_tab = NULL;
3628   void *old_ent;
3629   struct bfd_link_hash_entry *old_undefs = NULL;
3630   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3631   void *old_strtab = NULL;
3632   size_t tabsize = 0;
3633   asection *s;
3634   bfd_boolean just_syms;
3635
3636   htab = elf_hash_table (info);
3637   bed = get_elf_backend_data (abfd);
3638
3639   if ((abfd->flags & DYNAMIC) == 0)
3640     dynamic = FALSE;
3641   else
3642     {
3643       dynamic = TRUE;
3644
3645       /* You can't use -r against a dynamic object.  Also, there's no
3646          hope of using a dynamic object which does not exactly match
3647          the format of the output file.  */
3648       if (bfd_link_relocatable (info)
3649           || !is_elf_hash_table (htab)
3650           || info->output_bfd->xvec != abfd->xvec)
3651         {
3652           if (bfd_link_relocatable (info))
3653             bfd_set_error (bfd_error_invalid_operation);
3654           else
3655             bfd_set_error (bfd_error_wrong_format);
3656           goto error_return;
3657         }
3658     }
3659
3660   ehdr = elf_elfheader (abfd);
3661   if (info->warn_alternate_em
3662       && bed->elf_machine_code != ehdr->e_machine
3663       && ((bed->elf_machine_alt1 != 0
3664            && ehdr->e_machine == bed->elf_machine_alt1)
3665           || (bed->elf_machine_alt2 != 0
3666               && ehdr->e_machine == bed->elf_machine_alt2)))
3667     info->callbacks->einfo
3668       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3669        ehdr->e_machine, abfd, bed->elf_machine_code);
3670
3671   /* As a GNU extension, any input sections which are named
3672      .gnu.warning.SYMBOL are treated as warning symbols for the given
3673      symbol.  This differs from .gnu.warning sections, which generate
3674      warnings when they are included in an output file.  */
3675   /* PR 12761: Also generate this warning when building shared libraries.  */
3676   for (s = abfd->sections; s != NULL; s = s->next)
3677     {
3678       const char *name;
3679
3680       name = bfd_get_section_name (abfd, s);
3681       if (CONST_STRNEQ (name, ".gnu.warning."))
3682         {
3683           char *msg;
3684           bfd_size_type sz;
3685
3686           name += sizeof ".gnu.warning." - 1;
3687
3688           /* If this is a shared object, then look up the symbol
3689              in the hash table.  If it is there, and it is already
3690              been defined, then we will not be using the entry
3691              from this shared object, so we don't need to warn.
3692              FIXME: If we see the definition in a regular object
3693              later on, we will warn, but we shouldn't.  The only
3694              fix is to keep track of what warnings we are supposed
3695              to emit, and then handle them all at the end of the
3696              link.  */
3697           if (dynamic)
3698             {
3699               struct elf_link_hash_entry *h;
3700
3701               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3702
3703               /* FIXME: What about bfd_link_hash_common?  */
3704               if (h != NULL
3705                   && (h->root.type == bfd_link_hash_defined
3706                       || h->root.type == bfd_link_hash_defweak))
3707                 continue;
3708             }
3709
3710           sz = s->size;
3711           msg = (char *) bfd_alloc (abfd, sz + 1);
3712           if (msg == NULL)
3713             goto error_return;
3714
3715           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3716             goto error_return;
3717
3718           msg[sz] = '\0';
3719
3720           if (! (_bfd_generic_link_add_one_symbol
3721                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3722                   FALSE, bed->collect, NULL)))
3723             goto error_return;
3724
3725           if (bfd_link_executable (info))
3726             {
3727               /* Clobber the section size so that the warning does
3728                  not get copied into the output file.  */
3729               s->size = 0;
3730
3731               /* Also set SEC_EXCLUDE, so that symbols defined in
3732                  the warning section don't get copied to the output.  */
3733               s->flags |= SEC_EXCLUDE;
3734             }
3735         }
3736     }
3737
3738   just_syms = ((s = abfd->sections) != NULL
3739                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3740
3741   add_needed = TRUE;
3742   if (! dynamic)
3743     {
3744       /* If we are creating a shared library, create all the dynamic
3745          sections immediately.  We need to attach them to something,
3746          so we attach them to this BFD, provided it is the right
3747          format and is not from ld --just-symbols.  Always create the
3748          dynamic sections for -E/--dynamic-list.  FIXME: If there
3749          are no input BFD's of the same format as the output, we can't
3750          make a shared library.  */
3751       if (!just_syms
3752           && (bfd_link_pic (info)
3753               || (!bfd_link_relocatable (info)
3754                   && (info->export_dynamic || info->dynamic)))
3755           && is_elf_hash_table (htab)
3756           && info->output_bfd->xvec == abfd->xvec
3757           && !htab->dynamic_sections_created)
3758         {
3759           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3760             goto error_return;
3761         }
3762     }
3763   else if (!is_elf_hash_table (htab))
3764     goto error_return;
3765   else
3766     {
3767       const char *soname = NULL;
3768       char *audit = NULL;
3769       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3770       int ret;
3771
3772       /* ld --just-symbols and dynamic objects don't mix very well.
3773          ld shouldn't allow it.  */
3774       if (just_syms)
3775         abort ();
3776
3777       /* If this dynamic lib was specified on the command line with
3778          --as-needed in effect, then we don't want to add a DT_NEEDED
3779          tag unless the lib is actually used.  Similary for libs brought
3780          in by another lib's DT_NEEDED.  When --no-add-needed is used
3781          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3782          any dynamic library in DT_NEEDED tags in the dynamic lib at
3783          all.  */
3784       add_needed = (elf_dyn_lib_class (abfd)
3785                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3786                        | DYN_NO_NEEDED)) == 0;
3787
3788       s = bfd_get_section_by_name (abfd, ".dynamic");
3789       if (s != NULL)
3790         {
3791           bfd_byte *dynbuf;
3792           bfd_byte *extdyn;
3793           unsigned int elfsec;
3794           unsigned long shlink;
3795
3796           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3797             {
3798 error_free_dyn:
3799               free (dynbuf);
3800               goto error_return;
3801             }
3802
3803           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3804           if (elfsec == SHN_BAD)
3805             goto error_free_dyn;
3806           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3807
3808           for (extdyn = dynbuf;
3809                extdyn < dynbuf + s->size;
3810                extdyn += bed->s->sizeof_dyn)
3811             {
3812               Elf_Internal_Dyn dyn;
3813
3814               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3815               if (dyn.d_tag == DT_SONAME)
3816                 {
3817                   unsigned int tagv = dyn.d_un.d_val;
3818                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3819                   if (soname == NULL)
3820                     goto error_free_dyn;
3821                 }
3822               if (dyn.d_tag == DT_NEEDED)
3823                 {
3824                   struct bfd_link_needed_list *n, **pn;
3825                   char *fnm, *anm;
3826                   unsigned int tagv = dyn.d_un.d_val;
3827
3828                   amt = sizeof (struct bfd_link_needed_list);
3829                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3830                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3831                   if (n == NULL || fnm == NULL)
3832                     goto error_free_dyn;
3833                   amt = strlen (fnm) + 1;
3834                   anm = (char *) bfd_alloc (abfd, amt);
3835                   if (anm == NULL)
3836                     goto error_free_dyn;
3837                   memcpy (anm, fnm, amt);
3838                   n->name = anm;
3839                   n->by = abfd;
3840                   n->next = NULL;
3841                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3842                     ;
3843                   *pn = n;
3844                 }
3845               if (dyn.d_tag == DT_RUNPATH)
3846                 {
3847                   struct bfd_link_needed_list *n, **pn;
3848                   char *fnm, *anm;
3849                   unsigned int tagv = dyn.d_un.d_val;
3850
3851                   amt = sizeof (struct bfd_link_needed_list);
3852                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3853                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3854                   if (n == NULL || fnm == NULL)
3855                     goto error_free_dyn;
3856                   amt = strlen (fnm) + 1;
3857                   anm = (char *) bfd_alloc (abfd, amt);
3858                   if (anm == NULL)
3859                     goto error_free_dyn;
3860                   memcpy (anm, fnm, amt);
3861                   n->name = anm;
3862                   n->by = abfd;
3863                   n->next = NULL;
3864                   for (pn = & runpath;
3865                        *pn != NULL;
3866                        pn = &(*pn)->next)
3867                     ;
3868                   *pn = n;
3869                 }
3870               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3871               if (!runpath && dyn.d_tag == DT_RPATH)
3872                 {
3873                   struct bfd_link_needed_list *n, **pn;
3874                   char *fnm, *anm;
3875                   unsigned int tagv = dyn.d_un.d_val;
3876
3877                   amt = sizeof (struct bfd_link_needed_list);
3878                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3879                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3880                   if (n == NULL || fnm == NULL)
3881                     goto error_free_dyn;
3882                   amt = strlen (fnm) + 1;
3883                   anm = (char *) bfd_alloc (abfd, amt);
3884                   if (anm == NULL)
3885                     goto error_free_dyn;
3886                   memcpy (anm, fnm, amt);
3887                   n->name = anm;
3888                   n->by = abfd;
3889                   n->next = NULL;
3890                   for (pn = & rpath;
3891                        *pn != NULL;
3892                        pn = &(*pn)->next)
3893                     ;
3894                   *pn = n;
3895                 }
3896               if (dyn.d_tag == DT_AUDIT)
3897                 {
3898                   unsigned int tagv = dyn.d_un.d_val;
3899                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3900                 }
3901             }
3902
3903           free (dynbuf);
3904         }
3905
3906       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3907          frees all more recently bfd_alloc'd blocks as well.  */
3908       if (runpath)
3909         rpath = runpath;
3910
3911       if (rpath)
3912         {
3913           struct bfd_link_needed_list **pn;
3914           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3915             ;
3916           *pn = rpath;
3917         }
3918
3919       /* We do not want to include any of the sections in a dynamic
3920          object in the output file.  We hack by simply clobbering the
3921          list of sections in the BFD.  This could be handled more
3922          cleanly by, say, a new section flag; the existing
3923          SEC_NEVER_LOAD flag is not the one we want, because that one
3924          still implies that the section takes up space in the output
3925          file.  */
3926       bfd_section_list_clear (abfd);
3927
3928       /* Find the name to use in a DT_NEEDED entry that refers to this
3929          object.  If the object has a DT_SONAME entry, we use it.
3930          Otherwise, if the generic linker stuck something in
3931          elf_dt_name, we use that.  Otherwise, we just use the file
3932          name.  */
3933       if (soname == NULL || *soname == '\0')
3934         {
3935           soname = elf_dt_name (abfd);
3936           if (soname == NULL || *soname == '\0')
3937             soname = bfd_get_filename (abfd);
3938         }
3939
3940       /* Save the SONAME because sometimes the linker emulation code
3941          will need to know it.  */
3942       elf_dt_name (abfd) = soname;
3943
3944       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3945       if (ret < 0)
3946         goto error_return;
3947
3948       /* If we have already included this dynamic object in the
3949          link, just ignore it.  There is no reason to include a
3950          particular dynamic object more than once.  */
3951       if (ret > 0)
3952         return TRUE;
3953
3954       /* Save the DT_AUDIT entry for the linker emulation code. */
3955       elf_dt_audit (abfd) = audit;
3956     }
3957
3958   /* If this is a dynamic object, we always link against the .dynsym
3959      symbol table, not the .symtab symbol table.  The dynamic linker
3960      will only see the .dynsym symbol table, so there is no reason to
3961      look at .symtab for a dynamic object.  */
3962
3963   if (! dynamic || elf_dynsymtab (abfd) == 0)
3964     hdr = &elf_tdata (abfd)->symtab_hdr;
3965   else
3966     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3967
3968   symcount = hdr->sh_size / bed->s->sizeof_sym;
3969
3970   /* The sh_info field of the symtab header tells us where the
3971      external symbols start.  We don't care about the local symbols at
3972      this point.  */
3973   if (elf_bad_symtab (abfd))
3974     {
3975       extsymcount = symcount;
3976       extsymoff = 0;
3977     }
3978   else
3979     {
3980       extsymcount = symcount - hdr->sh_info;
3981       extsymoff = hdr->sh_info;
3982     }
3983
3984   sym_hash = elf_sym_hashes (abfd);
3985   if (extsymcount != 0)
3986     {
3987       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3988                                       NULL, NULL, NULL);
3989       if (isymbuf == NULL)
3990         goto error_return;
3991
3992       if (sym_hash == NULL)
3993         {
3994           /* We store a pointer to the hash table entry for each
3995              external symbol.  */
3996           amt = extsymcount;
3997           amt *= sizeof (struct elf_link_hash_entry *);
3998           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3999           if (sym_hash == NULL)
4000             goto error_free_sym;
4001           elf_sym_hashes (abfd) = sym_hash;
4002         }
4003     }
4004
4005   if (dynamic)
4006     {
4007       /* Read in any version definitions.  */
4008       if (!_bfd_elf_slurp_version_tables (abfd,
4009                                           info->default_imported_symver))
4010         goto error_free_sym;
4011
4012       /* Read in the symbol versions, but don't bother to convert them
4013          to internal format.  */
4014       if (elf_dynversym (abfd) != 0)
4015         {
4016           Elf_Internal_Shdr *versymhdr;
4017
4018           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4019           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4020           if (extversym == NULL)
4021             goto error_free_sym;
4022           amt = versymhdr->sh_size;
4023           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4024               || bfd_bread (extversym, amt, abfd) != amt)
4025             goto error_free_vers;
4026         }
4027     }
4028
4029   /* If we are loading an as-needed shared lib, save the symbol table
4030      state before we start adding symbols.  If the lib turns out
4031      to be unneeded, restore the state.  */
4032   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4033     {
4034       unsigned int i;
4035       size_t entsize;
4036
4037       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4038         {
4039           struct bfd_hash_entry *p;
4040           struct elf_link_hash_entry *h;
4041
4042           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4043             {
4044               h = (struct elf_link_hash_entry *) p;
4045               entsize += htab->root.table.entsize;
4046               if (h->root.type == bfd_link_hash_warning)
4047                 entsize += htab->root.table.entsize;
4048             }
4049         }
4050
4051       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4052       old_tab = bfd_malloc (tabsize + entsize);
4053       if (old_tab == NULL)
4054         goto error_free_vers;
4055
4056       /* Remember the current objalloc pointer, so that all mem for
4057          symbols added can later be reclaimed.  */
4058       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4059       if (alloc_mark == NULL)
4060         goto error_free_vers;
4061
4062       /* Make a special call to the linker "notice" function to
4063          tell it that we are about to handle an as-needed lib.  */
4064       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4065         goto error_free_vers;
4066
4067       /* Clone the symbol table.  Remember some pointers into the
4068          symbol table, and dynamic symbol count.  */
4069       old_ent = (char *) old_tab + tabsize;
4070       memcpy (old_tab, htab->root.table.table, tabsize);
4071       old_undefs = htab->root.undefs;
4072       old_undefs_tail = htab->root.undefs_tail;
4073       old_table = htab->root.table.table;
4074       old_size = htab->root.table.size;
4075       old_count = htab->root.table.count;
4076       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4077       if (old_strtab == NULL)
4078         goto error_free_vers;
4079
4080       for (i = 0; i < htab->root.table.size; i++)
4081         {
4082           struct bfd_hash_entry *p;
4083           struct elf_link_hash_entry *h;
4084
4085           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4086             {
4087               memcpy (old_ent, p, htab->root.table.entsize);
4088               old_ent = (char *) old_ent + htab->root.table.entsize;
4089               h = (struct elf_link_hash_entry *) p;
4090               if (h->root.type == bfd_link_hash_warning)
4091                 {
4092                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4093                   old_ent = (char *) old_ent + htab->root.table.entsize;
4094                 }
4095             }
4096         }
4097     }
4098
4099   weaks = NULL;
4100   ever = extversym != NULL ? extversym + extsymoff : NULL;
4101   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4102        isym < isymend;
4103        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4104     {
4105       int bind;
4106       bfd_vma value;
4107       asection *sec, *new_sec;
4108       flagword flags;
4109       const char *name;
4110       struct elf_link_hash_entry *h;
4111       struct elf_link_hash_entry *hi;
4112       bfd_boolean definition;
4113       bfd_boolean size_change_ok;
4114       bfd_boolean type_change_ok;
4115       bfd_boolean new_weakdef;
4116       bfd_boolean new_weak;
4117       bfd_boolean old_weak;
4118       bfd_boolean override;
4119       bfd_boolean common;
4120       bfd_boolean discarded;
4121       unsigned int old_alignment;
4122       bfd *old_bfd;
4123       bfd_boolean matched;
4124
4125       override = FALSE;
4126
4127       flags = BSF_NO_FLAGS;
4128       sec = NULL;
4129       value = isym->st_value;
4130       common = bed->common_definition (isym);
4131       discarded = FALSE;
4132
4133       bind = ELF_ST_BIND (isym->st_info);
4134       switch (bind)
4135         {
4136         case STB_LOCAL:
4137           /* This should be impossible, since ELF requires that all
4138              global symbols follow all local symbols, and that sh_info
4139              point to the first global symbol.  Unfortunately, Irix 5
4140              screws this up.  */
4141           continue;
4142
4143         case STB_GLOBAL:
4144           if (isym->st_shndx != SHN_UNDEF && !common)
4145             flags = BSF_GLOBAL;
4146           break;
4147
4148         case STB_WEAK:
4149           flags = BSF_WEAK;
4150           break;
4151
4152         case STB_GNU_UNIQUE:
4153           flags = BSF_GNU_UNIQUE;
4154           break;
4155
4156         default:
4157           /* Leave it up to the processor backend.  */
4158           break;
4159         }
4160
4161       if (isym->st_shndx == SHN_UNDEF)
4162         sec = bfd_und_section_ptr;
4163       else if (isym->st_shndx == SHN_ABS)
4164         sec = bfd_abs_section_ptr;
4165       else if (isym->st_shndx == SHN_COMMON)
4166         {
4167           sec = bfd_com_section_ptr;
4168           /* What ELF calls the size we call the value.  What ELF
4169              calls the value we call the alignment.  */
4170           value = isym->st_size;
4171         }
4172       else
4173         {
4174           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4175           if (sec == NULL)
4176             sec = bfd_abs_section_ptr;
4177           else if (discarded_section (sec))
4178             {
4179               /* Symbols from discarded section are undefined.  We keep
4180                  its visibility.  */
4181               sec = bfd_und_section_ptr;
4182               discarded = TRUE;
4183               isym->st_shndx = SHN_UNDEF;
4184             }
4185           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4186             value -= sec->vma;
4187         }
4188
4189       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4190                                               isym->st_name);
4191       if (name == NULL)
4192         goto error_free_vers;
4193
4194       if (isym->st_shndx == SHN_COMMON
4195           && (abfd->flags & BFD_PLUGIN) != 0)
4196         {
4197           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4198
4199           if (xc == NULL)
4200             {
4201               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4202                                  | SEC_EXCLUDE);
4203               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4204               if (xc == NULL)
4205                 goto error_free_vers;
4206             }
4207           sec = xc;
4208         }
4209       else if (isym->st_shndx == SHN_COMMON
4210                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4211                && !bfd_link_relocatable (info))
4212         {
4213           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4214
4215           if (tcomm == NULL)
4216             {
4217               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4218                                  | SEC_LINKER_CREATED);
4219               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4220               if (tcomm == NULL)
4221                 goto error_free_vers;
4222             }
4223           sec = tcomm;
4224         }
4225       else if (bed->elf_add_symbol_hook)
4226         {
4227           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4228                                              &sec, &value))
4229             goto error_free_vers;
4230
4231           /* The hook function sets the name to NULL if this symbol
4232              should be skipped for some reason.  */
4233           if (name == NULL)
4234             continue;
4235         }
4236
4237       /* Sanity check that all possibilities were handled.  */
4238       if (sec == NULL)
4239         {
4240           bfd_set_error (bfd_error_bad_value);
4241           goto error_free_vers;
4242         }
4243
4244       /* Silently discard TLS symbols from --just-syms.  There's
4245          no way to combine a static TLS block with a new TLS block
4246          for this executable.  */
4247       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4248           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4249         continue;
4250
4251       if (bfd_is_und_section (sec)
4252           || bfd_is_com_section (sec))
4253         definition = FALSE;
4254       else
4255         definition = TRUE;
4256
4257       size_change_ok = FALSE;
4258       type_change_ok = bed->type_change_ok;
4259       old_weak = FALSE;
4260       matched = FALSE;
4261       old_alignment = 0;
4262       old_bfd = NULL;
4263       new_sec = sec;
4264
4265       if (is_elf_hash_table (htab))
4266         {
4267           Elf_Internal_Versym iver;
4268           unsigned int vernum = 0;
4269           bfd_boolean skip;
4270
4271           if (ever == NULL)
4272             {
4273               if (info->default_imported_symver)
4274                 /* Use the default symbol version created earlier.  */
4275                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4276               else
4277                 iver.vs_vers = 0;
4278             }
4279           else
4280             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4281
4282           vernum = iver.vs_vers & VERSYM_VERSION;
4283
4284           /* If this is a hidden symbol, or if it is not version
4285              1, we append the version name to the symbol name.
4286              However, we do not modify a non-hidden absolute symbol
4287              if it is not a function, because it might be the version
4288              symbol itself.  FIXME: What if it isn't?  */
4289           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4290               || (vernum > 1
4291                   && (!bfd_is_abs_section (sec)
4292                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4293             {
4294               const char *verstr;
4295               size_t namelen, verlen, newlen;
4296               char *newname, *p;
4297
4298               if (isym->st_shndx != SHN_UNDEF)
4299                 {
4300                   if (vernum > elf_tdata (abfd)->cverdefs)
4301                     verstr = NULL;
4302                   else if (vernum > 1)
4303                     verstr =
4304                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4305                   else
4306                     verstr = "";
4307
4308                   if (verstr == NULL)
4309                     {
4310                       (*_bfd_error_handler)
4311                         (_("%B: %s: invalid version %u (max %d)"),
4312                          abfd, name, vernum,
4313                          elf_tdata (abfd)->cverdefs);
4314                       bfd_set_error (bfd_error_bad_value);
4315                       goto error_free_vers;
4316                     }
4317                 }
4318               else
4319                 {
4320                   /* We cannot simply test for the number of
4321                      entries in the VERNEED section since the
4322                      numbers for the needed versions do not start
4323                      at 0.  */
4324                   Elf_Internal_Verneed *t;
4325
4326                   verstr = NULL;
4327                   for (t = elf_tdata (abfd)->verref;
4328                        t != NULL;
4329                        t = t->vn_nextref)
4330                     {
4331                       Elf_Internal_Vernaux *a;
4332
4333                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4334                         {
4335                           if (a->vna_other == vernum)
4336                             {
4337                               verstr = a->vna_nodename;
4338                               break;
4339                             }
4340                         }
4341                       if (a != NULL)
4342                         break;
4343                     }
4344                   if (verstr == NULL)
4345                     {
4346                       (*_bfd_error_handler)
4347                         (_("%B: %s: invalid needed version %d"),
4348                          abfd, name, vernum);
4349                       bfd_set_error (bfd_error_bad_value);
4350                       goto error_free_vers;
4351                     }
4352                 }
4353
4354               namelen = strlen (name);
4355               verlen = strlen (verstr);
4356               newlen = namelen + verlen + 2;
4357               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4358                   && isym->st_shndx != SHN_UNDEF)
4359                 ++newlen;
4360
4361               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4362               if (newname == NULL)
4363                 goto error_free_vers;
4364               memcpy (newname, name, namelen);
4365               p = newname + namelen;
4366               *p++ = ELF_VER_CHR;
4367               /* If this is a defined non-hidden version symbol,
4368                  we add another @ to the name.  This indicates the
4369                  default version of the symbol.  */
4370               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4371                   && isym->st_shndx != SHN_UNDEF)
4372                 *p++ = ELF_VER_CHR;
4373               memcpy (p, verstr, verlen + 1);
4374
4375               name = newname;
4376             }
4377
4378           /* If this symbol has default visibility and the user has
4379              requested we not re-export it, then mark it as hidden.  */
4380           if (!bfd_is_und_section (sec)
4381               && !dynamic
4382               && abfd->no_export
4383               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4384             isym->st_other = (STV_HIDDEN
4385                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4386
4387           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4388                                       sym_hash, &old_bfd, &old_weak,
4389                                       &old_alignment, &skip, &override,
4390                                       &type_change_ok, &size_change_ok,
4391                                       &matched))
4392             goto error_free_vers;
4393
4394           if (skip)
4395             continue;
4396
4397           /* Override a definition only if the new symbol matches the
4398              existing one.  */
4399           if (override && matched)
4400             definition = FALSE;
4401
4402           h = *sym_hash;
4403           while (h->root.type == bfd_link_hash_indirect
4404                  || h->root.type == bfd_link_hash_warning)
4405             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4406
4407           if (elf_tdata (abfd)->verdef != NULL
4408               && vernum > 1
4409               && definition)
4410             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4411         }
4412
4413       if (! (_bfd_generic_link_add_one_symbol
4414              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4415               (struct bfd_link_hash_entry **) sym_hash)))
4416         goto error_free_vers;
4417
4418       if ((flags & BSF_GNU_UNIQUE)
4419           && (abfd->flags & DYNAMIC) == 0
4420           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4421         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4422
4423       h = *sym_hash;
4424       /* We need to make sure that indirect symbol dynamic flags are
4425          updated.  */
4426       hi = h;
4427       while (h->root.type == bfd_link_hash_indirect
4428              || h->root.type == bfd_link_hash_warning)
4429         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4430
4431       /* Setting the index to -3 tells elf_link_output_extsym that
4432          this symbol is defined in a discarded section.  */
4433       if (discarded)
4434         h->indx = -3;
4435
4436       *sym_hash = h;
4437
4438       new_weak = (flags & BSF_WEAK) != 0;
4439       new_weakdef = FALSE;
4440       if (dynamic
4441           && definition
4442           && new_weak
4443           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4444           && is_elf_hash_table (htab)
4445           && h->u.weakdef == NULL)
4446         {
4447           /* Keep a list of all weak defined non function symbols from
4448              a dynamic object, using the weakdef field.  Later in this
4449              function we will set the weakdef field to the correct
4450              value.  We only put non-function symbols from dynamic
4451              objects on this list, because that happens to be the only
4452              time we need to know the normal symbol corresponding to a
4453              weak symbol, and the information is time consuming to
4454              figure out.  If the weakdef field is not already NULL,
4455              then this symbol was already defined by some previous
4456              dynamic object, and we will be using that previous
4457              definition anyhow.  */
4458
4459           h->u.weakdef = weaks;
4460           weaks = h;
4461           new_weakdef = TRUE;
4462         }
4463
4464       /* Set the alignment of a common symbol.  */
4465       if ((common || bfd_is_com_section (sec))
4466           && h->root.type == bfd_link_hash_common)
4467         {
4468           unsigned int align;
4469
4470           if (common)
4471             align = bfd_log2 (isym->st_value);
4472           else
4473             {
4474               /* The new symbol is a common symbol in a shared object.
4475                  We need to get the alignment from the section.  */
4476               align = new_sec->alignment_power;
4477             }
4478           if (align > old_alignment)
4479             h->root.u.c.p->alignment_power = align;
4480           else
4481             h->root.u.c.p->alignment_power = old_alignment;
4482         }
4483
4484       if (is_elf_hash_table (htab))
4485         {
4486           /* Set a flag in the hash table entry indicating the type of
4487              reference or definition we just found.  A dynamic symbol
4488              is one which is referenced or defined by both a regular
4489              object and a shared object.  */
4490           bfd_boolean dynsym = FALSE;
4491
4492           /* Plugin symbols aren't normal.  Don't set def_regular or
4493              ref_regular for them, or make them dynamic.  */
4494           if ((abfd->flags & BFD_PLUGIN) != 0)
4495             ;
4496           else if (! dynamic)
4497             {
4498               if (! definition)
4499                 {
4500                   h->ref_regular = 1;
4501                   if (bind != STB_WEAK)
4502                     h->ref_regular_nonweak = 1;
4503                 }
4504               else
4505                 {
4506                   h->def_regular = 1;
4507                   if (h->def_dynamic)
4508                     {
4509                       h->def_dynamic = 0;
4510                       h->ref_dynamic = 1;
4511                     }
4512                 }
4513
4514               /* If the indirect symbol has been forced local, don't
4515                  make the real symbol dynamic.  */
4516               if ((h == hi || !hi->forced_local)
4517                   && (bfd_link_dll (info)
4518                       || h->def_dynamic
4519                       || h->ref_dynamic))
4520                 dynsym = TRUE;
4521             }
4522           else
4523             {
4524               if (! definition)
4525                 {
4526                   h->ref_dynamic = 1;
4527                   hi->ref_dynamic = 1;
4528                 }
4529               else
4530                 {
4531                   h->def_dynamic = 1;
4532                   hi->def_dynamic = 1;
4533                 }
4534
4535               /* If the indirect symbol has been forced local, don't
4536                  make the real symbol dynamic.  */
4537               if ((h == hi || !hi->forced_local)
4538                   && (h->def_regular
4539                       || h->ref_regular
4540                       || (h->u.weakdef != NULL
4541                           && ! new_weakdef
4542                           && h->u.weakdef->dynindx != -1)))
4543                 dynsym = TRUE;
4544             }
4545
4546           /* Check to see if we need to add an indirect symbol for
4547              the default name.  */
4548           if (definition
4549               || (!override && h->root.type == bfd_link_hash_common))
4550             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4551                                               sec, value, &old_bfd, &dynsym))
4552               goto error_free_vers;
4553
4554           /* Check the alignment when a common symbol is involved. This
4555              can change when a common symbol is overridden by a normal
4556              definition or a common symbol is ignored due to the old
4557              normal definition. We need to make sure the maximum
4558              alignment is maintained.  */
4559           if ((old_alignment || common)
4560               && h->root.type != bfd_link_hash_common)
4561             {
4562               unsigned int common_align;
4563               unsigned int normal_align;
4564               unsigned int symbol_align;
4565               bfd *normal_bfd;
4566               bfd *common_bfd;
4567
4568               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4569                           || h->root.type == bfd_link_hash_defweak);
4570
4571               symbol_align = ffs (h->root.u.def.value) - 1;
4572               if (h->root.u.def.section->owner != NULL
4573                   && (h->root.u.def.section->owner->flags
4574                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4575                 {
4576                   normal_align = h->root.u.def.section->alignment_power;
4577                   if (normal_align > symbol_align)
4578                     normal_align = symbol_align;
4579                 }
4580               else
4581                 normal_align = symbol_align;
4582
4583               if (old_alignment)
4584                 {
4585                   common_align = old_alignment;
4586                   common_bfd = old_bfd;
4587                   normal_bfd = abfd;
4588                 }
4589               else
4590                 {
4591                   common_align = bfd_log2 (isym->st_value);
4592                   common_bfd = abfd;
4593                   normal_bfd = old_bfd;
4594                 }
4595
4596               if (normal_align < common_align)
4597                 {
4598                   /* PR binutils/2735 */
4599                   if (normal_bfd == NULL)
4600                     (*_bfd_error_handler)
4601                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4602                          " greater than the alignment (%u) of its section %A"),
4603                        common_bfd, h->root.u.def.section,
4604                        1 << common_align, name, 1 << normal_align);
4605                   else
4606                     (*_bfd_error_handler)
4607                       (_("Warning: alignment %u of symbol `%s' in %B"
4608                          " is smaller than %u in %B"),
4609                        normal_bfd, common_bfd,
4610                        1 << normal_align, name, 1 << common_align);
4611                 }
4612             }
4613
4614           /* Remember the symbol size if it isn't undefined.  */
4615           if (isym->st_size != 0
4616               && isym->st_shndx != SHN_UNDEF
4617               && (definition || h->size == 0))
4618             {
4619               if (h->size != 0
4620                   && h->size != isym->st_size
4621                   && ! size_change_ok)
4622                 (*_bfd_error_handler)
4623                   (_("Warning: size of symbol `%s' changed"
4624                      " from %lu in %B to %lu in %B"),
4625                    old_bfd, abfd,
4626                    name, (unsigned long) h->size,
4627                    (unsigned long) isym->st_size);
4628
4629               h->size = isym->st_size;
4630             }
4631
4632           /* If this is a common symbol, then we always want H->SIZE
4633              to be the size of the common symbol.  The code just above
4634              won't fix the size if a common symbol becomes larger.  We
4635              don't warn about a size change here, because that is
4636              covered by --warn-common.  Allow changes between different
4637              function types.  */
4638           if (h->root.type == bfd_link_hash_common)
4639             h->size = h->root.u.c.size;
4640
4641           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4642               && ((definition && !new_weak)
4643                   || (old_weak && h->root.type == bfd_link_hash_common)
4644                   || h->type == STT_NOTYPE))
4645             {
4646               unsigned int type = ELF_ST_TYPE (isym->st_info);
4647
4648               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4649                  symbol.  */
4650               if (type == STT_GNU_IFUNC
4651                   && (abfd->flags & DYNAMIC) != 0)
4652                 type = STT_FUNC;
4653
4654               if (h->type != type)
4655                 {
4656                   if (h->type != STT_NOTYPE && ! type_change_ok)
4657                     (*_bfd_error_handler)
4658                       (_("Warning: type of symbol `%s' changed"
4659                          " from %d to %d in %B"),
4660                        abfd, name, h->type, type);
4661
4662                   h->type = type;
4663                 }
4664             }
4665
4666           /* Merge st_other field.  */
4667           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4668
4669           /* We don't want to make debug symbol dynamic.  */
4670           if (definition
4671               && (sec->flags & SEC_DEBUGGING)
4672               && !bfd_link_relocatable (info))
4673             dynsym = FALSE;
4674
4675           /* Nor should we make plugin symbols dynamic.  */
4676           if ((abfd->flags & BFD_PLUGIN) != 0)
4677             dynsym = FALSE;
4678
4679           if (definition)
4680             {
4681               h->target_internal = isym->st_target_internal;
4682               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4683             }
4684
4685           if (definition && !dynamic)
4686             {
4687               char *p = strchr (name, ELF_VER_CHR);
4688               if (p != NULL && p[1] != ELF_VER_CHR)
4689                 {
4690                   /* Queue non-default versions so that .symver x, x@FOO
4691                      aliases can be checked.  */
4692                   if (!nondeflt_vers)
4693                     {
4694                       amt = ((isymend - isym + 1)
4695                              * sizeof (struct elf_link_hash_entry *));
4696                       nondeflt_vers
4697                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4698                       if (!nondeflt_vers)
4699                         goto error_free_vers;
4700                     }
4701                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4702                 }
4703             }
4704
4705           if (dynsym && h->dynindx == -1)
4706             {
4707               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4708                 goto error_free_vers;
4709               if (h->u.weakdef != NULL
4710                   && ! new_weakdef
4711                   && h->u.weakdef->dynindx == -1)
4712                 {
4713                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4714                     goto error_free_vers;
4715                 }
4716             }
4717           else if (h->dynindx != -1)
4718             /* If the symbol already has a dynamic index, but
4719                visibility says it should not be visible, turn it into
4720                a local symbol.  */
4721             switch (ELF_ST_VISIBILITY (h->other))
4722               {
4723               case STV_INTERNAL:
4724               case STV_HIDDEN:
4725                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4726                 dynsym = FALSE;
4727                 break;
4728               }
4729
4730           /* Don't add DT_NEEDED for references from the dummy bfd nor
4731              for unmatched symbol.  */
4732           if (!add_needed
4733               && matched
4734               && definition
4735               && ((dynsym
4736                    && h->ref_regular_nonweak
4737                    && (old_bfd == NULL
4738                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4739                   || (h->ref_dynamic_nonweak
4740                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4741                       && !on_needed_list (elf_dt_name (abfd),
4742                                           htab->needed, NULL))))
4743             {
4744               int ret;
4745               const char *soname = elf_dt_name (abfd);
4746
4747               info->callbacks->minfo ("%!", soname, old_bfd,
4748                                       h->root.root.string);
4749
4750               /* A symbol from a library loaded via DT_NEEDED of some
4751                  other library is referenced by a regular object.
4752                  Add a DT_NEEDED entry for it.  Issue an error if
4753                  --no-add-needed is used and the reference was not
4754                  a weak one.  */
4755               if (old_bfd != NULL
4756                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4757                 {
4758                   (*_bfd_error_handler)
4759                     (_("%B: undefined reference to symbol '%s'"),
4760                      old_bfd, name);
4761                   bfd_set_error (bfd_error_missing_dso);
4762                   goto error_free_vers;
4763                 }
4764
4765               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4766                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4767
4768               add_needed = TRUE;
4769               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4770               if (ret < 0)
4771                 goto error_free_vers;
4772
4773               BFD_ASSERT (ret == 0);
4774             }
4775         }
4776     }
4777
4778   if (extversym != NULL)
4779     {
4780       free (extversym);
4781       extversym = NULL;
4782     }
4783
4784   if (isymbuf != NULL)
4785     {
4786       free (isymbuf);
4787       isymbuf = NULL;
4788     }
4789
4790   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4791     {
4792       unsigned int i;
4793
4794       /* Restore the symbol table.  */
4795       old_ent = (char *) old_tab + tabsize;
4796       memset (elf_sym_hashes (abfd), 0,
4797               extsymcount * sizeof (struct elf_link_hash_entry *));
4798       htab->root.table.table = old_table;
4799       htab->root.table.size = old_size;
4800       htab->root.table.count = old_count;
4801       memcpy (htab->root.table.table, old_tab, tabsize);
4802       htab->root.undefs = old_undefs;
4803       htab->root.undefs_tail = old_undefs_tail;
4804       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4805       free (old_strtab);
4806       old_strtab = NULL;
4807       for (i = 0; i < htab->root.table.size; i++)
4808         {
4809           struct bfd_hash_entry *p;
4810           struct elf_link_hash_entry *h;
4811           bfd_size_type size;
4812           unsigned int alignment_power;
4813
4814           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4815             {
4816               h = (struct elf_link_hash_entry *) p;
4817               if (h->root.type == bfd_link_hash_warning)
4818                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4819
4820               /* Preserve the maximum alignment and size for common
4821                  symbols even if this dynamic lib isn't on DT_NEEDED
4822                  since it can still be loaded at run time by another
4823                  dynamic lib.  */
4824               if (h->root.type == bfd_link_hash_common)
4825                 {
4826                   size = h->root.u.c.size;
4827                   alignment_power = h->root.u.c.p->alignment_power;
4828                 }
4829               else
4830                 {
4831                   size = 0;
4832                   alignment_power = 0;
4833                 }
4834               memcpy (p, old_ent, htab->root.table.entsize);
4835               old_ent = (char *) old_ent + htab->root.table.entsize;
4836               h = (struct elf_link_hash_entry *) p;
4837               if (h->root.type == bfd_link_hash_warning)
4838                 {
4839                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4840                   old_ent = (char *) old_ent + htab->root.table.entsize;
4841                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4842                 }
4843               if (h->root.type == bfd_link_hash_common)
4844                 {
4845                   if (size > h->root.u.c.size)
4846                     h->root.u.c.size = size;
4847                   if (alignment_power > h->root.u.c.p->alignment_power)
4848                     h->root.u.c.p->alignment_power = alignment_power;
4849                 }
4850             }
4851         }
4852
4853       /* Make a special call to the linker "notice" function to
4854          tell it that symbols added for crefs may need to be removed.  */
4855       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4856         goto error_free_vers;
4857
4858       free (old_tab);
4859       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4860                            alloc_mark);
4861       if (nondeflt_vers != NULL)
4862         free (nondeflt_vers);
4863       return TRUE;
4864     }
4865
4866   if (old_tab != NULL)
4867     {
4868       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4869         goto error_free_vers;
4870       free (old_tab);
4871       old_tab = NULL;
4872     }
4873
4874   /* Now that all the symbols from this input file are created, if
4875      not performing a relocatable link, handle .symver foo, foo@BAR
4876      such that any relocs against foo become foo@BAR.  */
4877   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4878     {
4879       size_t cnt, symidx;
4880
4881       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4882         {
4883           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4884           char *shortname, *p;
4885
4886           p = strchr (h->root.root.string, ELF_VER_CHR);
4887           if (p == NULL
4888               || (h->root.type != bfd_link_hash_defined
4889                   && h->root.type != bfd_link_hash_defweak))
4890             continue;
4891
4892           amt = p - h->root.root.string;
4893           shortname = (char *) bfd_malloc (amt + 1);
4894           if (!shortname)
4895             goto error_free_vers;
4896           memcpy (shortname, h->root.root.string, amt);
4897           shortname[amt] = '\0';
4898
4899           hi = (struct elf_link_hash_entry *)
4900                bfd_link_hash_lookup (&htab->root, shortname,
4901                                      FALSE, FALSE, FALSE);
4902           if (hi != NULL
4903               && hi->root.type == h->root.type
4904               && hi->root.u.def.value == h->root.u.def.value
4905               && hi->root.u.def.section == h->root.u.def.section)
4906             {
4907               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4908               hi->root.type = bfd_link_hash_indirect;
4909               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4910               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4911               sym_hash = elf_sym_hashes (abfd);
4912               if (sym_hash)
4913                 for (symidx = 0; symidx < extsymcount; ++symidx)
4914                   if (sym_hash[symidx] == hi)
4915                     {
4916                       sym_hash[symidx] = h;
4917                       break;
4918                     }
4919             }
4920           free (shortname);
4921         }
4922       free (nondeflt_vers);
4923       nondeflt_vers = NULL;
4924     }
4925
4926   /* Now set the weakdefs field correctly for all the weak defined
4927      symbols we found.  The only way to do this is to search all the
4928      symbols.  Since we only need the information for non functions in
4929      dynamic objects, that's the only time we actually put anything on
4930      the list WEAKS.  We need this information so that if a regular
4931      object refers to a symbol defined weakly in a dynamic object, the
4932      real symbol in the dynamic object is also put in the dynamic
4933      symbols; we also must arrange for both symbols to point to the
4934      same memory location.  We could handle the general case of symbol
4935      aliasing, but a general symbol alias can only be generated in
4936      assembler code, handling it correctly would be very time
4937      consuming, and other ELF linkers don't handle general aliasing
4938      either.  */
4939   if (weaks != NULL)
4940     {
4941       struct elf_link_hash_entry **hpp;
4942       struct elf_link_hash_entry **hppend;
4943       struct elf_link_hash_entry **sorted_sym_hash;
4944       struct elf_link_hash_entry *h;
4945       size_t sym_count;
4946
4947       /* Since we have to search the whole symbol list for each weak
4948          defined symbol, search time for N weak defined symbols will be
4949          O(N^2). Binary search will cut it down to O(NlogN).  */
4950       amt = extsymcount;
4951       amt *= sizeof (struct elf_link_hash_entry *);
4952       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4953       if (sorted_sym_hash == NULL)
4954         goto error_return;
4955       sym_hash = sorted_sym_hash;
4956       hpp = elf_sym_hashes (abfd);
4957       hppend = hpp + extsymcount;
4958       sym_count = 0;
4959       for (; hpp < hppend; hpp++)
4960         {
4961           h = *hpp;
4962           if (h != NULL
4963               && h->root.type == bfd_link_hash_defined
4964               && !bed->is_function_type (h->type))
4965             {
4966               *sym_hash = h;
4967               sym_hash++;
4968               sym_count++;
4969             }
4970         }
4971
4972       qsort (sorted_sym_hash, sym_count,
4973              sizeof (struct elf_link_hash_entry *),
4974              elf_sort_symbol);
4975
4976       while (weaks != NULL)
4977         {
4978           struct elf_link_hash_entry *hlook;
4979           asection *slook;
4980           bfd_vma vlook;
4981           size_t i, j, idx = 0;
4982
4983           hlook = weaks;
4984           weaks = hlook->u.weakdef;
4985           hlook->u.weakdef = NULL;
4986
4987           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4988                       || hlook->root.type == bfd_link_hash_defweak
4989                       || hlook->root.type == bfd_link_hash_common
4990                       || hlook->root.type == bfd_link_hash_indirect);
4991           slook = hlook->root.u.def.section;
4992           vlook = hlook->root.u.def.value;
4993
4994           i = 0;
4995           j = sym_count;
4996           while (i != j)
4997             {
4998               bfd_signed_vma vdiff;
4999               idx = (i + j) / 2;
5000               h = sorted_sym_hash[idx];
5001               vdiff = vlook - h->root.u.def.value;
5002               if (vdiff < 0)
5003                 j = idx;
5004               else if (vdiff > 0)
5005                 i = idx + 1;
5006               else
5007                 {
5008                   int sdiff = slook->id - h->root.u.def.section->id;
5009                   if (sdiff < 0)
5010                     j = idx;
5011                   else if (sdiff > 0)
5012                     i = idx + 1;
5013                   else
5014                     break;
5015                 }
5016             }
5017
5018           /* We didn't find a value/section match.  */
5019           if (i == j)
5020             continue;
5021
5022           /* With multiple aliases, or when the weak symbol is already
5023              strongly defined, we have multiple matching symbols and
5024              the binary search above may land on any of them.  Step
5025              one past the matching symbol(s).  */
5026           while (++idx != j)
5027             {
5028               h = sorted_sym_hash[idx];
5029               if (h->root.u.def.section != slook
5030                   || h->root.u.def.value != vlook)
5031                 break;
5032             }
5033
5034           /* Now look back over the aliases.  Since we sorted by size
5035              as well as value and section, we'll choose the one with
5036              the largest size.  */
5037           while (idx-- != i)
5038             {
5039               h = sorted_sym_hash[idx];
5040
5041               /* Stop if value or section doesn't match.  */
5042               if (h->root.u.def.section != slook
5043                   || h->root.u.def.value != vlook)
5044                 break;
5045               else if (h != hlook)
5046                 {
5047                   hlook->u.weakdef = h;
5048
5049                   /* If the weak definition is in the list of dynamic
5050                      symbols, make sure the real definition is put
5051                      there as well.  */
5052                   if (hlook->dynindx != -1 && h->dynindx == -1)
5053                     {
5054                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5055                         {
5056                         err_free_sym_hash:
5057                           free (sorted_sym_hash);
5058                           goto error_return;
5059                         }
5060                     }
5061
5062                   /* If the real definition is in the list of dynamic
5063                      symbols, make sure the weak definition is put
5064                      there as well.  If we don't do this, then the
5065                      dynamic loader might not merge the entries for the
5066                      real definition and the weak definition.  */
5067                   if (h->dynindx != -1 && hlook->dynindx == -1)
5068                     {
5069                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5070                         goto err_free_sym_hash;
5071                     }
5072                   break;
5073                 }
5074             }
5075         }
5076
5077       free (sorted_sym_hash);
5078     }
5079
5080   if (bed->check_directives
5081       && !(*bed->check_directives) (abfd, info))
5082     return FALSE;
5083
5084   if (!info->check_relocs_after_open_input
5085       && !_bfd_elf_link_check_relocs (abfd, info))
5086     return FALSE;
5087
5088   /* If this is a non-traditional link, try to optimize the handling
5089      of the .stab/.stabstr sections.  */
5090   if (! dynamic
5091       && ! info->traditional_format
5092       && is_elf_hash_table (htab)
5093       && (info->strip != strip_all && info->strip != strip_debugger))
5094     {
5095       asection *stabstr;
5096
5097       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5098       if (stabstr != NULL)
5099         {
5100           bfd_size_type string_offset = 0;
5101           asection *stab;
5102
5103           for (stab = abfd->sections; stab; stab = stab->next)
5104             if (CONST_STRNEQ (stab->name, ".stab")
5105                 && (!stab->name[5] ||
5106                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5107                 && (stab->flags & SEC_MERGE) == 0
5108                 && !bfd_is_abs_section (stab->output_section))
5109               {
5110                 struct bfd_elf_section_data *secdata;
5111
5112                 secdata = elf_section_data (stab);
5113                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5114                                                stabstr, &secdata->sec_info,
5115                                                &string_offset))
5116                   goto error_return;
5117                 if (secdata->sec_info)
5118                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5119             }
5120         }
5121     }
5122
5123   if (is_elf_hash_table (htab) && add_needed)
5124     {
5125       /* Add this bfd to the loaded list.  */
5126       struct elf_link_loaded_list *n;
5127
5128       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5129       if (n == NULL)
5130         goto error_return;
5131       n->abfd = abfd;
5132       n->next = htab->loaded;
5133       htab->loaded = n;
5134     }
5135
5136   return TRUE;
5137
5138  error_free_vers:
5139   if (old_tab != NULL)
5140     free (old_tab);
5141   if (old_strtab != NULL)
5142     free (old_strtab);
5143   if (nondeflt_vers != NULL)
5144     free (nondeflt_vers);
5145   if (extversym != NULL)
5146     free (extversym);
5147  error_free_sym:
5148   if (isymbuf != NULL)
5149     free (isymbuf);
5150  error_return:
5151   return FALSE;
5152 }
5153
5154 /* Return the linker hash table entry of a symbol that might be
5155    satisfied by an archive symbol.  Return -1 on error.  */
5156
5157 struct elf_link_hash_entry *
5158 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5159                                 struct bfd_link_info *info,
5160                                 const char *name)
5161 {
5162   struct elf_link_hash_entry *h;
5163   char *p, *copy;
5164   size_t len, first;
5165
5166   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5167   if (h != NULL)
5168     return h;
5169
5170   /* If this is a default version (the name contains @@), look up the
5171      symbol again with only one `@' as well as without the version.
5172      The effect is that references to the symbol with and without the
5173      version will be matched by the default symbol in the archive.  */
5174
5175   p = strchr (name, ELF_VER_CHR);
5176   if (p == NULL || p[1] != ELF_VER_CHR)
5177     return h;
5178
5179   /* First check with only one `@'.  */
5180   len = strlen (name);
5181   copy = (char *) bfd_alloc (abfd, len);
5182   if (copy == NULL)
5183     return (struct elf_link_hash_entry *) 0 - 1;
5184
5185   first = p - name + 1;
5186   memcpy (copy, name, first);
5187   memcpy (copy + first, name + first + 1, len - first);
5188
5189   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5190   if (h == NULL)
5191     {
5192       /* We also need to check references to the symbol without the
5193          version.  */
5194       copy[first - 1] = '\0';
5195       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5196                                 FALSE, FALSE, TRUE);
5197     }
5198
5199   bfd_release (abfd, copy);
5200   return h;
5201 }
5202
5203 /* Add symbols from an ELF archive file to the linker hash table.  We
5204    don't use _bfd_generic_link_add_archive_symbols because we need to
5205    handle versioned symbols.
5206
5207    Fortunately, ELF archive handling is simpler than that done by
5208    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5209    oddities.  In ELF, if we find a symbol in the archive map, and the
5210    symbol is currently undefined, we know that we must pull in that
5211    object file.
5212
5213    Unfortunately, we do have to make multiple passes over the symbol
5214    table until nothing further is resolved.  */
5215
5216 static bfd_boolean
5217 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5218 {
5219   symindex c;
5220   unsigned char *included = NULL;
5221   carsym *symdefs;
5222   bfd_boolean loop;
5223   bfd_size_type amt;
5224   const struct elf_backend_data *bed;
5225   struct elf_link_hash_entry * (*archive_symbol_lookup)
5226     (bfd *, struct bfd_link_info *, const char *);
5227
5228   if (! bfd_has_map (abfd))
5229     {
5230       /* An empty archive is a special case.  */
5231       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5232         return TRUE;
5233       bfd_set_error (bfd_error_no_armap);
5234       return FALSE;
5235     }
5236
5237   /* Keep track of all symbols we know to be already defined, and all
5238      files we know to be already included.  This is to speed up the
5239      second and subsequent passes.  */
5240   c = bfd_ardata (abfd)->symdef_count;
5241   if (c == 0)
5242     return TRUE;
5243   amt = c;
5244   amt *= sizeof (*included);
5245   included = (unsigned char *) bfd_zmalloc (amt);
5246   if (included == NULL)
5247     return FALSE;
5248
5249   symdefs = bfd_ardata (abfd)->symdefs;
5250   bed = get_elf_backend_data (abfd);
5251   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5252
5253   do
5254     {
5255       file_ptr last;
5256       symindex i;
5257       carsym *symdef;
5258       carsym *symdefend;
5259
5260       loop = FALSE;
5261       last = -1;
5262
5263       symdef = symdefs;
5264       symdefend = symdef + c;
5265       for (i = 0; symdef < symdefend; symdef++, i++)
5266         {
5267           struct elf_link_hash_entry *h;
5268           bfd *element;
5269           struct bfd_link_hash_entry *undefs_tail;
5270           symindex mark;
5271
5272           if (included[i])
5273             continue;
5274           if (symdef->file_offset == last)
5275             {
5276               included[i] = TRUE;
5277               continue;
5278             }
5279
5280           h = archive_symbol_lookup (abfd, info, symdef->name);
5281           if (h == (struct elf_link_hash_entry *) 0 - 1)
5282             goto error_return;
5283
5284           if (h == NULL)
5285             continue;
5286
5287           if (h->root.type == bfd_link_hash_common)
5288             {
5289               /* We currently have a common symbol.  The archive map contains
5290                  a reference to this symbol, so we may want to include it.  We
5291                  only want to include it however, if this archive element
5292                  contains a definition of the symbol, not just another common
5293                  declaration of it.
5294
5295                  Unfortunately some archivers (including GNU ar) will put
5296                  declarations of common symbols into their archive maps, as
5297                  well as real definitions, so we cannot just go by the archive
5298                  map alone.  Instead we must read in the element's symbol
5299                  table and check that to see what kind of symbol definition
5300                  this is.  */
5301               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5302                 continue;
5303             }
5304           else if (h->root.type != bfd_link_hash_undefined)
5305             {
5306               if (h->root.type != bfd_link_hash_undefweak)
5307                 /* Symbol must be defined.  Don't check it again.  */
5308                 included[i] = TRUE;
5309               continue;
5310             }
5311
5312           /* We need to include this archive member.  */
5313           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5314           if (element == NULL)
5315             goto error_return;
5316
5317           if (! bfd_check_format (element, bfd_object))
5318             goto error_return;
5319
5320           undefs_tail = info->hash->undefs_tail;
5321
5322           if (!(*info->callbacks
5323                 ->add_archive_element) (info, element, symdef->name, &element))
5324             continue;
5325           if (!bfd_link_add_symbols (element, info))
5326             goto error_return;
5327
5328           /* If there are any new undefined symbols, we need to make
5329              another pass through the archive in order to see whether
5330              they can be defined.  FIXME: This isn't perfect, because
5331              common symbols wind up on undefs_tail and because an
5332              undefined symbol which is defined later on in this pass
5333              does not require another pass.  This isn't a bug, but it
5334              does make the code less efficient than it could be.  */
5335           if (undefs_tail != info->hash->undefs_tail)
5336             loop = TRUE;
5337
5338           /* Look backward to mark all symbols from this object file
5339              which we have already seen in this pass.  */
5340           mark = i;
5341           do
5342             {
5343               included[mark] = TRUE;
5344               if (mark == 0)
5345                 break;
5346               --mark;
5347             }
5348           while (symdefs[mark].file_offset == symdef->file_offset);
5349
5350           /* We mark subsequent symbols from this object file as we go
5351              on through the loop.  */
5352           last = symdef->file_offset;
5353         }
5354     }
5355   while (loop);
5356
5357   free (included);
5358
5359   return TRUE;
5360
5361  error_return:
5362   if (included != NULL)
5363     free (included);
5364   return FALSE;
5365 }
5366
5367 /* Given an ELF BFD, add symbols to the global hash table as
5368    appropriate.  */
5369
5370 bfd_boolean
5371 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5372 {
5373   switch (bfd_get_format (abfd))
5374     {
5375     case bfd_object:
5376       return elf_link_add_object_symbols (abfd, info);
5377     case bfd_archive:
5378       return elf_link_add_archive_symbols (abfd, info);
5379     default:
5380       bfd_set_error (bfd_error_wrong_format);
5381       return FALSE;
5382     }
5383 }
5384 \f
5385 struct hash_codes_info
5386 {
5387   unsigned long *hashcodes;
5388   bfd_boolean error;
5389 };
5390
5391 /* This function will be called though elf_link_hash_traverse to store
5392    all hash value of the exported symbols in an array.  */
5393
5394 static bfd_boolean
5395 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5396 {
5397   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5398   const char *name;
5399   unsigned long ha;
5400   char *alc = NULL;
5401
5402   /* Ignore indirect symbols.  These are added by the versioning code.  */
5403   if (h->dynindx == -1)
5404     return TRUE;
5405
5406   name = h->root.root.string;
5407   if (h->versioned >= versioned)
5408     {
5409       char *p = strchr (name, ELF_VER_CHR);
5410       if (p != NULL)
5411         {
5412           alc = (char *) bfd_malloc (p - name + 1);
5413           if (alc == NULL)
5414             {
5415               inf->error = TRUE;
5416               return FALSE;
5417             }
5418           memcpy (alc, name, p - name);
5419           alc[p - name] = '\0';
5420           name = alc;
5421         }
5422     }
5423
5424   /* Compute the hash value.  */
5425   ha = bfd_elf_hash (name);
5426
5427   /* Store the found hash value in the array given as the argument.  */
5428   *(inf->hashcodes)++ = ha;
5429
5430   /* And store it in the struct so that we can put it in the hash table
5431      later.  */
5432   h->u.elf_hash_value = ha;
5433
5434   if (alc != NULL)
5435     free (alc);
5436
5437   return TRUE;
5438 }
5439
5440 struct collect_gnu_hash_codes
5441 {
5442   bfd *output_bfd;
5443   const struct elf_backend_data *bed;
5444   unsigned long int nsyms;
5445   unsigned long int maskbits;
5446   unsigned long int *hashcodes;
5447   unsigned long int *hashval;
5448   unsigned long int *indx;
5449   unsigned long int *counts;
5450   bfd_vma *bitmask;
5451   bfd_byte *contents;
5452   long int min_dynindx;
5453   unsigned long int bucketcount;
5454   unsigned long int symindx;
5455   long int local_indx;
5456   long int shift1, shift2;
5457   unsigned long int mask;
5458   bfd_boolean error;
5459 };
5460
5461 /* This function will be called though elf_link_hash_traverse to store
5462    all hash value of the exported symbols in an array.  */
5463
5464 static bfd_boolean
5465 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5466 {
5467   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5468   const char *name;
5469   unsigned long ha;
5470   char *alc = NULL;
5471
5472   /* Ignore indirect symbols.  These are added by the versioning code.  */
5473   if (h->dynindx == -1)
5474     return TRUE;
5475
5476   /* Ignore also local symbols and undefined symbols.  */
5477   if (! (*s->bed->elf_hash_symbol) (h))
5478     return TRUE;
5479
5480   name = h->root.root.string;
5481   if (h->versioned >= versioned)
5482     {
5483       char *p = strchr (name, ELF_VER_CHR);
5484       if (p != NULL)
5485         {
5486           alc = (char *) bfd_malloc (p - name + 1);
5487           if (alc == NULL)
5488             {
5489               s->error = TRUE;
5490               return FALSE;
5491             }
5492           memcpy (alc, name, p - name);
5493           alc[p - name] = '\0';
5494           name = alc;
5495         }
5496     }
5497
5498   /* Compute the hash value.  */
5499   ha = bfd_elf_gnu_hash (name);
5500
5501   /* Store the found hash value in the array for compute_bucket_count,
5502      and also for .dynsym reordering purposes.  */
5503   s->hashcodes[s->nsyms] = ha;
5504   s->hashval[h->dynindx] = ha;
5505   ++s->nsyms;
5506   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5507     s->min_dynindx = h->dynindx;
5508
5509   if (alc != NULL)
5510     free (alc);
5511
5512   return TRUE;
5513 }
5514
5515 /* This function will be called though elf_link_hash_traverse to do
5516    final dynaminc symbol renumbering.  */
5517
5518 static bfd_boolean
5519 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5520 {
5521   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5522   unsigned long int bucket;
5523   unsigned long int val;
5524
5525   /* Ignore indirect symbols.  */
5526   if (h->dynindx == -1)
5527     return TRUE;
5528
5529   /* Ignore also local symbols and undefined symbols.  */
5530   if (! (*s->bed->elf_hash_symbol) (h))
5531     {
5532       if (h->dynindx >= s->min_dynindx)
5533         h->dynindx = s->local_indx++;
5534       return TRUE;
5535     }
5536
5537   bucket = s->hashval[h->dynindx] % s->bucketcount;
5538   val = (s->hashval[h->dynindx] >> s->shift1)
5539         & ((s->maskbits >> s->shift1) - 1);
5540   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5541   s->bitmask[val]
5542     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5543   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5544   if (s->counts[bucket] == 1)
5545     /* Last element terminates the chain.  */
5546     val |= 1;
5547   bfd_put_32 (s->output_bfd, val,
5548               s->contents + (s->indx[bucket] - s->symindx) * 4);
5549   --s->counts[bucket];
5550   h->dynindx = s->indx[bucket]++;
5551   return TRUE;
5552 }
5553
5554 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5555
5556 bfd_boolean
5557 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5558 {
5559   return !(h->forced_local
5560            || h->root.type == bfd_link_hash_undefined
5561            || h->root.type == bfd_link_hash_undefweak
5562            || ((h->root.type == bfd_link_hash_defined
5563                 || h->root.type == bfd_link_hash_defweak)
5564                && h->root.u.def.section->output_section == NULL));
5565 }
5566
5567 /* Array used to determine the number of hash table buckets to use
5568    based on the number of symbols there are.  If there are fewer than
5569    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5570    fewer than 37 we use 17 buckets, and so forth.  We never use more
5571    than 32771 buckets.  */
5572
5573 static const size_t elf_buckets[] =
5574 {
5575   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5576   16411, 32771, 0
5577 };
5578
5579 /* Compute bucket count for hashing table.  We do not use a static set
5580    of possible tables sizes anymore.  Instead we determine for all
5581    possible reasonable sizes of the table the outcome (i.e., the
5582    number of collisions etc) and choose the best solution.  The
5583    weighting functions are not too simple to allow the table to grow
5584    without bounds.  Instead one of the weighting factors is the size.
5585    Therefore the result is always a good payoff between few collisions
5586    (= short chain lengths) and table size.  */
5587 static size_t
5588 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5589                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5590                       unsigned long int nsyms,
5591                       int gnu_hash)
5592 {
5593   size_t best_size = 0;
5594   unsigned long int i;
5595
5596   /* We have a problem here.  The following code to optimize the table
5597      size requires an integer type with more the 32 bits.  If
5598      BFD_HOST_U_64_BIT is set we know about such a type.  */
5599 #ifdef BFD_HOST_U_64_BIT
5600   if (info->optimize)
5601     {
5602       size_t minsize;
5603       size_t maxsize;
5604       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5605       bfd *dynobj = elf_hash_table (info)->dynobj;
5606       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5607       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5608       unsigned long int *counts;
5609       bfd_size_type amt;
5610       unsigned int no_improvement_count = 0;
5611
5612       /* Possible optimization parameters: if we have NSYMS symbols we say
5613          that the hashing table must at least have NSYMS/4 and at most
5614          2*NSYMS buckets.  */
5615       minsize = nsyms / 4;
5616       if (minsize == 0)
5617         minsize = 1;
5618       best_size = maxsize = nsyms * 2;
5619       if (gnu_hash)
5620         {
5621           if (minsize < 2)
5622             minsize = 2;
5623           if ((best_size & 31) == 0)
5624             ++best_size;
5625         }
5626
5627       /* Create array where we count the collisions in.  We must use bfd_malloc
5628          since the size could be large.  */
5629       amt = maxsize;
5630       amt *= sizeof (unsigned long int);
5631       counts = (unsigned long int *) bfd_malloc (amt);
5632       if (counts == NULL)
5633         return 0;
5634
5635       /* Compute the "optimal" size for the hash table.  The criteria is a
5636          minimal chain length.  The minor criteria is (of course) the size
5637          of the table.  */
5638       for (i = minsize; i < maxsize; ++i)
5639         {
5640           /* Walk through the array of hashcodes and count the collisions.  */
5641           BFD_HOST_U_64_BIT max;
5642           unsigned long int j;
5643           unsigned long int fact;
5644
5645           if (gnu_hash && (i & 31) == 0)
5646             continue;
5647
5648           memset (counts, '\0', i * sizeof (unsigned long int));
5649
5650           /* Determine how often each hash bucket is used.  */
5651           for (j = 0; j < nsyms; ++j)
5652             ++counts[hashcodes[j] % i];
5653
5654           /* For the weight function we need some information about the
5655              pagesize on the target.  This is information need not be 100%
5656              accurate.  Since this information is not available (so far) we
5657              define it here to a reasonable default value.  If it is crucial
5658              to have a better value some day simply define this value.  */
5659 # ifndef BFD_TARGET_PAGESIZE
5660 #  define BFD_TARGET_PAGESIZE   (4096)
5661 # endif
5662
5663           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5664              and the chains.  */
5665           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5666
5667 # if 1
5668           /* Variant 1: optimize for short chains.  We add the squares
5669              of all the chain lengths (which favors many small chain
5670              over a few long chains).  */
5671           for (j = 0; j < i; ++j)
5672             max += counts[j] * counts[j];
5673
5674           /* This adds penalties for the overall size of the table.  */
5675           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5676           max *= fact * fact;
5677 # else
5678           /* Variant 2: Optimize a lot more for small table.  Here we
5679              also add squares of the size but we also add penalties for
5680              empty slots (the +1 term).  */
5681           for (j = 0; j < i; ++j)
5682             max += (1 + counts[j]) * (1 + counts[j]);
5683
5684           /* The overall size of the table is considered, but not as
5685              strong as in variant 1, where it is squared.  */
5686           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5687           max *= fact;
5688 # endif
5689
5690           /* Compare with current best results.  */
5691           if (max < best_chlen)
5692             {
5693               best_chlen = max;
5694               best_size = i;
5695               no_improvement_count = 0;
5696             }
5697           /* PR 11843: Avoid futile long searches for the best bucket size
5698              when there are a large number of symbols.  */
5699           else if (++no_improvement_count == 100)
5700             break;
5701         }
5702
5703       free (counts);
5704     }
5705   else
5706 #endif /* defined (BFD_HOST_U_64_BIT) */
5707     {
5708       /* This is the fallback solution if no 64bit type is available or if we
5709          are not supposed to spend much time on optimizations.  We select the
5710          bucket count using a fixed set of numbers.  */
5711       for (i = 0; elf_buckets[i] != 0; i++)
5712         {
5713           best_size = elf_buckets[i];
5714           if (nsyms < elf_buckets[i + 1])
5715             break;
5716         }
5717       if (gnu_hash && best_size < 2)
5718         best_size = 2;
5719     }
5720
5721   return best_size;
5722 }
5723
5724 /* Size any SHT_GROUP section for ld -r.  */
5725
5726 bfd_boolean
5727 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5728 {
5729   bfd *ibfd;
5730
5731   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5732     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5733         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5734       return FALSE;
5735   return TRUE;
5736 }
5737
5738 /* Set a default stack segment size.  The value in INFO wins.  If it
5739    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5740    undefined it is initialized.  */
5741
5742 bfd_boolean
5743 bfd_elf_stack_segment_size (bfd *output_bfd,
5744                             struct bfd_link_info *info,
5745                             const char *legacy_symbol,
5746                             bfd_vma default_size)
5747 {
5748   struct elf_link_hash_entry *h = NULL;
5749
5750   /* Look for legacy symbol.  */
5751   if (legacy_symbol)
5752     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5753                               FALSE, FALSE, FALSE);
5754   if (h && (h->root.type == bfd_link_hash_defined
5755             || h->root.type == bfd_link_hash_defweak)
5756       && h->def_regular
5757       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5758     {
5759       /* The symbol has no type if specified on the command line.  */
5760       h->type = STT_OBJECT;
5761       if (info->stacksize)
5762         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5763                                output_bfd, legacy_symbol);
5764       else if (h->root.u.def.section != bfd_abs_section_ptr)
5765         (*_bfd_error_handler) (_("%B: %s not absolute"),
5766                                output_bfd, legacy_symbol);
5767       else
5768         info->stacksize = h->root.u.def.value;
5769     }
5770
5771   if (!info->stacksize)
5772     /* If the user didn't set a size, or explicitly inhibit the
5773        size, set it now.  */
5774     info->stacksize = default_size;
5775
5776   /* Provide the legacy symbol, if it is referenced.  */
5777   if (h && (h->root.type == bfd_link_hash_undefined
5778             || h->root.type == bfd_link_hash_undefweak))
5779     {
5780       struct bfd_link_hash_entry *bh = NULL;
5781
5782       if (!(_bfd_generic_link_add_one_symbol
5783             (info, output_bfd, legacy_symbol,
5784              BSF_GLOBAL, bfd_abs_section_ptr,
5785              info->stacksize >= 0 ? info->stacksize : 0,
5786              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5787         return FALSE;
5788
5789       h = (struct elf_link_hash_entry *) bh;
5790       h->def_regular = 1;
5791       h->type = STT_OBJECT;
5792     }
5793
5794   return TRUE;
5795 }
5796
5797 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5798    called by the ELF linker emulation before_allocation routine.  We
5799    must set the sizes of the sections before the linker sets the
5800    addresses of the various sections.  */
5801
5802 bfd_boolean
5803 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5804                                const char *soname,
5805                                const char *rpath,
5806                                const char *filter_shlib,
5807                                const char *audit,
5808                                const char *depaudit,
5809                                const char * const *auxiliary_filters,
5810                                struct bfd_link_info *info,
5811                                asection **sinterpptr)
5812 {
5813   size_t soname_indx;
5814   bfd *dynobj;
5815   const struct elf_backend_data *bed;
5816   struct elf_info_failed asvinfo;
5817
5818   *sinterpptr = NULL;
5819
5820   soname_indx = (size_t) -1;
5821
5822   if (!is_elf_hash_table (info->hash))
5823     return TRUE;
5824
5825   bed = get_elf_backend_data (output_bfd);
5826
5827   /* Any syms created from now on start with -1 in
5828      got.refcount/offset and plt.refcount/offset.  */
5829   elf_hash_table (info)->init_got_refcount
5830     = elf_hash_table (info)->init_got_offset;
5831   elf_hash_table (info)->init_plt_refcount
5832     = elf_hash_table (info)->init_plt_offset;
5833
5834   if (bfd_link_relocatable (info)
5835       && !_bfd_elf_size_group_sections (info))
5836     return FALSE;
5837
5838   /* The backend may have to create some sections regardless of whether
5839      we're dynamic or not.  */
5840   if (bed->elf_backend_always_size_sections
5841       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5842     return FALSE;
5843
5844   /* Determine any GNU_STACK segment requirements, after the backend
5845      has had a chance to set a default segment size.  */
5846   if (info->execstack)
5847     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5848   else if (info->noexecstack)
5849     elf_stack_flags (output_bfd) = PF_R | PF_W;
5850   else
5851     {
5852       bfd *inputobj;
5853       asection *notesec = NULL;
5854       int exec = 0;
5855
5856       for (inputobj = info->input_bfds;
5857            inputobj;
5858            inputobj = inputobj->link.next)
5859         {
5860           asection *s;
5861
5862           if (inputobj->flags
5863               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5864             continue;
5865           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5866           if (s)
5867             {
5868               if (s->flags & SEC_CODE)
5869                 exec = PF_X;
5870               notesec = s;
5871             }
5872           else if (bed->default_execstack)
5873             exec = PF_X;
5874         }
5875       if (notesec || info->stacksize > 0)
5876         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5877       if (notesec && exec && bfd_link_relocatable (info)
5878           && notesec->output_section != bfd_abs_section_ptr)
5879         notesec->output_section->flags |= SEC_CODE;
5880     }
5881
5882   dynobj = elf_hash_table (info)->dynobj;
5883
5884   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5885     {
5886       struct elf_info_failed eif;
5887       struct elf_link_hash_entry *h;
5888       asection *dynstr;
5889       struct bfd_elf_version_tree *t;
5890       struct bfd_elf_version_expr *d;
5891       asection *s;
5892       bfd_boolean all_defined;
5893
5894       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5895       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
5896
5897       if (soname != NULL)
5898         {
5899           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5900                                              soname, TRUE);
5901           if (soname_indx == (size_t) -1
5902               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5903             return FALSE;
5904         }
5905
5906       if (info->symbolic)
5907         {
5908           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5909             return FALSE;
5910           info->flags |= DF_SYMBOLIC;
5911         }
5912
5913       if (rpath != NULL)
5914         {
5915           size_t indx;
5916           bfd_vma tag;
5917
5918           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5919                                       TRUE);
5920           if (indx == (size_t) -1)
5921             return FALSE;
5922
5923           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5924           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5925             return FALSE;
5926         }
5927
5928       if (filter_shlib != NULL)
5929         {
5930           size_t indx;
5931
5932           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5933                                       filter_shlib, TRUE);
5934           if (indx == (size_t) -1
5935               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5936             return FALSE;
5937         }
5938
5939       if (auxiliary_filters != NULL)
5940         {
5941           const char * const *p;
5942
5943           for (p = auxiliary_filters; *p != NULL; p++)
5944             {
5945               size_t indx;
5946
5947               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5948                                           *p, TRUE);
5949               if (indx == (size_t) -1
5950                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5951                 return FALSE;
5952             }
5953         }
5954
5955       if (audit != NULL)
5956         {
5957           size_t indx;
5958
5959           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5960                                       TRUE);
5961           if (indx == (size_t) -1
5962               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5963             return FALSE;
5964         }
5965
5966       if (depaudit != NULL)
5967         {
5968           size_t indx;
5969
5970           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5971                                       TRUE);
5972           if (indx == (size_t) -1
5973               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5974             return FALSE;
5975         }
5976
5977       eif.info = info;
5978       eif.failed = FALSE;
5979
5980       /* If we are supposed to export all symbols into the dynamic symbol
5981          table (this is not the normal case), then do so.  */
5982       if (info->export_dynamic
5983           || (bfd_link_executable (info) && info->dynamic))
5984         {
5985           elf_link_hash_traverse (elf_hash_table (info),
5986                                   _bfd_elf_export_symbol,
5987                                   &eif);
5988           if (eif.failed)
5989             return FALSE;
5990         }
5991
5992       /* Make all global versions with definition.  */
5993       for (t = info->version_info; t != NULL; t = t->next)
5994         for (d = t->globals.list; d != NULL; d = d->next)
5995           if (!d->symver && d->literal)
5996             {
5997               const char *verstr, *name;
5998               size_t namelen, verlen, newlen;
5999               char *newname, *p, leading_char;
6000               struct elf_link_hash_entry *newh;
6001
6002               leading_char = bfd_get_symbol_leading_char (output_bfd);
6003               name = d->pattern;
6004               namelen = strlen (name) + (leading_char != '\0');
6005               verstr = t->name;
6006               verlen = strlen (verstr);
6007               newlen = namelen + verlen + 3;
6008
6009               newname = (char *) bfd_malloc (newlen);
6010               if (newname == NULL)
6011                 return FALSE;
6012               newname[0] = leading_char;
6013               memcpy (newname + (leading_char != '\0'), name, namelen);
6014
6015               /* Check the hidden versioned definition.  */
6016               p = newname + namelen;
6017               *p++ = ELF_VER_CHR;
6018               memcpy (p, verstr, verlen + 1);
6019               newh = elf_link_hash_lookup (elf_hash_table (info),
6020                                            newname, FALSE, FALSE,
6021                                            FALSE);
6022               if (newh == NULL
6023                   || (newh->root.type != bfd_link_hash_defined
6024                       && newh->root.type != bfd_link_hash_defweak))
6025                 {
6026                   /* Check the default versioned definition.  */
6027                   *p++ = ELF_VER_CHR;
6028                   memcpy (p, verstr, verlen + 1);
6029                   newh = elf_link_hash_lookup (elf_hash_table (info),
6030                                                newname, FALSE, FALSE,
6031                                                FALSE);
6032                 }
6033               free (newname);
6034
6035               /* Mark this version if there is a definition and it is
6036                  not defined in a shared object.  */
6037               if (newh != NULL
6038                   && !newh->def_dynamic
6039                   && (newh->root.type == bfd_link_hash_defined
6040                       || newh->root.type == bfd_link_hash_defweak))
6041                 d->symver = 1;
6042             }
6043
6044       /* Attach all the symbols to their version information.  */
6045       asvinfo.info = info;
6046       asvinfo.failed = FALSE;
6047
6048       elf_link_hash_traverse (elf_hash_table (info),
6049                               _bfd_elf_link_assign_sym_version,
6050                               &asvinfo);
6051       if (asvinfo.failed)
6052         return FALSE;
6053
6054       if (!info->allow_undefined_version)
6055         {
6056           /* Check if all global versions have a definition.  */
6057           all_defined = TRUE;
6058           for (t = info->version_info; t != NULL; t = t->next)
6059             for (d = t->globals.list; d != NULL; d = d->next)
6060               if (d->literal && !d->symver && !d->script)
6061                 {
6062                   (*_bfd_error_handler)
6063                     (_("%s: undefined version: %s"),
6064                      d->pattern, t->name);
6065                   all_defined = FALSE;
6066                 }
6067
6068           if (!all_defined)
6069             {
6070               bfd_set_error (bfd_error_bad_value);
6071               return FALSE;
6072             }
6073         }
6074
6075       /* Find all symbols which were defined in a dynamic object and make
6076          the backend pick a reasonable value for them.  */
6077       elf_link_hash_traverse (elf_hash_table (info),
6078                               _bfd_elf_adjust_dynamic_symbol,
6079                               &eif);
6080       if (eif.failed)
6081         return FALSE;
6082
6083       /* Add some entries to the .dynamic section.  We fill in some of the
6084          values later, in bfd_elf_final_link, but we must add the entries
6085          now so that we know the final size of the .dynamic section.  */
6086
6087       /* If there are initialization and/or finalization functions to
6088          call then add the corresponding DT_INIT/DT_FINI entries.  */
6089       h = (info->init_function
6090            ? elf_link_hash_lookup (elf_hash_table (info),
6091                                    info->init_function, FALSE,
6092                                    FALSE, FALSE)
6093            : NULL);
6094       if (h != NULL
6095           && (h->ref_regular
6096               || h->def_regular))
6097         {
6098           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6099             return FALSE;
6100         }
6101       h = (info->fini_function
6102            ? elf_link_hash_lookup (elf_hash_table (info),
6103                                    info->fini_function, FALSE,
6104                                    FALSE, FALSE)
6105            : NULL);
6106       if (h != NULL
6107           && (h->ref_regular
6108               || h->def_regular))
6109         {
6110           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6111             return FALSE;
6112         }
6113
6114       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6115       if (s != NULL && s->linker_has_input)
6116         {
6117           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6118           if (! bfd_link_executable (info))
6119             {
6120               bfd *sub;
6121               asection *o;
6122
6123               for (sub = info->input_bfds; sub != NULL;
6124                    sub = sub->link.next)
6125                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6126                   for (o = sub->sections; o != NULL; o = o->next)
6127                     if (elf_section_data (o)->this_hdr.sh_type
6128                         == SHT_PREINIT_ARRAY)
6129                       {
6130                         (*_bfd_error_handler)
6131                           (_("%B: .preinit_array section is not allowed in DSO"),
6132                            sub);
6133                         break;
6134                       }
6135
6136               bfd_set_error (bfd_error_nonrepresentable_section);
6137               return FALSE;
6138             }
6139
6140           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6141               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6142             return FALSE;
6143         }
6144       s = bfd_get_section_by_name (output_bfd, ".init_array");
6145       if (s != NULL && s->linker_has_input)
6146         {
6147           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6148               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6149             return FALSE;
6150         }
6151       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6152       if (s != NULL && s->linker_has_input)
6153         {
6154           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6155               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6156             return FALSE;
6157         }
6158
6159       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6160       /* If .dynstr is excluded from the link, we don't want any of
6161          these tags.  Strictly, we should be checking each section
6162          individually;  This quick check covers for the case where
6163          someone does a /DISCARD/ : { *(*) }.  */
6164       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6165         {
6166           bfd_size_type strsize;
6167
6168           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6169           if ((info->emit_hash
6170                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6171               || (info->emit_gnu_hash
6172                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6173               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6174               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6175               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6176               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6177                                               bed->s->sizeof_sym))
6178             return FALSE;
6179         }
6180     }
6181
6182   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6183     return FALSE;
6184
6185   /* The backend must work out the sizes of all the other dynamic
6186      sections.  */
6187   if (dynobj != NULL
6188       && bed->elf_backend_size_dynamic_sections != NULL
6189       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6190     return FALSE;
6191
6192   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6193     {
6194       unsigned long section_sym_count;
6195       struct bfd_elf_version_tree *verdefs;
6196       asection *s;
6197
6198       /* Set up the version definition section.  */
6199       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6200       BFD_ASSERT (s != NULL);
6201
6202       /* We may have created additional version definitions if we are
6203          just linking a regular application.  */
6204       verdefs = info->version_info;
6205
6206       /* Skip anonymous version tag.  */
6207       if (verdefs != NULL && verdefs->vernum == 0)
6208         verdefs = verdefs->next;
6209
6210       if (verdefs == NULL && !info->create_default_symver)
6211         s->flags |= SEC_EXCLUDE;
6212       else
6213         {
6214           unsigned int cdefs;
6215           bfd_size_type size;
6216           struct bfd_elf_version_tree *t;
6217           bfd_byte *p;
6218           Elf_Internal_Verdef def;
6219           Elf_Internal_Verdaux defaux;
6220           struct bfd_link_hash_entry *bh;
6221           struct elf_link_hash_entry *h;
6222           const char *name;
6223
6224           cdefs = 0;
6225           size = 0;
6226
6227           /* Make space for the base version.  */
6228           size += sizeof (Elf_External_Verdef);
6229           size += sizeof (Elf_External_Verdaux);
6230           ++cdefs;
6231
6232           /* Make space for the default version.  */
6233           if (info->create_default_symver)
6234             {
6235               size += sizeof (Elf_External_Verdef);
6236               ++cdefs;
6237             }
6238
6239           for (t = verdefs; t != NULL; t = t->next)
6240             {
6241               struct bfd_elf_version_deps *n;
6242
6243               /* Don't emit base version twice.  */
6244               if (t->vernum == 0)
6245                 continue;
6246
6247               size += sizeof (Elf_External_Verdef);
6248               size += sizeof (Elf_External_Verdaux);
6249               ++cdefs;
6250
6251               for (n = t->deps; n != NULL; n = n->next)
6252                 size += sizeof (Elf_External_Verdaux);
6253             }
6254
6255           s->size = size;
6256           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6257           if (s->contents == NULL && s->size != 0)
6258             return FALSE;
6259
6260           /* Fill in the version definition section.  */
6261
6262           p = s->contents;
6263
6264           def.vd_version = VER_DEF_CURRENT;
6265           def.vd_flags = VER_FLG_BASE;
6266           def.vd_ndx = 1;
6267           def.vd_cnt = 1;
6268           if (info->create_default_symver)
6269             {
6270               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6271               def.vd_next = sizeof (Elf_External_Verdef);
6272             }
6273           else
6274             {
6275               def.vd_aux = sizeof (Elf_External_Verdef);
6276               def.vd_next = (sizeof (Elf_External_Verdef)
6277                              + sizeof (Elf_External_Verdaux));
6278             }
6279
6280           if (soname_indx != (size_t) -1)
6281             {
6282               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6283                                       soname_indx);
6284               def.vd_hash = bfd_elf_hash (soname);
6285               defaux.vda_name = soname_indx;
6286               name = soname;
6287             }
6288           else
6289             {
6290               size_t indx;
6291
6292               name = lbasename (output_bfd->filename);
6293               def.vd_hash = bfd_elf_hash (name);
6294               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6295                                           name, FALSE);
6296               if (indx == (size_t) -1)
6297                 return FALSE;
6298               defaux.vda_name = indx;
6299             }
6300           defaux.vda_next = 0;
6301
6302           _bfd_elf_swap_verdef_out (output_bfd, &def,
6303                                     (Elf_External_Verdef *) p);
6304           p += sizeof (Elf_External_Verdef);
6305           if (info->create_default_symver)
6306             {
6307               /* Add a symbol representing this version.  */
6308               bh = NULL;
6309               if (! (_bfd_generic_link_add_one_symbol
6310                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6311                       0, NULL, FALSE,
6312                       get_elf_backend_data (dynobj)->collect, &bh)))
6313                 return FALSE;
6314               h = (struct elf_link_hash_entry *) bh;
6315               h->non_elf = 0;
6316               h->def_regular = 1;
6317               h->type = STT_OBJECT;
6318               h->verinfo.vertree = NULL;
6319
6320               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6321                 return FALSE;
6322
6323               /* Create a duplicate of the base version with the same
6324                  aux block, but different flags.  */
6325               def.vd_flags = 0;
6326               def.vd_ndx = 2;
6327               def.vd_aux = sizeof (Elf_External_Verdef);
6328               if (verdefs)
6329                 def.vd_next = (sizeof (Elf_External_Verdef)
6330                                + sizeof (Elf_External_Verdaux));
6331               else
6332                 def.vd_next = 0;
6333               _bfd_elf_swap_verdef_out (output_bfd, &def,
6334                                         (Elf_External_Verdef *) p);
6335               p += sizeof (Elf_External_Verdef);
6336             }
6337           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6338                                      (Elf_External_Verdaux *) p);
6339           p += sizeof (Elf_External_Verdaux);
6340
6341           for (t = verdefs; t != NULL; t = t->next)
6342             {
6343               unsigned int cdeps;
6344               struct bfd_elf_version_deps *n;
6345
6346               /* Don't emit the base version twice.  */
6347               if (t->vernum == 0)
6348                 continue;
6349
6350               cdeps = 0;
6351               for (n = t->deps; n != NULL; n = n->next)
6352                 ++cdeps;
6353
6354               /* Add a symbol representing this version.  */
6355               bh = NULL;
6356               if (! (_bfd_generic_link_add_one_symbol
6357                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6358                       0, NULL, FALSE,
6359                       get_elf_backend_data (dynobj)->collect, &bh)))
6360                 return FALSE;
6361               h = (struct elf_link_hash_entry *) bh;
6362               h->non_elf = 0;
6363               h->def_regular = 1;
6364               h->type = STT_OBJECT;
6365               h->verinfo.vertree = t;
6366
6367               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6368                 return FALSE;
6369
6370               def.vd_version = VER_DEF_CURRENT;
6371               def.vd_flags = 0;
6372               if (t->globals.list == NULL
6373                   && t->locals.list == NULL
6374                   && ! t->used)
6375                 def.vd_flags |= VER_FLG_WEAK;
6376               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6377               def.vd_cnt = cdeps + 1;
6378               def.vd_hash = bfd_elf_hash (t->name);
6379               def.vd_aux = sizeof (Elf_External_Verdef);
6380               def.vd_next = 0;
6381
6382               /* If a basever node is next, it *must* be the last node in
6383                  the chain, otherwise Verdef construction breaks.  */
6384               if (t->next != NULL && t->next->vernum == 0)
6385                 BFD_ASSERT (t->next->next == NULL);
6386
6387               if (t->next != NULL && t->next->vernum != 0)
6388                 def.vd_next = (sizeof (Elf_External_Verdef)
6389                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6390
6391               _bfd_elf_swap_verdef_out (output_bfd, &def,
6392                                         (Elf_External_Verdef *) p);
6393               p += sizeof (Elf_External_Verdef);
6394
6395               defaux.vda_name = h->dynstr_index;
6396               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6397                                       h->dynstr_index);
6398               defaux.vda_next = 0;
6399               if (t->deps != NULL)
6400                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6401               t->name_indx = defaux.vda_name;
6402
6403               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6404                                          (Elf_External_Verdaux *) p);
6405               p += sizeof (Elf_External_Verdaux);
6406
6407               for (n = t->deps; n != NULL; n = n->next)
6408                 {
6409                   if (n->version_needed == NULL)
6410                     {
6411                       /* This can happen if there was an error in the
6412                          version script.  */
6413                       defaux.vda_name = 0;
6414                     }
6415                   else
6416                     {
6417                       defaux.vda_name = n->version_needed->name_indx;
6418                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6419                                               defaux.vda_name);
6420                     }
6421                   if (n->next == NULL)
6422                     defaux.vda_next = 0;
6423                   else
6424                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6425
6426                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6427                                              (Elf_External_Verdaux *) p);
6428                   p += sizeof (Elf_External_Verdaux);
6429                 }
6430             }
6431
6432           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6433               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6434             return FALSE;
6435
6436           elf_tdata (output_bfd)->cverdefs = cdefs;
6437         }
6438
6439       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6440         {
6441           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6442             return FALSE;
6443         }
6444       else if (info->flags & DF_BIND_NOW)
6445         {
6446           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6447             return FALSE;
6448         }
6449
6450       if (info->flags_1)
6451         {
6452           if (bfd_link_executable (info))
6453             info->flags_1 &= ~ (DF_1_INITFIRST
6454                                 | DF_1_NODELETE
6455                                 | DF_1_NOOPEN);
6456           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6457             return FALSE;
6458         }
6459
6460       /* Work out the size of the version reference section.  */
6461
6462       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6463       BFD_ASSERT (s != NULL);
6464       {
6465         struct elf_find_verdep_info sinfo;
6466
6467         sinfo.info = info;
6468         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6469         if (sinfo.vers == 0)
6470           sinfo.vers = 1;
6471         sinfo.failed = FALSE;
6472
6473         elf_link_hash_traverse (elf_hash_table (info),
6474                                 _bfd_elf_link_find_version_dependencies,
6475                                 &sinfo);
6476         if (sinfo.failed)
6477           return FALSE;
6478
6479         if (elf_tdata (output_bfd)->verref == NULL)
6480           s->flags |= SEC_EXCLUDE;
6481         else
6482           {
6483             Elf_Internal_Verneed *t;
6484             unsigned int size;
6485             unsigned int crefs;
6486             bfd_byte *p;
6487
6488             /* Build the version dependency section.  */
6489             size = 0;
6490             crefs = 0;
6491             for (t = elf_tdata (output_bfd)->verref;
6492                  t != NULL;
6493                  t = t->vn_nextref)
6494               {
6495                 Elf_Internal_Vernaux *a;
6496
6497                 size += sizeof (Elf_External_Verneed);
6498                 ++crefs;
6499                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6500                   size += sizeof (Elf_External_Vernaux);
6501               }
6502
6503             s->size = size;
6504             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6505             if (s->contents == NULL)
6506               return FALSE;
6507
6508             p = s->contents;
6509             for (t = elf_tdata (output_bfd)->verref;
6510                  t != NULL;
6511                  t = t->vn_nextref)
6512               {
6513                 unsigned int caux;
6514                 Elf_Internal_Vernaux *a;
6515                 size_t indx;
6516
6517                 caux = 0;
6518                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6519                   ++caux;
6520
6521                 t->vn_version = VER_NEED_CURRENT;
6522                 t->vn_cnt = caux;
6523                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6524                                             elf_dt_name (t->vn_bfd) != NULL
6525                                             ? elf_dt_name (t->vn_bfd)
6526                                             : lbasename (t->vn_bfd->filename),
6527                                             FALSE);
6528                 if (indx == (size_t) -1)
6529                   return FALSE;
6530                 t->vn_file = indx;
6531                 t->vn_aux = sizeof (Elf_External_Verneed);
6532                 if (t->vn_nextref == NULL)
6533                   t->vn_next = 0;
6534                 else
6535                   t->vn_next = (sizeof (Elf_External_Verneed)
6536                                 + caux * sizeof (Elf_External_Vernaux));
6537
6538                 _bfd_elf_swap_verneed_out (output_bfd, t,
6539                                            (Elf_External_Verneed *) p);
6540                 p += sizeof (Elf_External_Verneed);
6541
6542                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6543                   {
6544                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6545                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6546                                                 a->vna_nodename, FALSE);
6547                     if (indx == (size_t) -1)
6548                       return FALSE;
6549                     a->vna_name = indx;
6550                     if (a->vna_nextptr == NULL)
6551                       a->vna_next = 0;
6552                     else
6553                       a->vna_next = sizeof (Elf_External_Vernaux);
6554
6555                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6556                                                (Elf_External_Vernaux *) p);
6557                     p += sizeof (Elf_External_Vernaux);
6558                   }
6559               }
6560
6561             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6562                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6563               return FALSE;
6564
6565             elf_tdata (output_bfd)->cverrefs = crefs;
6566           }
6567       }
6568
6569       if ((elf_tdata (output_bfd)->cverrefs == 0
6570            && elf_tdata (output_bfd)->cverdefs == 0)
6571           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6572                                              &section_sym_count) == 0)
6573         {
6574           s = bfd_get_linker_section (dynobj, ".gnu.version");
6575           s->flags |= SEC_EXCLUDE;
6576         }
6577     }
6578   return TRUE;
6579 }
6580
6581 /* Find the first non-excluded output section.  We'll use its
6582    section symbol for some emitted relocs.  */
6583 void
6584 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6585 {
6586   asection *s;
6587
6588   for (s = output_bfd->sections; s != NULL; s = s->next)
6589     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6590         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6591       {
6592         elf_hash_table (info)->text_index_section = s;
6593         break;
6594       }
6595 }
6596
6597 /* Find two non-excluded output sections, one for code, one for data.
6598    We'll use their section symbols for some emitted relocs.  */
6599 void
6600 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6601 {
6602   asection *s;
6603
6604   /* Data first, since setting text_index_section changes
6605      _bfd_elf_link_omit_section_dynsym.  */
6606   for (s = output_bfd->sections; s != NULL; s = s->next)
6607     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6608         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6609       {
6610         elf_hash_table (info)->data_index_section = s;
6611         break;
6612       }
6613
6614   for (s = output_bfd->sections; s != NULL; s = s->next)
6615     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6616          == (SEC_ALLOC | SEC_READONLY))
6617         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6618       {
6619         elf_hash_table (info)->text_index_section = s;
6620         break;
6621       }
6622
6623   if (elf_hash_table (info)->text_index_section == NULL)
6624     elf_hash_table (info)->text_index_section
6625       = elf_hash_table (info)->data_index_section;
6626 }
6627
6628 bfd_boolean
6629 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6630 {
6631   const struct elf_backend_data *bed;
6632
6633   if (!is_elf_hash_table (info->hash))
6634     return TRUE;
6635
6636   bed = get_elf_backend_data (output_bfd);
6637   (*bed->elf_backend_init_index_section) (output_bfd, info);
6638
6639   if (elf_hash_table (info)->dynamic_sections_created)
6640     {
6641       bfd *dynobj;
6642       asection *s;
6643       bfd_size_type dynsymcount;
6644       unsigned long section_sym_count;
6645       unsigned int dtagcount;
6646
6647       dynobj = elf_hash_table (info)->dynobj;
6648
6649       /* Assign dynsym indicies.  In a shared library we generate a
6650          section symbol for each output section, which come first.
6651          Next come all of the back-end allocated local dynamic syms,
6652          followed by the rest of the global symbols.  */
6653
6654       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6655                                                     &section_sym_count);
6656
6657       /* Work out the size of the symbol version section.  */
6658       s = bfd_get_linker_section (dynobj, ".gnu.version");
6659       BFD_ASSERT (s != NULL);
6660       if ((s->flags & SEC_EXCLUDE) == 0)
6661         {
6662           s->size = dynsymcount * sizeof (Elf_External_Versym);
6663           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6664           if (s->contents == NULL)
6665             return FALSE;
6666
6667           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6668             return FALSE;
6669         }
6670
6671       /* Set the size of the .dynsym and .hash sections.  We counted
6672          the number of dynamic symbols in elf_link_add_object_symbols.
6673          We will build the contents of .dynsym and .hash when we build
6674          the final symbol table, because until then we do not know the
6675          correct value to give the symbols.  We built the .dynstr
6676          section as we went along in elf_link_add_object_symbols.  */
6677       s = elf_hash_table (info)->dynsym;
6678       BFD_ASSERT (s != NULL);
6679       s->size = dynsymcount * bed->s->sizeof_sym;
6680
6681       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6682       if (s->contents == NULL)
6683         return FALSE;
6684
6685       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6686          section syms, in case we don't output them all.  */
6687       ++section_sym_count;
6688       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6689
6690       elf_hash_table (info)->bucketcount = 0;
6691
6692       /* Compute the size of the hashing table.  As a side effect this
6693          computes the hash values for all the names we export.  */
6694       if (info->emit_hash)
6695         {
6696           unsigned long int *hashcodes;
6697           struct hash_codes_info hashinf;
6698           bfd_size_type amt;
6699           unsigned long int nsyms;
6700           size_t bucketcount;
6701           size_t hash_entry_size;
6702
6703           /* Compute the hash values for all exported symbols.  At the same
6704              time store the values in an array so that we could use them for
6705              optimizations.  */
6706           amt = dynsymcount * sizeof (unsigned long int);
6707           hashcodes = (unsigned long int *) bfd_malloc (amt);
6708           if (hashcodes == NULL)
6709             return FALSE;
6710           hashinf.hashcodes = hashcodes;
6711           hashinf.error = FALSE;
6712
6713           /* Put all hash values in HASHCODES.  */
6714           elf_link_hash_traverse (elf_hash_table (info),
6715                                   elf_collect_hash_codes, &hashinf);
6716           if (hashinf.error)
6717             {
6718               free (hashcodes);
6719               return FALSE;
6720             }
6721
6722           nsyms = hashinf.hashcodes - hashcodes;
6723           bucketcount
6724             = compute_bucket_count (info, hashcodes, nsyms, 0);
6725           free (hashcodes);
6726
6727           if (bucketcount == 0)
6728             return FALSE;
6729
6730           elf_hash_table (info)->bucketcount = bucketcount;
6731
6732           s = bfd_get_linker_section (dynobj, ".hash");
6733           BFD_ASSERT (s != NULL);
6734           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6735           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6736           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6737           if (s->contents == NULL)
6738             return FALSE;
6739
6740           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6741           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6742                    s->contents + hash_entry_size);
6743         }
6744
6745       if (info->emit_gnu_hash)
6746         {
6747           size_t i, cnt;
6748           unsigned char *contents;
6749           struct collect_gnu_hash_codes cinfo;
6750           bfd_size_type amt;
6751           size_t bucketcount;
6752
6753           memset (&cinfo, 0, sizeof (cinfo));
6754
6755           /* Compute the hash values for all exported symbols.  At the same
6756              time store the values in an array so that we could use them for
6757              optimizations.  */
6758           amt = dynsymcount * 2 * sizeof (unsigned long int);
6759           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6760           if (cinfo.hashcodes == NULL)
6761             return FALSE;
6762
6763           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6764           cinfo.min_dynindx = -1;
6765           cinfo.output_bfd = output_bfd;
6766           cinfo.bed = bed;
6767
6768           /* Put all hash values in HASHCODES.  */
6769           elf_link_hash_traverse (elf_hash_table (info),
6770                                   elf_collect_gnu_hash_codes, &cinfo);
6771           if (cinfo.error)
6772             {
6773               free (cinfo.hashcodes);
6774               return FALSE;
6775             }
6776
6777           bucketcount
6778             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6779
6780           if (bucketcount == 0)
6781             {
6782               free (cinfo.hashcodes);
6783               return FALSE;
6784             }
6785
6786           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6787           BFD_ASSERT (s != NULL);
6788
6789           if (cinfo.nsyms == 0)
6790             {
6791               /* Empty .gnu.hash section is special.  */
6792               BFD_ASSERT (cinfo.min_dynindx == -1);
6793               free (cinfo.hashcodes);
6794               s->size = 5 * 4 + bed->s->arch_size / 8;
6795               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6796               if (contents == NULL)
6797                 return FALSE;
6798               s->contents = contents;
6799               /* 1 empty bucket.  */
6800               bfd_put_32 (output_bfd, 1, contents);
6801               /* SYMIDX above the special symbol 0.  */
6802               bfd_put_32 (output_bfd, 1, contents + 4);
6803               /* Just one word for bitmask.  */
6804               bfd_put_32 (output_bfd, 1, contents + 8);
6805               /* Only hash fn bloom filter.  */
6806               bfd_put_32 (output_bfd, 0, contents + 12);
6807               /* No hashes are valid - empty bitmask.  */
6808               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6809               /* No hashes in the only bucket.  */
6810               bfd_put_32 (output_bfd, 0,
6811                           contents + 16 + bed->s->arch_size / 8);
6812             }
6813           else
6814             {
6815               unsigned long int maskwords, maskbitslog2, x;
6816               BFD_ASSERT (cinfo.min_dynindx != -1);
6817
6818               x = cinfo.nsyms;
6819               maskbitslog2 = 1;
6820               while ((x >>= 1) != 0)
6821                 ++maskbitslog2;
6822               if (maskbitslog2 < 3)
6823                 maskbitslog2 = 5;
6824               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6825                 maskbitslog2 = maskbitslog2 + 3;
6826               else
6827                 maskbitslog2 = maskbitslog2 + 2;
6828               if (bed->s->arch_size == 64)
6829                 {
6830                   if (maskbitslog2 == 5)
6831                     maskbitslog2 = 6;
6832                   cinfo.shift1 = 6;
6833                 }
6834               else
6835                 cinfo.shift1 = 5;
6836               cinfo.mask = (1 << cinfo.shift1) - 1;
6837               cinfo.shift2 = maskbitslog2;
6838               cinfo.maskbits = 1 << maskbitslog2;
6839               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6840               amt = bucketcount * sizeof (unsigned long int) * 2;
6841               amt += maskwords * sizeof (bfd_vma);
6842               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6843               if (cinfo.bitmask == NULL)
6844                 {
6845                   free (cinfo.hashcodes);
6846                   return FALSE;
6847                 }
6848
6849               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6850               cinfo.indx = cinfo.counts + bucketcount;
6851               cinfo.symindx = dynsymcount - cinfo.nsyms;
6852               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6853
6854               /* Determine how often each hash bucket is used.  */
6855               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6856               for (i = 0; i < cinfo.nsyms; ++i)
6857                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6858
6859               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6860                 if (cinfo.counts[i] != 0)
6861                   {
6862                     cinfo.indx[i] = cnt;
6863                     cnt += cinfo.counts[i];
6864                   }
6865               BFD_ASSERT (cnt == dynsymcount);
6866               cinfo.bucketcount = bucketcount;
6867               cinfo.local_indx = cinfo.min_dynindx;
6868
6869               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6870               s->size += cinfo.maskbits / 8;
6871               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6872               if (contents == NULL)
6873                 {
6874                   free (cinfo.bitmask);
6875                   free (cinfo.hashcodes);
6876                   return FALSE;
6877                 }
6878
6879               s->contents = contents;
6880               bfd_put_32 (output_bfd, bucketcount, contents);
6881               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6882               bfd_put_32 (output_bfd, maskwords, contents + 8);
6883               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6884               contents += 16 + cinfo.maskbits / 8;
6885
6886               for (i = 0; i < bucketcount; ++i)
6887                 {
6888                   if (cinfo.counts[i] == 0)
6889                     bfd_put_32 (output_bfd, 0, contents);
6890                   else
6891                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6892                   contents += 4;
6893                 }
6894
6895               cinfo.contents = contents;
6896
6897               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6898               elf_link_hash_traverse (elf_hash_table (info),
6899                                       elf_renumber_gnu_hash_syms, &cinfo);
6900
6901               contents = s->contents + 16;
6902               for (i = 0; i < maskwords; ++i)
6903                 {
6904                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6905                            contents);
6906                   contents += bed->s->arch_size / 8;
6907                 }
6908
6909               free (cinfo.bitmask);
6910               free (cinfo.hashcodes);
6911             }
6912         }
6913
6914       s = bfd_get_linker_section (dynobj, ".dynstr");
6915       BFD_ASSERT (s != NULL);
6916
6917       elf_finalize_dynstr (output_bfd, info);
6918
6919       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6920
6921       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6922         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6923           return FALSE;
6924     }
6925
6926   return TRUE;
6927 }
6928 \f
6929 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6930
6931 static void
6932 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6933                             asection *sec)
6934 {
6935   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6936   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6937 }
6938
6939 /* Finish SHF_MERGE section merging.  */
6940
6941 bfd_boolean
6942 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
6943 {
6944   bfd *ibfd;
6945   asection *sec;
6946
6947   if (!is_elf_hash_table (info->hash))
6948     return FALSE;
6949
6950   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6951     if ((ibfd->flags & DYNAMIC) == 0
6952         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6953         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
6954             == get_elf_backend_data (obfd)->s->elfclass))
6955       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6956         if ((sec->flags & SEC_MERGE) != 0
6957             && !bfd_is_abs_section (sec->output_section))
6958           {
6959             struct bfd_elf_section_data *secdata;
6960
6961             secdata = elf_section_data (sec);
6962             if (! _bfd_add_merge_section (obfd,
6963                                           &elf_hash_table (info)->merge_info,
6964                                           sec, &secdata->sec_info))
6965               return FALSE;
6966             else if (secdata->sec_info)
6967               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6968           }
6969
6970   if (elf_hash_table (info)->merge_info != NULL)
6971     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
6972                          merge_sections_remove_hook);
6973   return TRUE;
6974 }
6975
6976 /* Create an entry in an ELF linker hash table.  */
6977
6978 struct bfd_hash_entry *
6979 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6980                             struct bfd_hash_table *table,
6981                             const char *string)
6982 {
6983   /* Allocate the structure if it has not already been allocated by a
6984      subclass.  */
6985   if (entry == NULL)
6986     {
6987       entry = (struct bfd_hash_entry *)
6988         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6989       if (entry == NULL)
6990         return entry;
6991     }
6992
6993   /* Call the allocation method of the superclass.  */
6994   entry = _bfd_link_hash_newfunc (entry, table, string);
6995   if (entry != NULL)
6996     {
6997       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6998       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6999
7000       /* Set local fields.  */
7001       ret->indx = -1;
7002       ret->dynindx = -1;
7003       ret->got = htab->init_got_refcount;
7004       ret->plt = htab->init_plt_refcount;
7005       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7006                               - offsetof (struct elf_link_hash_entry, size)));
7007       /* Assume that we have been called by a non-ELF symbol reader.
7008          This flag is then reset by the code which reads an ELF input
7009          file.  This ensures that a symbol created by a non-ELF symbol
7010          reader will have the flag set correctly.  */
7011       ret->non_elf = 1;
7012     }
7013
7014   return entry;
7015 }
7016
7017 /* Copy data from an indirect symbol to its direct symbol, hiding the
7018    old indirect symbol.  Also used for copying flags to a weakdef.  */
7019
7020 void
7021 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7022                                   struct elf_link_hash_entry *dir,
7023                                   struct elf_link_hash_entry *ind)
7024 {
7025   struct elf_link_hash_table *htab;
7026
7027   /* Copy down any references that we may have already seen to the
7028      symbol which just became indirect if DIR isn't a hidden versioned
7029      symbol.  */
7030
7031   if (dir->versioned != versioned_hidden)
7032     {
7033       dir->ref_dynamic |= ind->ref_dynamic;
7034       dir->ref_regular |= ind->ref_regular;
7035       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7036       dir->non_got_ref |= ind->non_got_ref;
7037       dir->needs_plt |= ind->needs_plt;
7038       dir->pointer_equality_needed |= ind->pointer_equality_needed;
7039     }
7040
7041   if (ind->root.type != bfd_link_hash_indirect)
7042     return;
7043
7044   /* Copy over the global and procedure linkage table refcount entries.
7045      These may have been already set up by a check_relocs routine.  */
7046   htab = elf_hash_table (info);
7047   if (ind->got.refcount > htab->init_got_refcount.refcount)
7048     {
7049       if (dir->got.refcount < 0)
7050         dir->got.refcount = 0;
7051       dir->got.refcount += ind->got.refcount;
7052       ind->got.refcount = htab->init_got_refcount.refcount;
7053     }
7054
7055   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7056     {
7057       if (dir->plt.refcount < 0)
7058         dir->plt.refcount = 0;
7059       dir->plt.refcount += ind->plt.refcount;
7060       ind->plt.refcount = htab->init_plt_refcount.refcount;
7061     }
7062
7063   if (ind->dynindx != -1)
7064     {
7065       if (dir->dynindx != -1)
7066         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7067       dir->dynindx = ind->dynindx;
7068       dir->dynstr_index = ind->dynstr_index;
7069       ind->dynindx = -1;
7070       ind->dynstr_index = 0;
7071     }
7072 }
7073
7074 void
7075 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7076                                 struct elf_link_hash_entry *h,
7077                                 bfd_boolean force_local)
7078 {
7079   /* STT_GNU_IFUNC symbol must go through PLT.  */
7080   if (h->type != STT_GNU_IFUNC)
7081     {
7082       h->plt = elf_hash_table (info)->init_plt_offset;
7083       h->needs_plt = 0;
7084     }
7085   if (force_local)
7086     {
7087       h->forced_local = 1;
7088       if (h->dynindx != -1)
7089         {
7090           h->dynindx = -1;
7091           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7092                                   h->dynstr_index);
7093         }
7094     }
7095 }
7096
7097 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7098    caller.  */
7099
7100 bfd_boolean
7101 _bfd_elf_link_hash_table_init
7102   (struct elf_link_hash_table *table,
7103    bfd *abfd,
7104    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7105                                       struct bfd_hash_table *,
7106                                       const char *),
7107    unsigned int entsize,
7108    enum elf_target_id target_id)
7109 {
7110   bfd_boolean ret;
7111   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7112
7113   table->init_got_refcount.refcount = can_refcount - 1;
7114   table->init_plt_refcount.refcount = can_refcount - 1;
7115   table->init_got_offset.offset = -(bfd_vma) 1;
7116   table->init_plt_offset.offset = -(bfd_vma) 1;
7117   /* The first dynamic symbol is a dummy.  */
7118   table->dynsymcount = 1;
7119
7120   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7121
7122   table->root.type = bfd_link_elf_hash_table;
7123   table->hash_table_id = target_id;
7124
7125   return ret;
7126 }
7127
7128 /* Create an ELF linker hash table.  */
7129
7130 struct bfd_link_hash_table *
7131 _bfd_elf_link_hash_table_create (bfd *abfd)
7132 {
7133   struct elf_link_hash_table *ret;
7134   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7135
7136   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7137   if (ret == NULL)
7138     return NULL;
7139
7140   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7141                                        sizeof (struct elf_link_hash_entry),
7142                                        GENERIC_ELF_DATA))
7143     {
7144       free (ret);
7145       return NULL;
7146     }
7147   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7148
7149   return &ret->root;
7150 }
7151
7152 /* Destroy an ELF linker hash table.  */
7153
7154 void
7155 _bfd_elf_link_hash_table_free (bfd *obfd)
7156 {
7157   struct elf_link_hash_table *htab;
7158
7159   htab = (struct elf_link_hash_table *) obfd->link.hash;
7160   if (htab->dynstr != NULL)
7161     _bfd_elf_strtab_free (htab->dynstr);
7162   _bfd_merge_sections_free (htab->merge_info);
7163   _bfd_generic_link_hash_table_free (obfd);
7164 }
7165
7166 /* This is a hook for the ELF emulation code in the generic linker to
7167    tell the backend linker what file name to use for the DT_NEEDED
7168    entry for a dynamic object.  */
7169
7170 void
7171 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7172 {
7173   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7174       && bfd_get_format (abfd) == bfd_object)
7175     elf_dt_name (abfd) = name;
7176 }
7177
7178 int
7179 bfd_elf_get_dyn_lib_class (bfd *abfd)
7180 {
7181   int lib_class;
7182   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7183       && bfd_get_format (abfd) == bfd_object)
7184     lib_class = elf_dyn_lib_class (abfd);
7185   else
7186     lib_class = 0;
7187   return lib_class;
7188 }
7189
7190 void
7191 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7192 {
7193   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7194       && bfd_get_format (abfd) == bfd_object)
7195     elf_dyn_lib_class (abfd) = lib_class;
7196 }
7197
7198 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7199    the linker ELF emulation code.  */
7200
7201 struct bfd_link_needed_list *
7202 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7203                          struct bfd_link_info *info)
7204 {
7205   if (! is_elf_hash_table (info->hash))
7206     return NULL;
7207   return elf_hash_table (info)->needed;
7208 }
7209
7210 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7211    hook for the linker ELF emulation code.  */
7212
7213 struct bfd_link_needed_list *
7214 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7215                           struct bfd_link_info *info)
7216 {
7217   if (! is_elf_hash_table (info->hash))
7218     return NULL;
7219   return elf_hash_table (info)->runpath;
7220 }
7221
7222 /* Get the name actually used for a dynamic object for a link.  This
7223    is the SONAME entry if there is one.  Otherwise, it is the string
7224    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7225
7226 const char *
7227 bfd_elf_get_dt_soname (bfd *abfd)
7228 {
7229   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7230       && bfd_get_format (abfd) == bfd_object)
7231     return elf_dt_name (abfd);
7232   return NULL;
7233 }
7234
7235 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7236    the ELF linker emulation code.  */
7237
7238 bfd_boolean
7239 bfd_elf_get_bfd_needed_list (bfd *abfd,
7240                              struct bfd_link_needed_list **pneeded)
7241 {
7242   asection *s;
7243   bfd_byte *dynbuf = NULL;
7244   unsigned int elfsec;
7245   unsigned long shlink;
7246   bfd_byte *extdyn, *extdynend;
7247   size_t extdynsize;
7248   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7249
7250   *pneeded = NULL;
7251
7252   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7253       || bfd_get_format (abfd) != bfd_object)
7254     return TRUE;
7255
7256   s = bfd_get_section_by_name (abfd, ".dynamic");
7257   if (s == NULL || s->size == 0)
7258     return TRUE;
7259
7260   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7261     goto error_return;
7262
7263   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7264   if (elfsec == SHN_BAD)
7265     goto error_return;
7266
7267   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7268
7269   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7270   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7271
7272   extdyn = dynbuf;
7273   extdynend = extdyn + s->size;
7274   for (; extdyn < extdynend; extdyn += extdynsize)
7275     {
7276       Elf_Internal_Dyn dyn;
7277
7278       (*swap_dyn_in) (abfd, extdyn, &dyn);
7279
7280       if (dyn.d_tag == DT_NULL)
7281         break;
7282
7283       if (dyn.d_tag == DT_NEEDED)
7284         {
7285           const char *string;
7286           struct bfd_link_needed_list *l;
7287           unsigned int tagv = dyn.d_un.d_val;
7288           bfd_size_type amt;
7289
7290           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7291           if (string == NULL)
7292             goto error_return;
7293
7294           amt = sizeof *l;
7295           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7296           if (l == NULL)
7297             goto error_return;
7298
7299           l->by = abfd;
7300           l->name = string;
7301           l->next = *pneeded;
7302           *pneeded = l;
7303         }
7304     }
7305
7306   free (dynbuf);
7307
7308   return TRUE;
7309
7310  error_return:
7311   if (dynbuf != NULL)
7312     free (dynbuf);
7313   return FALSE;
7314 }
7315
7316 struct elf_symbuf_symbol
7317 {
7318   unsigned long st_name;        /* Symbol name, index in string tbl */
7319   unsigned char st_info;        /* Type and binding attributes */
7320   unsigned char st_other;       /* Visibilty, and target specific */
7321 };
7322
7323 struct elf_symbuf_head
7324 {
7325   struct elf_symbuf_symbol *ssym;
7326   size_t count;
7327   unsigned int st_shndx;
7328 };
7329
7330 struct elf_symbol
7331 {
7332   union
7333     {
7334       Elf_Internal_Sym *isym;
7335       struct elf_symbuf_symbol *ssym;
7336     } u;
7337   const char *name;
7338 };
7339
7340 /* Sort references to symbols by ascending section number.  */
7341
7342 static int
7343 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7344 {
7345   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7346   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7347
7348   return s1->st_shndx - s2->st_shndx;
7349 }
7350
7351 static int
7352 elf_sym_name_compare (const void *arg1, const void *arg2)
7353 {
7354   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7355   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7356   return strcmp (s1->name, s2->name);
7357 }
7358
7359 static struct elf_symbuf_head *
7360 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7361 {
7362   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7363   struct elf_symbuf_symbol *ssym;
7364   struct elf_symbuf_head *ssymbuf, *ssymhead;
7365   size_t i, shndx_count, total_size;
7366
7367   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7368   if (indbuf == NULL)
7369     return NULL;
7370
7371   for (ind = indbuf, i = 0; i < symcount; i++)
7372     if (isymbuf[i].st_shndx != SHN_UNDEF)
7373       *ind++ = &isymbuf[i];
7374   indbufend = ind;
7375
7376   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7377          elf_sort_elf_symbol);
7378
7379   shndx_count = 0;
7380   if (indbufend > indbuf)
7381     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7382       if (ind[0]->st_shndx != ind[1]->st_shndx)
7383         shndx_count++;
7384
7385   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7386                 + (indbufend - indbuf) * sizeof (*ssym));
7387   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7388   if (ssymbuf == NULL)
7389     {
7390       free (indbuf);
7391       return NULL;
7392     }
7393
7394   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7395   ssymbuf->ssym = NULL;
7396   ssymbuf->count = shndx_count;
7397   ssymbuf->st_shndx = 0;
7398   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7399     {
7400       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7401         {
7402           ssymhead++;
7403           ssymhead->ssym = ssym;
7404           ssymhead->count = 0;
7405           ssymhead->st_shndx = (*ind)->st_shndx;
7406         }
7407       ssym->st_name = (*ind)->st_name;
7408       ssym->st_info = (*ind)->st_info;
7409       ssym->st_other = (*ind)->st_other;
7410       ssymhead->count++;
7411     }
7412   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7413               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7414                   == total_size));
7415
7416   free (indbuf);
7417   return ssymbuf;
7418 }
7419
7420 /* Check if 2 sections define the same set of local and global
7421    symbols.  */
7422
7423 static bfd_boolean
7424 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7425                                    struct bfd_link_info *info)
7426 {
7427   bfd *bfd1, *bfd2;
7428   const struct elf_backend_data *bed1, *bed2;
7429   Elf_Internal_Shdr *hdr1, *hdr2;
7430   size_t symcount1, symcount2;
7431   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7432   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7433   Elf_Internal_Sym *isym, *isymend;
7434   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7435   size_t count1, count2, i;
7436   unsigned int shndx1, shndx2;
7437   bfd_boolean result;
7438
7439   bfd1 = sec1->owner;
7440   bfd2 = sec2->owner;
7441
7442   /* Both sections have to be in ELF.  */
7443   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7444       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7445     return FALSE;
7446
7447   if (elf_section_type (sec1) != elf_section_type (sec2))
7448     return FALSE;
7449
7450   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7451   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7452   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7453     return FALSE;
7454
7455   bed1 = get_elf_backend_data (bfd1);
7456   bed2 = get_elf_backend_data (bfd2);
7457   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7458   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7459   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7460   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7461
7462   if (symcount1 == 0 || symcount2 == 0)
7463     return FALSE;
7464
7465   result = FALSE;
7466   isymbuf1 = NULL;
7467   isymbuf2 = NULL;
7468   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7469   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7470
7471   if (ssymbuf1 == NULL)
7472     {
7473       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7474                                        NULL, NULL, NULL);
7475       if (isymbuf1 == NULL)
7476         goto done;
7477
7478       if (!info->reduce_memory_overheads)
7479         elf_tdata (bfd1)->symbuf = ssymbuf1
7480           = elf_create_symbuf (symcount1, isymbuf1);
7481     }
7482
7483   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7484     {
7485       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7486                                        NULL, NULL, NULL);
7487       if (isymbuf2 == NULL)
7488         goto done;
7489
7490       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7491         elf_tdata (bfd2)->symbuf = ssymbuf2
7492           = elf_create_symbuf (symcount2, isymbuf2);
7493     }
7494
7495   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7496     {
7497       /* Optimized faster version.  */
7498       size_t lo, hi, mid;
7499       struct elf_symbol *symp;
7500       struct elf_symbuf_symbol *ssym, *ssymend;
7501
7502       lo = 0;
7503       hi = ssymbuf1->count;
7504       ssymbuf1++;
7505       count1 = 0;
7506       while (lo < hi)
7507         {
7508           mid = (lo + hi) / 2;
7509           if (shndx1 < ssymbuf1[mid].st_shndx)
7510             hi = mid;
7511           else if (shndx1 > ssymbuf1[mid].st_shndx)
7512             lo = mid + 1;
7513           else
7514             {
7515               count1 = ssymbuf1[mid].count;
7516               ssymbuf1 += mid;
7517               break;
7518             }
7519         }
7520
7521       lo = 0;
7522       hi = ssymbuf2->count;
7523       ssymbuf2++;
7524       count2 = 0;
7525       while (lo < hi)
7526         {
7527           mid = (lo + hi) / 2;
7528           if (shndx2 < ssymbuf2[mid].st_shndx)
7529             hi = mid;
7530           else if (shndx2 > ssymbuf2[mid].st_shndx)
7531             lo = mid + 1;
7532           else
7533             {
7534               count2 = ssymbuf2[mid].count;
7535               ssymbuf2 += mid;
7536               break;
7537             }
7538         }
7539
7540       if (count1 == 0 || count2 == 0 || count1 != count2)
7541         goto done;
7542
7543       symtable1
7544         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7545       symtable2
7546         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7547       if (symtable1 == NULL || symtable2 == NULL)
7548         goto done;
7549
7550       symp = symtable1;
7551       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7552            ssym < ssymend; ssym++, symp++)
7553         {
7554           symp->u.ssym = ssym;
7555           symp->name = bfd_elf_string_from_elf_section (bfd1,
7556                                                         hdr1->sh_link,
7557                                                         ssym->st_name);
7558         }
7559
7560       symp = symtable2;
7561       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7562            ssym < ssymend; ssym++, symp++)
7563         {
7564           symp->u.ssym = ssym;
7565           symp->name = bfd_elf_string_from_elf_section (bfd2,
7566                                                         hdr2->sh_link,
7567                                                         ssym->st_name);
7568         }
7569
7570       /* Sort symbol by name.  */
7571       qsort (symtable1, count1, sizeof (struct elf_symbol),
7572              elf_sym_name_compare);
7573       qsort (symtable2, count1, sizeof (struct elf_symbol),
7574              elf_sym_name_compare);
7575
7576       for (i = 0; i < count1; i++)
7577         /* Two symbols must have the same binding, type and name.  */
7578         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7579             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7580             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7581           goto done;
7582
7583       result = TRUE;
7584       goto done;
7585     }
7586
7587   symtable1 = (struct elf_symbol *)
7588       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7589   symtable2 = (struct elf_symbol *)
7590       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7591   if (symtable1 == NULL || symtable2 == NULL)
7592     goto done;
7593
7594   /* Count definitions in the section.  */
7595   count1 = 0;
7596   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7597     if (isym->st_shndx == shndx1)
7598       symtable1[count1++].u.isym = isym;
7599
7600   count2 = 0;
7601   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7602     if (isym->st_shndx == shndx2)
7603       symtable2[count2++].u.isym = isym;
7604
7605   if (count1 == 0 || count2 == 0 || count1 != count2)
7606     goto done;
7607
7608   for (i = 0; i < count1; i++)
7609     symtable1[i].name
7610       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7611                                          symtable1[i].u.isym->st_name);
7612
7613   for (i = 0; i < count2; i++)
7614     symtable2[i].name
7615       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7616                                          symtable2[i].u.isym->st_name);
7617
7618   /* Sort symbol by name.  */
7619   qsort (symtable1, count1, sizeof (struct elf_symbol),
7620          elf_sym_name_compare);
7621   qsort (symtable2, count1, sizeof (struct elf_symbol),
7622          elf_sym_name_compare);
7623
7624   for (i = 0; i < count1; i++)
7625     /* Two symbols must have the same binding, type and name.  */
7626     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7627         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7628         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7629       goto done;
7630
7631   result = TRUE;
7632
7633 done:
7634   if (symtable1)
7635     free (symtable1);
7636   if (symtable2)
7637     free (symtable2);
7638   if (isymbuf1)
7639     free (isymbuf1);
7640   if (isymbuf2)
7641     free (isymbuf2);
7642
7643   return result;
7644 }
7645
7646 /* Return TRUE if 2 section types are compatible.  */
7647
7648 bfd_boolean
7649 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7650                                  bfd *bbfd, const asection *bsec)
7651 {
7652   if (asec == NULL
7653       || bsec == NULL
7654       || abfd->xvec->flavour != bfd_target_elf_flavour
7655       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7656     return TRUE;
7657
7658   return elf_section_type (asec) == elf_section_type (bsec);
7659 }
7660 \f
7661 /* Final phase of ELF linker.  */
7662
7663 /* A structure we use to avoid passing large numbers of arguments.  */
7664
7665 struct elf_final_link_info
7666 {
7667   /* General link information.  */
7668   struct bfd_link_info *info;
7669   /* Output BFD.  */
7670   bfd *output_bfd;
7671   /* Symbol string table.  */
7672   struct elf_strtab_hash *symstrtab;
7673   /* .hash section.  */
7674   asection *hash_sec;
7675   /* symbol version section (.gnu.version).  */
7676   asection *symver_sec;
7677   /* Buffer large enough to hold contents of any section.  */
7678   bfd_byte *contents;
7679   /* Buffer large enough to hold external relocs of any section.  */
7680   void *external_relocs;
7681   /* Buffer large enough to hold internal relocs of any section.  */
7682   Elf_Internal_Rela *internal_relocs;
7683   /* Buffer large enough to hold external local symbols of any input
7684      BFD.  */
7685   bfd_byte *external_syms;
7686   /* And a buffer for symbol section indices.  */
7687   Elf_External_Sym_Shndx *locsym_shndx;
7688   /* Buffer large enough to hold internal local symbols of any input
7689      BFD.  */
7690   Elf_Internal_Sym *internal_syms;
7691   /* Array large enough to hold a symbol index for each local symbol
7692      of any input BFD.  */
7693   long *indices;
7694   /* Array large enough to hold a section pointer for each local
7695      symbol of any input BFD.  */
7696   asection **sections;
7697   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7698   Elf_External_Sym_Shndx *symshndxbuf;
7699   /* Number of STT_FILE syms seen.  */
7700   size_t filesym_count;
7701 };
7702
7703 /* This struct is used to pass information to elf_link_output_extsym.  */
7704
7705 struct elf_outext_info
7706 {
7707   bfd_boolean failed;
7708   bfd_boolean localsyms;
7709   bfd_boolean file_sym_done;
7710   struct elf_final_link_info *flinfo;
7711 };
7712
7713
7714 /* Support for evaluating a complex relocation.
7715
7716    Complex relocations are generalized, self-describing relocations.  The
7717    implementation of them consists of two parts: complex symbols, and the
7718    relocations themselves.
7719
7720    The relocations are use a reserved elf-wide relocation type code (R_RELC
7721    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7722    information (start bit, end bit, word width, etc) into the addend.  This
7723    information is extracted from CGEN-generated operand tables within gas.
7724
7725    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7726    internal) representing prefix-notation expressions, including but not
7727    limited to those sorts of expressions normally encoded as addends in the
7728    addend field.  The symbol mangling format is:
7729
7730    <node> := <literal>
7731           |  <unary-operator> ':' <node>
7732           |  <binary-operator> ':' <node> ':' <node>
7733           ;
7734
7735    <literal> := 's' <digits=N> ':' <N character symbol name>
7736              |  'S' <digits=N> ':' <N character section name>
7737              |  '#' <hexdigits>
7738              ;
7739
7740    <binary-operator> := as in C
7741    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7742
7743 static void
7744 set_symbol_value (bfd *bfd_with_globals,
7745                   Elf_Internal_Sym *isymbuf,
7746                   size_t locsymcount,
7747                   size_t symidx,
7748                   bfd_vma val)
7749 {
7750   struct elf_link_hash_entry **sym_hashes;
7751   struct elf_link_hash_entry *h;
7752   size_t extsymoff = locsymcount;
7753
7754   if (symidx < locsymcount)
7755     {
7756       Elf_Internal_Sym *sym;
7757
7758       sym = isymbuf + symidx;
7759       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7760         {
7761           /* It is a local symbol: move it to the
7762              "absolute" section and give it a value.  */
7763           sym->st_shndx = SHN_ABS;
7764           sym->st_value = val;
7765           return;
7766         }
7767       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7768       extsymoff = 0;
7769     }
7770
7771   /* It is a global symbol: set its link type
7772      to "defined" and give it a value.  */
7773
7774   sym_hashes = elf_sym_hashes (bfd_with_globals);
7775   h = sym_hashes [symidx - extsymoff];
7776   while (h->root.type == bfd_link_hash_indirect
7777          || h->root.type == bfd_link_hash_warning)
7778     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7779   h->root.type = bfd_link_hash_defined;
7780   h->root.u.def.value = val;
7781   h->root.u.def.section = bfd_abs_section_ptr;
7782 }
7783
7784 static bfd_boolean
7785 resolve_symbol (const char *name,
7786                 bfd *input_bfd,
7787                 struct elf_final_link_info *flinfo,
7788                 bfd_vma *result,
7789                 Elf_Internal_Sym *isymbuf,
7790                 size_t locsymcount)
7791 {
7792   Elf_Internal_Sym *sym;
7793   struct bfd_link_hash_entry *global_entry;
7794   const char *candidate = NULL;
7795   Elf_Internal_Shdr *symtab_hdr;
7796   size_t i;
7797
7798   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7799
7800   for (i = 0; i < locsymcount; ++ i)
7801     {
7802       sym = isymbuf + i;
7803
7804       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7805         continue;
7806
7807       candidate = bfd_elf_string_from_elf_section (input_bfd,
7808                                                    symtab_hdr->sh_link,
7809                                                    sym->st_name);
7810 #ifdef DEBUG
7811       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7812               name, candidate, (unsigned long) sym->st_value);
7813 #endif
7814       if (candidate && strcmp (candidate, name) == 0)
7815         {
7816           asection *sec = flinfo->sections [i];
7817
7818           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7819           *result += sec->output_offset + sec->output_section->vma;
7820 #ifdef DEBUG
7821           printf ("Found symbol with value %8.8lx\n",
7822                   (unsigned long) *result);
7823 #endif
7824           return TRUE;
7825         }
7826     }
7827
7828   /* Hmm, haven't found it yet. perhaps it is a global.  */
7829   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7830                                        FALSE, FALSE, TRUE);
7831   if (!global_entry)
7832     return FALSE;
7833
7834   if (global_entry->type == bfd_link_hash_defined
7835       || global_entry->type == bfd_link_hash_defweak)
7836     {
7837       *result = (global_entry->u.def.value
7838                  + global_entry->u.def.section->output_section->vma
7839                  + global_entry->u.def.section->output_offset);
7840 #ifdef DEBUG
7841       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7842               global_entry->root.string, (unsigned long) *result);
7843 #endif
7844       return TRUE;
7845     }
7846
7847   return FALSE;
7848 }
7849
7850 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
7851    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
7852    names like "foo.end" which is the end address of section "foo".  */
7853    
7854 static bfd_boolean
7855 resolve_section (const char *name,
7856                  asection *sections,
7857                  bfd_vma *result,
7858                  bfd * abfd)
7859 {
7860   asection *curr;
7861   unsigned int len;
7862
7863   for (curr = sections; curr; curr = curr->next)
7864     if (strcmp (curr->name, name) == 0)
7865       {
7866         *result = curr->vma;
7867         return TRUE;
7868       }
7869
7870   /* Hmm. still haven't found it. try pseudo-section names.  */
7871   /* FIXME: This could be coded more efficiently...  */
7872   for (curr = sections; curr; curr = curr->next)
7873     {
7874       len = strlen (curr->name);
7875       if (len > strlen (name))
7876         continue;
7877
7878       if (strncmp (curr->name, name, len) == 0)
7879         {
7880           if (strncmp (".end", name + len, 4) == 0)
7881             {
7882               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
7883               return TRUE;
7884             }
7885
7886           /* Insert more pseudo-section names here, if you like.  */
7887         }
7888     }
7889
7890   return FALSE;
7891 }
7892
7893 static void
7894 undefined_reference (const char *reftype, const char *name)
7895 {
7896   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7897                       reftype, name);
7898 }
7899
7900 static bfd_boolean
7901 eval_symbol (bfd_vma *result,
7902              const char **symp,
7903              bfd *input_bfd,
7904              struct elf_final_link_info *flinfo,
7905              bfd_vma dot,
7906              Elf_Internal_Sym *isymbuf,
7907              size_t locsymcount,
7908              int signed_p)
7909 {
7910   size_t len;
7911   size_t symlen;
7912   bfd_vma a;
7913   bfd_vma b;
7914   char symbuf[4096];
7915   const char *sym = *symp;
7916   const char *symend;
7917   bfd_boolean symbol_is_section = FALSE;
7918
7919   len = strlen (sym);
7920   symend = sym + len;
7921
7922   if (len < 1 || len > sizeof (symbuf))
7923     {
7924       bfd_set_error (bfd_error_invalid_operation);
7925       return FALSE;
7926     }
7927
7928   switch (* sym)
7929     {
7930     case '.':
7931       *result = dot;
7932       *symp = sym + 1;
7933       return TRUE;
7934
7935     case '#':
7936       ++sym;
7937       *result = strtoul (sym, (char **) symp, 16);
7938       return TRUE;
7939
7940     case 'S':
7941       symbol_is_section = TRUE;
7942     case 's':
7943       ++sym;
7944       symlen = strtol (sym, (char **) symp, 10);
7945       sym = *symp + 1; /* Skip the trailing ':'.  */
7946
7947       if (symend < sym || symlen + 1 > sizeof (symbuf))
7948         {
7949           bfd_set_error (bfd_error_invalid_operation);
7950           return FALSE;
7951         }
7952
7953       memcpy (symbuf, sym, symlen);
7954       symbuf[symlen] = '\0';
7955       *symp = sym + symlen;
7956
7957       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7958          the symbol as a section, or vice-versa. so we're pretty liberal in our
7959          interpretation here; section means "try section first", not "must be a
7960          section", and likewise with symbol.  */
7961
7962       if (symbol_is_section)
7963         {
7964           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
7965               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7966                                   isymbuf, locsymcount))
7967             {
7968               undefined_reference ("section", symbuf);
7969               return FALSE;
7970             }
7971         }
7972       else
7973         {
7974           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7975                                isymbuf, locsymcount)
7976               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7977                                    result, input_bfd))
7978             {
7979               undefined_reference ("symbol", symbuf);
7980               return FALSE;
7981             }
7982         }
7983
7984       return TRUE;
7985
7986       /* All that remains are operators.  */
7987
7988 #define UNARY_OP(op)                                            \
7989   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7990     {                                                           \
7991       sym += strlen (#op);                                      \
7992       if (*sym == ':')                                          \
7993         ++sym;                                                  \
7994       *symp = sym;                                              \
7995       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7996                         isymbuf, locsymcount, signed_p))        \
7997         return FALSE;                                           \
7998       if (signed_p)                                             \
7999         *result = op ((bfd_signed_vma) a);                      \
8000       else                                                      \
8001         *result = op a;                                         \
8002       return TRUE;                                              \
8003     }
8004
8005 #define BINARY_OP(op)                                           \
8006   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8007     {                                                           \
8008       sym += strlen (#op);                                      \
8009       if (*sym == ':')                                          \
8010         ++sym;                                                  \
8011       *symp = sym;                                              \
8012       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8013                         isymbuf, locsymcount, signed_p))        \
8014         return FALSE;                                           \
8015       ++*symp;                                                  \
8016       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8017                         isymbuf, locsymcount, signed_p))        \
8018         return FALSE;                                           \
8019       if (signed_p)                                             \
8020         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8021       else                                                      \
8022         *result = a op b;                                       \
8023       return TRUE;                                              \
8024     }
8025
8026     default:
8027       UNARY_OP  (0-);
8028       BINARY_OP (<<);
8029       BINARY_OP (>>);
8030       BINARY_OP (==);
8031       BINARY_OP (!=);
8032       BINARY_OP (<=);
8033       BINARY_OP (>=);
8034       BINARY_OP (&&);
8035       BINARY_OP (||);
8036       UNARY_OP  (~);
8037       UNARY_OP  (!);
8038       BINARY_OP (*);
8039       BINARY_OP (/);
8040       BINARY_OP (%);
8041       BINARY_OP (^);
8042       BINARY_OP (|);
8043       BINARY_OP (&);
8044       BINARY_OP (+);
8045       BINARY_OP (-);
8046       BINARY_OP (<);
8047       BINARY_OP (>);
8048 #undef UNARY_OP
8049 #undef BINARY_OP
8050       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8051       bfd_set_error (bfd_error_invalid_operation);
8052       return FALSE;
8053     }
8054 }
8055
8056 static void
8057 put_value (bfd_vma size,
8058            unsigned long chunksz,
8059            bfd *input_bfd,
8060            bfd_vma x,
8061            bfd_byte *location)
8062 {
8063   location += (size - chunksz);
8064
8065   for (; size; size -= chunksz, location -= chunksz)
8066     {
8067       switch (chunksz)
8068         {
8069         case 1:
8070           bfd_put_8 (input_bfd, x, location);
8071           x >>= 8;
8072           break;
8073         case 2:
8074           bfd_put_16 (input_bfd, x, location);
8075           x >>= 16;
8076           break;
8077         case 4:
8078           bfd_put_32 (input_bfd, x, location);
8079           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8080           x >>= 16;
8081           x >>= 16;
8082           break;
8083 #ifdef BFD64
8084         case 8:
8085           bfd_put_64 (input_bfd, x, location);
8086           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8087           x >>= 32;
8088           x >>= 32;
8089           break;
8090 #endif
8091         default:
8092           abort ();
8093           break;
8094         }
8095     }
8096 }
8097
8098 static bfd_vma
8099 get_value (bfd_vma size,
8100            unsigned long chunksz,
8101            bfd *input_bfd,
8102            bfd_byte *location)
8103 {
8104   int shift;
8105   bfd_vma x = 0;
8106
8107   /* Sanity checks.  */
8108   BFD_ASSERT (chunksz <= sizeof (x)
8109               && size >= chunksz
8110               && chunksz != 0
8111               && (size % chunksz) == 0
8112               && input_bfd != NULL
8113               && location != NULL);
8114
8115   if (chunksz == sizeof (x))
8116     {
8117       BFD_ASSERT (size == chunksz);
8118
8119       /* Make sure that we do not perform an undefined shift operation.
8120          We know that size == chunksz so there will only be one iteration
8121          of the loop below.  */
8122       shift = 0;
8123     }
8124   else
8125     shift = 8 * chunksz;
8126
8127   for (; size; size -= chunksz, location += chunksz)
8128     {
8129       switch (chunksz)
8130         {
8131         case 1:
8132           x = (x << shift) | bfd_get_8 (input_bfd, location);
8133           break;
8134         case 2:
8135           x = (x << shift) | bfd_get_16 (input_bfd, location);
8136           break;
8137         case 4:
8138           x = (x << shift) | bfd_get_32 (input_bfd, location);
8139           break;
8140 #ifdef BFD64
8141         case 8:
8142           x = (x << shift) | bfd_get_64 (input_bfd, location);
8143           break;
8144 #endif
8145         default:
8146           abort ();
8147         }
8148     }
8149   return x;
8150 }
8151
8152 static void
8153 decode_complex_addend (unsigned long *start,   /* in bits */
8154                        unsigned long *oplen,   /* in bits */
8155                        unsigned long *len,     /* in bits */
8156                        unsigned long *wordsz,  /* in bytes */
8157                        unsigned long *chunksz, /* in bytes */
8158                        unsigned long *lsb0_p,
8159                        unsigned long *signed_p,
8160                        unsigned long *trunc_p,
8161                        unsigned long encoded)
8162 {
8163   * start     =  encoded        & 0x3F;
8164   * len       = (encoded >>  6) & 0x3F;
8165   * oplen     = (encoded >> 12) & 0x3F;
8166   * wordsz    = (encoded >> 18) & 0xF;
8167   * chunksz   = (encoded >> 22) & 0xF;
8168   * lsb0_p    = (encoded >> 27) & 1;
8169   * signed_p  = (encoded >> 28) & 1;
8170   * trunc_p   = (encoded >> 29) & 1;
8171 }
8172
8173 bfd_reloc_status_type
8174 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8175                                     asection *input_section ATTRIBUTE_UNUSED,
8176                                     bfd_byte *contents,
8177                                     Elf_Internal_Rela *rel,
8178                                     bfd_vma relocation)
8179 {
8180   bfd_vma shift, x, mask;
8181   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8182   bfd_reloc_status_type r;
8183
8184   /*  Perform this reloc, since it is complex.
8185       (this is not to say that it necessarily refers to a complex
8186       symbol; merely that it is a self-describing CGEN based reloc.
8187       i.e. the addend has the complete reloc information (bit start, end,
8188       word size, etc) encoded within it.).  */
8189
8190   decode_complex_addend (&start, &oplen, &len, &wordsz,
8191                          &chunksz, &lsb0_p, &signed_p,
8192                          &trunc_p, rel->r_addend);
8193
8194   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8195
8196   if (lsb0_p)
8197     shift = (start + 1) - len;
8198   else
8199     shift = (8 * wordsz) - (start + len);
8200
8201   x = get_value (wordsz, chunksz, input_bfd,
8202                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8203
8204 #ifdef DEBUG
8205   printf ("Doing complex reloc: "
8206           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8207           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8208           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8209           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8210           oplen, (unsigned long) x, (unsigned long) mask,
8211           (unsigned long) relocation);
8212 #endif
8213
8214   r = bfd_reloc_ok;
8215   if (! trunc_p)
8216     /* Now do an overflow check.  */
8217     r = bfd_check_overflow ((signed_p
8218                              ? complain_overflow_signed
8219                              : complain_overflow_unsigned),
8220                             len, 0, (8 * wordsz),
8221                             relocation);
8222
8223   /* Do the deed.  */
8224   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8225
8226 #ifdef DEBUG
8227   printf ("           relocation: %8.8lx\n"
8228           "         shifted mask: %8.8lx\n"
8229           " shifted/masked reloc: %8.8lx\n"
8230           "               result: %8.8lx\n",
8231           (unsigned long) relocation, (unsigned long) (mask << shift),
8232           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8233 #endif
8234   put_value (wordsz, chunksz, input_bfd, x,
8235              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8236   return r;
8237 }
8238
8239 /* Functions to read r_offset from external (target order) reloc
8240    entry.  Faster than bfd_getl32 et al, because we let the compiler
8241    know the value is aligned.  */
8242
8243 static bfd_vma
8244 ext32l_r_offset (const void *p)
8245 {
8246   union aligned32
8247   {
8248     uint32_t v;
8249     unsigned char c[4];
8250   };
8251   const union aligned32 *a
8252     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8253
8254   uint32_t aval = (  (uint32_t) a->c[0]
8255                    | (uint32_t) a->c[1] << 8
8256                    | (uint32_t) a->c[2] << 16
8257                    | (uint32_t) a->c[3] << 24);
8258   return aval;
8259 }
8260
8261 static bfd_vma
8262 ext32b_r_offset (const void *p)
8263 {
8264   union aligned32
8265   {
8266     uint32_t v;
8267     unsigned char c[4];
8268   };
8269   const union aligned32 *a
8270     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8271
8272   uint32_t aval = (  (uint32_t) a->c[0] << 24
8273                    | (uint32_t) a->c[1] << 16
8274                    | (uint32_t) a->c[2] << 8
8275                    | (uint32_t) a->c[3]);
8276   return aval;
8277 }
8278
8279 #ifdef BFD_HOST_64_BIT
8280 static bfd_vma
8281 ext64l_r_offset (const void *p)
8282 {
8283   union aligned64
8284   {
8285     uint64_t v;
8286     unsigned char c[8];
8287   };
8288   const union aligned64 *a
8289     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8290
8291   uint64_t aval = (  (uint64_t) a->c[0]
8292                    | (uint64_t) a->c[1] << 8
8293                    | (uint64_t) a->c[2] << 16
8294                    | (uint64_t) a->c[3] << 24
8295                    | (uint64_t) a->c[4] << 32
8296                    | (uint64_t) a->c[5] << 40
8297                    | (uint64_t) a->c[6] << 48
8298                    | (uint64_t) a->c[7] << 56);
8299   return aval;
8300 }
8301
8302 static bfd_vma
8303 ext64b_r_offset (const void *p)
8304 {
8305   union aligned64
8306   {
8307     uint64_t v;
8308     unsigned char c[8];
8309   };
8310   const union aligned64 *a
8311     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8312
8313   uint64_t aval = (  (uint64_t) a->c[0] << 56
8314                    | (uint64_t) a->c[1] << 48
8315                    | (uint64_t) a->c[2] << 40
8316                    | (uint64_t) a->c[3] << 32
8317                    | (uint64_t) a->c[4] << 24
8318                    | (uint64_t) a->c[5] << 16
8319                    | (uint64_t) a->c[6] << 8
8320                    | (uint64_t) a->c[7]);
8321   return aval;
8322 }
8323 #endif
8324
8325 /* When performing a relocatable link, the input relocations are
8326    preserved.  But, if they reference global symbols, the indices
8327    referenced must be updated.  Update all the relocations found in
8328    RELDATA.  */
8329
8330 static bfd_boolean
8331 elf_link_adjust_relocs (bfd *abfd,
8332                         struct bfd_elf_section_reloc_data *reldata,
8333                         bfd_boolean sort)
8334 {
8335   unsigned int i;
8336   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8337   bfd_byte *erela;
8338   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8339   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8340   bfd_vma r_type_mask;
8341   int r_sym_shift;
8342   unsigned int count = reldata->count;
8343   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8344
8345   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8346     {
8347       swap_in = bed->s->swap_reloc_in;
8348       swap_out = bed->s->swap_reloc_out;
8349     }
8350   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8351     {
8352       swap_in = bed->s->swap_reloca_in;
8353       swap_out = bed->s->swap_reloca_out;
8354     }
8355   else
8356     abort ();
8357
8358   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8359     abort ();
8360
8361   if (bed->s->arch_size == 32)
8362     {
8363       r_type_mask = 0xff;
8364       r_sym_shift = 8;
8365     }
8366   else
8367     {
8368       r_type_mask = 0xffffffff;
8369       r_sym_shift = 32;
8370     }
8371
8372   erela = reldata->hdr->contents;
8373   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8374     {
8375       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8376       unsigned int j;
8377
8378       if (*rel_hash == NULL)
8379         continue;
8380
8381       BFD_ASSERT ((*rel_hash)->indx >= 0);
8382
8383       (*swap_in) (abfd, erela, irela);
8384       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8385         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8386                            | (irela[j].r_info & r_type_mask));
8387       (*swap_out) (abfd, irela, erela);
8388     }
8389
8390   if (sort && count != 0)
8391     {
8392       bfd_vma (*ext_r_off) (const void *);
8393       bfd_vma r_off;
8394       size_t elt_size;
8395       bfd_byte *base, *end, *p, *loc;
8396       bfd_byte *buf = NULL;
8397
8398       if (bed->s->arch_size == 32)
8399         {
8400           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8401             ext_r_off = ext32l_r_offset;
8402           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8403             ext_r_off = ext32b_r_offset;
8404           else
8405             abort ();
8406         }
8407       else
8408         {
8409 #ifdef BFD_HOST_64_BIT
8410           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8411             ext_r_off = ext64l_r_offset;
8412           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8413             ext_r_off = ext64b_r_offset;
8414           else
8415 #endif
8416             abort ();
8417         }
8418
8419       /*  Must use a stable sort here.  A modified insertion sort,
8420           since the relocs are mostly sorted already.  */
8421       elt_size = reldata->hdr->sh_entsize;
8422       base = reldata->hdr->contents;
8423       end = base + count * elt_size;
8424       if (elt_size > sizeof (Elf64_External_Rela))
8425         abort ();
8426
8427       /* Ensure the first element is lowest.  This acts as a sentinel,
8428          speeding the main loop below.  */
8429       r_off = (*ext_r_off) (base);
8430       for (p = loc = base; (p += elt_size) < end; )
8431         {
8432           bfd_vma r_off2 = (*ext_r_off) (p);
8433           if (r_off > r_off2)
8434             {
8435               r_off = r_off2;
8436               loc = p;
8437             }
8438         }
8439       if (loc != base)
8440         {
8441           /* Don't just swap *base and *loc as that changes the order
8442              of the original base[0] and base[1] if they happen to
8443              have the same r_offset.  */
8444           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8445           memcpy (onebuf, loc, elt_size);
8446           memmove (base + elt_size, base, loc - base);
8447           memcpy (base, onebuf, elt_size);
8448         }
8449
8450       for (p = base + elt_size; (p += elt_size) < end; )
8451         {
8452           /* base to p is sorted, *p is next to insert.  */
8453           r_off = (*ext_r_off) (p);
8454           /* Search the sorted region for location to insert.  */
8455           loc = p - elt_size;
8456           while (r_off < (*ext_r_off) (loc))
8457             loc -= elt_size;
8458           loc += elt_size;
8459           if (loc != p)
8460             {
8461               /* Chances are there is a run of relocs to insert here,
8462                  from one of more input files.  Files are not always
8463                  linked in order due to the way elf_link_input_bfd is
8464                  called.  See pr17666.  */
8465               size_t sortlen = p - loc;
8466               bfd_vma r_off2 = (*ext_r_off) (loc);
8467               size_t runlen = elt_size;
8468               size_t buf_size = 96 * 1024;
8469               while (p + runlen < end
8470                      && (sortlen <= buf_size
8471                          || runlen + elt_size <= buf_size)
8472                      && r_off2 > (*ext_r_off) (p + runlen))
8473                 runlen += elt_size;
8474               if (buf == NULL)
8475                 {
8476                   buf = bfd_malloc (buf_size);
8477                   if (buf == NULL)
8478                     return FALSE;
8479                 }
8480               if (runlen < sortlen)
8481                 {
8482                   memcpy (buf, p, runlen);
8483                   memmove (loc + runlen, loc, sortlen);
8484                   memcpy (loc, buf, runlen);
8485                 }
8486               else
8487                 {
8488                   memcpy (buf, loc, sortlen);
8489                   memmove (loc, p, runlen);
8490                   memcpy (loc + runlen, buf, sortlen);
8491                 }
8492               p += runlen - elt_size;
8493             }
8494         }
8495       /* Hashes are no longer valid.  */
8496       free (reldata->hashes);
8497       reldata->hashes = NULL;
8498       free (buf);
8499     }
8500   return TRUE;
8501 }
8502
8503 struct elf_link_sort_rela
8504 {
8505   union {
8506     bfd_vma offset;
8507     bfd_vma sym_mask;
8508   } u;
8509   enum elf_reloc_type_class type;
8510   /* We use this as an array of size int_rels_per_ext_rel.  */
8511   Elf_Internal_Rela rela[1];
8512 };
8513
8514 static int
8515 elf_link_sort_cmp1 (const void *A, const void *B)
8516 {
8517   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8518   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8519   int relativea, relativeb;
8520
8521   relativea = a->type == reloc_class_relative;
8522   relativeb = b->type == reloc_class_relative;
8523
8524   if (relativea < relativeb)
8525     return 1;
8526   if (relativea > relativeb)
8527     return -1;
8528   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8529     return -1;
8530   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8531     return 1;
8532   if (a->rela->r_offset < b->rela->r_offset)
8533     return -1;
8534   if (a->rela->r_offset > b->rela->r_offset)
8535     return 1;
8536   return 0;
8537 }
8538
8539 static int
8540 elf_link_sort_cmp2 (const void *A, const void *B)
8541 {
8542   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8543   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8544
8545   if (a->type < b->type)
8546     return -1;
8547   if (a->type > b->type)
8548     return 1;
8549   if (a->u.offset < b->u.offset)
8550     return -1;
8551   if (a->u.offset > b->u.offset)
8552     return 1;
8553   if (a->rela->r_offset < b->rela->r_offset)
8554     return -1;
8555   if (a->rela->r_offset > b->rela->r_offset)
8556     return 1;
8557   return 0;
8558 }
8559
8560 static size_t
8561 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8562 {
8563   asection *dynamic_relocs;
8564   asection *rela_dyn;
8565   asection *rel_dyn;
8566   bfd_size_type count, size;
8567   size_t i, ret, sort_elt, ext_size;
8568   bfd_byte *sort, *s_non_relative, *p;
8569   struct elf_link_sort_rela *sq;
8570   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8571   int i2e = bed->s->int_rels_per_ext_rel;
8572   unsigned int opb = bfd_octets_per_byte (abfd);
8573   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8574   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8575   struct bfd_link_order *lo;
8576   bfd_vma r_sym_mask;
8577   bfd_boolean use_rela;
8578
8579   /* Find a dynamic reloc section.  */
8580   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8581   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8582   if (rela_dyn != NULL && rela_dyn->size > 0
8583       && rel_dyn != NULL && rel_dyn->size > 0)
8584     {
8585       bfd_boolean use_rela_initialised = FALSE;
8586
8587       /* This is just here to stop gcc from complaining.
8588          Its initialization checking code is not perfect.  */
8589       use_rela = TRUE;
8590
8591       /* Both sections are present.  Examine the sizes
8592          of the indirect sections to help us choose.  */
8593       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8594         if (lo->type == bfd_indirect_link_order)
8595           {
8596             asection *o = lo->u.indirect.section;
8597
8598             if ((o->size % bed->s->sizeof_rela) == 0)
8599               {
8600                 if ((o->size % bed->s->sizeof_rel) == 0)
8601                   /* Section size is divisible by both rel and rela sizes.
8602                      It is of no help to us.  */
8603                   ;
8604                 else
8605                   {
8606                     /* Section size is only divisible by rela.  */
8607                     if (use_rela_initialised && (use_rela == FALSE))
8608                       {
8609                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8610                                               "they are in more than one size"),
8611                                             abfd);
8612                         bfd_set_error (bfd_error_invalid_operation);
8613                         return 0;
8614                       }
8615                     else
8616                       {
8617                         use_rela = TRUE;
8618                         use_rela_initialised = TRUE;
8619                       }
8620                   }
8621               }
8622             else if ((o->size % bed->s->sizeof_rel) == 0)
8623               {
8624                 /* Section size is only divisible by rel.  */
8625                 if (use_rela_initialised && (use_rela == TRUE))
8626                   {
8627                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8628                                           "they are in more than one size"),
8629                                         abfd);
8630                     bfd_set_error (bfd_error_invalid_operation);
8631                     return 0;
8632                   }
8633                 else
8634                   {
8635                     use_rela = FALSE;
8636                     use_rela_initialised = TRUE;
8637                   }
8638               }
8639             else
8640               {
8641                 /* The section size is not divisible by either -
8642                    something is wrong.  */
8643                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8644                                       "they are of an unknown size"), abfd);
8645                 bfd_set_error (bfd_error_invalid_operation);
8646                 return 0;
8647               }
8648           }
8649
8650       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8651         if (lo->type == bfd_indirect_link_order)
8652           {
8653             asection *o = lo->u.indirect.section;
8654
8655             if ((o->size % bed->s->sizeof_rela) == 0)
8656               {
8657                 if ((o->size % bed->s->sizeof_rel) == 0)
8658                   /* Section size is divisible by both rel and rela sizes.
8659                      It is of no help to us.  */
8660                   ;
8661                 else
8662                   {
8663                     /* Section size is only divisible by rela.  */
8664                     if (use_rela_initialised && (use_rela == FALSE))
8665                       {
8666                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8667                                               "they are in more than one size"),
8668                                             abfd);
8669                         bfd_set_error (bfd_error_invalid_operation);
8670                         return 0;
8671                       }
8672                     else
8673                       {
8674                         use_rela = TRUE;
8675                         use_rela_initialised = TRUE;
8676                       }
8677                   }
8678               }
8679             else if ((o->size % bed->s->sizeof_rel) == 0)
8680               {
8681                 /* Section size is only divisible by rel.  */
8682                 if (use_rela_initialised && (use_rela == TRUE))
8683                   {
8684                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8685                                           "they are in more than one size"),
8686                                         abfd);
8687                     bfd_set_error (bfd_error_invalid_operation);
8688                     return 0;
8689                   }
8690                 else
8691                   {
8692                     use_rela = FALSE;
8693                     use_rela_initialised = TRUE;
8694                   }
8695               }
8696             else
8697               {
8698                 /* The section size is not divisible by either -
8699                    something is wrong.  */
8700                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8701                                       "they are of an unknown size"), abfd);
8702                 bfd_set_error (bfd_error_invalid_operation);
8703                 return 0;
8704               }
8705           }
8706
8707       if (! use_rela_initialised)
8708         /* Make a guess.  */
8709         use_rela = TRUE;
8710     }
8711   else if (rela_dyn != NULL && rela_dyn->size > 0)
8712     use_rela = TRUE;
8713   else if (rel_dyn != NULL && rel_dyn->size > 0)
8714     use_rela = FALSE;
8715   else
8716     return 0;
8717
8718   if (use_rela)
8719     {
8720       dynamic_relocs = rela_dyn;
8721       ext_size = bed->s->sizeof_rela;
8722       swap_in = bed->s->swap_reloca_in;
8723       swap_out = bed->s->swap_reloca_out;
8724     }
8725   else
8726     {
8727       dynamic_relocs = rel_dyn;
8728       ext_size = bed->s->sizeof_rel;
8729       swap_in = bed->s->swap_reloc_in;
8730       swap_out = bed->s->swap_reloc_out;
8731     }
8732
8733   size = 0;
8734   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8735     if (lo->type == bfd_indirect_link_order)
8736       size += lo->u.indirect.section->size;
8737
8738   if (size != dynamic_relocs->size)
8739     return 0;
8740
8741   sort_elt = (sizeof (struct elf_link_sort_rela)
8742               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8743
8744   count = dynamic_relocs->size / ext_size;
8745   if (count == 0)
8746     return 0;
8747   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8748
8749   if (sort == NULL)
8750     {
8751       (*info->callbacks->warning)
8752         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8753       return 0;
8754     }
8755
8756   if (bed->s->arch_size == 32)
8757     r_sym_mask = ~(bfd_vma) 0xff;
8758   else
8759     r_sym_mask = ~(bfd_vma) 0xffffffff;
8760
8761   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8762     if (lo->type == bfd_indirect_link_order)
8763       {
8764         bfd_byte *erel, *erelend;
8765         asection *o = lo->u.indirect.section;
8766
8767         if (o->contents == NULL && o->size != 0)
8768           {
8769             /* This is a reloc section that is being handled as a normal
8770                section.  See bfd_section_from_shdr.  We can't combine
8771                relocs in this case.  */
8772             free (sort);
8773             return 0;
8774           }
8775         erel = o->contents;
8776         erelend = o->contents + o->size;
8777         p = sort + o->output_offset * opb / ext_size * sort_elt;
8778
8779         while (erel < erelend)
8780           {
8781             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8782
8783             (*swap_in) (abfd, erel, s->rela);
8784             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8785             s->u.sym_mask = r_sym_mask;
8786             p += sort_elt;
8787             erel += ext_size;
8788           }
8789       }
8790
8791   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8792
8793   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8794     {
8795       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8796       if (s->type != reloc_class_relative)
8797         break;
8798     }
8799   ret = i;
8800   s_non_relative = p;
8801
8802   sq = (struct elf_link_sort_rela *) s_non_relative;
8803   for (; i < count; i++, p += sort_elt)
8804     {
8805       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8806       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8807         sq = sp;
8808       sp->u.offset = sq->rela->r_offset;
8809     }
8810
8811   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8812
8813   struct elf_link_hash_table *htab = elf_hash_table (info);
8814   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
8815     {
8816       /* We have plt relocs in .rela.dyn.  */
8817       sq = (struct elf_link_sort_rela *) sort;
8818       for (i = 0; i < count; i++)
8819         if (sq[count - i - 1].type != reloc_class_plt)
8820           break;
8821       if (i != 0 && htab->srelplt->size == i * ext_size)
8822         {
8823           struct bfd_link_order **plo;
8824           /* Put srelplt link_order last.  This is so the output_offset
8825              set in the next loop is correct for DT_JMPREL.  */
8826           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
8827             if ((*plo)->type == bfd_indirect_link_order
8828                 && (*plo)->u.indirect.section == htab->srelplt)
8829               {
8830                 lo = *plo;
8831                 *plo = lo->next;
8832               }
8833             else
8834               plo = &(*plo)->next;
8835           *plo = lo;
8836           lo->next = NULL;
8837           dynamic_relocs->map_tail.link_order = lo;
8838         }
8839     }
8840
8841   p = sort;
8842   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8843     if (lo->type == bfd_indirect_link_order)
8844       {
8845         bfd_byte *erel, *erelend;
8846         asection *o = lo->u.indirect.section;
8847
8848         erel = o->contents;
8849         erelend = o->contents + o->size;
8850         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
8851         while (erel < erelend)
8852           {
8853             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8854             (*swap_out) (abfd, s->rela, erel);
8855             p += sort_elt;
8856             erel += ext_size;
8857           }
8858       }
8859
8860   free (sort);
8861   *psec = dynamic_relocs;
8862   return ret;
8863 }
8864
8865 /* Add a symbol to the output symbol string table.  */
8866
8867 static int
8868 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8869                            const char *name,
8870                            Elf_Internal_Sym *elfsym,
8871                            asection *input_sec,
8872                            struct elf_link_hash_entry *h)
8873 {
8874   int (*output_symbol_hook)
8875     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8876      struct elf_link_hash_entry *);
8877   struct elf_link_hash_table *hash_table;
8878   const struct elf_backend_data *bed;
8879   bfd_size_type strtabsize;
8880
8881   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8882
8883   bed = get_elf_backend_data (flinfo->output_bfd);
8884   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8885   if (output_symbol_hook != NULL)
8886     {
8887       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8888       if (ret != 1)
8889         return ret;
8890     }
8891
8892   if (name == NULL
8893       || *name == '\0'
8894       || (input_sec->flags & SEC_EXCLUDE))
8895     elfsym->st_name = (unsigned long) -1;
8896   else
8897     {
8898       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8899          to get the final offset for st_name.  */
8900       elfsym->st_name
8901         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8902                                                name, FALSE);
8903       if (elfsym->st_name == (unsigned long) -1)
8904         return 0;
8905     }
8906
8907   hash_table = elf_hash_table (flinfo->info);
8908   strtabsize = hash_table->strtabsize;
8909   if (strtabsize <= hash_table->strtabcount)
8910     {
8911       strtabsize += strtabsize;
8912       hash_table->strtabsize = strtabsize;
8913       strtabsize *= sizeof (*hash_table->strtab);
8914       hash_table->strtab
8915         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8916                                                  strtabsize);
8917       if (hash_table->strtab == NULL)
8918         return 0;
8919     }
8920   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8921   hash_table->strtab[hash_table->strtabcount].dest_index
8922     = hash_table->strtabcount;
8923   hash_table->strtab[hash_table->strtabcount].destshndx_index
8924     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8925
8926   bfd_get_symcount (flinfo->output_bfd) += 1;
8927   hash_table->strtabcount += 1;
8928
8929   return 1;
8930 }
8931
8932 /* Swap symbols out to the symbol table and flush the output symbols to
8933    the file.  */
8934
8935 static bfd_boolean
8936 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8937 {
8938   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8939   bfd_size_type amt;
8940   size_t i;
8941   const struct elf_backend_data *bed;
8942   bfd_byte *symbuf;
8943   Elf_Internal_Shdr *hdr;
8944   file_ptr pos;
8945   bfd_boolean ret;
8946
8947   if (!hash_table->strtabcount)
8948     return TRUE;
8949
8950   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8951
8952   bed = get_elf_backend_data (flinfo->output_bfd);
8953
8954   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8955   symbuf = (bfd_byte *) bfd_malloc (amt);
8956   if (symbuf == NULL)
8957     return FALSE;
8958
8959   if (flinfo->symshndxbuf)
8960     {
8961       amt = sizeof (Elf_External_Sym_Shndx);
8962       amt *= bfd_get_symcount (flinfo->output_bfd);
8963       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8964       if (flinfo->symshndxbuf == NULL)
8965         {
8966           free (symbuf);
8967           return FALSE;
8968         }
8969     }
8970
8971   for (i = 0; i < hash_table->strtabcount; i++)
8972     {
8973       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8974       if (elfsym->sym.st_name == (unsigned long) -1)
8975         elfsym->sym.st_name = 0;
8976       else
8977         elfsym->sym.st_name
8978           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8979                                                     elfsym->sym.st_name);
8980       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8981                                ((bfd_byte *) symbuf
8982                                 + (elfsym->dest_index
8983                                    * bed->s->sizeof_sym)),
8984                                (flinfo->symshndxbuf
8985                                 + elfsym->destshndx_index));
8986     }
8987
8988   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8989   pos = hdr->sh_offset + hdr->sh_size;
8990   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8991   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8992       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8993     {
8994       hdr->sh_size += amt;
8995       ret = TRUE;
8996     }
8997   else
8998     ret = FALSE;
8999
9000   free (symbuf);
9001
9002   free (hash_table->strtab);
9003   hash_table->strtab = NULL;
9004
9005   return ret;
9006 }
9007
9008 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9009
9010 static bfd_boolean
9011 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9012 {
9013   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9014       && sym->st_shndx < SHN_LORESERVE)
9015     {
9016       /* The gABI doesn't support dynamic symbols in output sections
9017          beyond 64k.  */
9018       (*_bfd_error_handler)
9019         (_("%B: Too many sections: %d (>= %d)"),
9020          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9021       bfd_set_error (bfd_error_nonrepresentable_section);
9022       return FALSE;
9023     }
9024   return TRUE;
9025 }
9026
9027 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9028    allowing an unsatisfied unversioned symbol in the DSO to match a
9029    versioned symbol that would normally require an explicit version.
9030    We also handle the case that a DSO references a hidden symbol
9031    which may be satisfied by a versioned symbol in another DSO.  */
9032
9033 static bfd_boolean
9034 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9035                                  const struct elf_backend_data *bed,
9036                                  struct elf_link_hash_entry *h)
9037 {
9038   bfd *abfd;
9039   struct elf_link_loaded_list *loaded;
9040
9041   if (!is_elf_hash_table (info->hash))
9042     return FALSE;
9043
9044   /* Check indirect symbol.  */
9045   while (h->root.type == bfd_link_hash_indirect)
9046     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9047
9048   switch (h->root.type)
9049     {
9050     default:
9051       abfd = NULL;
9052       break;
9053
9054     case bfd_link_hash_undefined:
9055     case bfd_link_hash_undefweak:
9056       abfd = h->root.u.undef.abfd;
9057       if (abfd == NULL
9058           || (abfd->flags & DYNAMIC) == 0
9059           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9060         return FALSE;
9061       break;
9062
9063     case bfd_link_hash_defined:
9064     case bfd_link_hash_defweak:
9065       abfd = h->root.u.def.section->owner;
9066       break;
9067
9068     case bfd_link_hash_common:
9069       abfd = h->root.u.c.p->section->owner;
9070       break;
9071     }
9072   BFD_ASSERT (abfd != NULL);
9073
9074   for (loaded = elf_hash_table (info)->loaded;
9075        loaded != NULL;
9076        loaded = loaded->next)
9077     {
9078       bfd *input;
9079       Elf_Internal_Shdr *hdr;
9080       size_t symcount;
9081       size_t extsymcount;
9082       size_t extsymoff;
9083       Elf_Internal_Shdr *versymhdr;
9084       Elf_Internal_Sym *isym;
9085       Elf_Internal_Sym *isymend;
9086       Elf_Internal_Sym *isymbuf;
9087       Elf_External_Versym *ever;
9088       Elf_External_Versym *extversym;
9089
9090       input = loaded->abfd;
9091
9092       /* We check each DSO for a possible hidden versioned definition.  */
9093       if (input == abfd
9094           || (input->flags & DYNAMIC) == 0
9095           || elf_dynversym (input) == 0)
9096         continue;
9097
9098       hdr = &elf_tdata (input)->dynsymtab_hdr;
9099
9100       symcount = hdr->sh_size / bed->s->sizeof_sym;
9101       if (elf_bad_symtab (input))
9102         {
9103           extsymcount = symcount;
9104           extsymoff = 0;
9105         }
9106       else
9107         {
9108           extsymcount = symcount - hdr->sh_info;
9109           extsymoff = hdr->sh_info;
9110         }
9111
9112       if (extsymcount == 0)
9113         continue;
9114
9115       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9116                                       NULL, NULL, NULL);
9117       if (isymbuf == NULL)
9118         return FALSE;
9119
9120       /* Read in any version definitions.  */
9121       versymhdr = &elf_tdata (input)->dynversym_hdr;
9122       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9123       if (extversym == NULL)
9124         goto error_ret;
9125
9126       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9127           || (bfd_bread (extversym, versymhdr->sh_size, input)
9128               != versymhdr->sh_size))
9129         {
9130           free (extversym);
9131         error_ret:
9132           free (isymbuf);
9133           return FALSE;
9134         }
9135
9136       ever = extversym + extsymoff;
9137       isymend = isymbuf + extsymcount;
9138       for (isym = isymbuf; isym < isymend; isym++, ever++)
9139         {
9140           const char *name;
9141           Elf_Internal_Versym iver;
9142           unsigned short version_index;
9143
9144           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9145               || isym->st_shndx == SHN_UNDEF)
9146             continue;
9147
9148           name = bfd_elf_string_from_elf_section (input,
9149                                                   hdr->sh_link,
9150                                                   isym->st_name);
9151           if (strcmp (name, h->root.root.string) != 0)
9152             continue;
9153
9154           _bfd_elf_swap_versym_in (input, ever, &iver);
9155
9156           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9157               && !(h->def_regular
9158                    && h->forced_local))
9159             {
9160               /* If we have a non-hidden versioned sym, then it should
9161                  have provided a definition for the undefined sym unless
9162                  it is defined in a non-shared object and forced local.
9163                */
9164               abort ();
9165             }
9166
9167           version_index = iver.vs_vers & VERSYM_VERSION;
9168           if (version_index == 1 || version_index == 2)
9169             {
9170               /* This is the base or first version.  We can use it.  */
9171               free (extversym);
9172               free (isymbuf);
9173               return TRUE;
9174             }
9175         }
9176
9177       free (extversym);
9178       free (isymbuf);
9179     }
9180
9181   return FALSE;
9182 }
9183
9184 /* Convert ELF common symbol TYPE.  */
9185
9186 static int
9187 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9188 {
9189   /* Commom symbol can only appear in relocatable link.  */
9190   if (!bfd_link_relocatable (info))
9191     abort ();
9192   switch (info->elf_stt_common)
9193     {
9194     case unchanged:
9195       break;
9196     case elf_stt_common:
9197       type = STT_COMMON;
9198       break;
9199     case no_elf_stt_common:
9200       type = STT_OBJECT;
9201       break;
9202     }
9203   return type;
9204 }
9205
9206 /* Add an external symbol to the symbol table.  This is called from
9207    the hash table traversal routine.  When generating a shared object,
9208    we go through the symbol table twice.  The first time we output
9209    anything that might have been forced to local scope in a version
9210    script.  The second time we output the symbols that are still
9211    global symbols.  */
9212
9213 static bfd_boolean
9214 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9215 {
9216   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9217   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9218   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9219   bfd_boolean strip;
9220   Elf_Internal_Sym sym;
9221   asection *input_sec;
9222   const struct elf_backend_data *bed;
9223   long indx;
9224   int ret;
9225   unsigned int type;
9226   /* A symbol is bound locally if it is forced local or it is locally
9227      defined, hidden versioned, not referenced by shared library and
9228      not exported when linking executable.  */
9229   bfd_boolean local_bind = (h->forced_local
9230                             || (bfd_link_executable (flinfo->info)
9231                                 && !flinfo->info->export_dynamic
9232                                 && !h->dynamic
9233                                 && !h->ref_dynamic
9234                                 && h->def_regular
9235                                 && h->versioned == versioned_hidden));
9236
9237   if (h->root.type == bfd_link_hash_warning)
9238     {
9239       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9240       if (h->root.type == bfd_link_hash_new)
9241         return TRUE;
9242     }
9243
9244   /* Decide whether to output this symbol in this pass.  */
9245   if (eoinfo->localsyms)
9246     {
9247       if (!local_bind)
9248         return TRUE;
9249     }
9250   else
9251     {
9252       if (local_bind)
9253         return TRUE;
9254     }
9255
9256   bed = get_elf_backend_data (flinfo->output_bfd);
9257
9258   if (h->root.type == bfd_link_hash_undefined)
9259     {
9260       /* If we have an undefined symbol reference here then it must have
9261          come from a shared library that is being linked in.  (Undefined
9262          references in regular files have already been handled unless
9263          they are in unreferenced sections which are removed by garbage
9264          collection).  */
9265       bfd_boolean ignore_undef = FALSE;
9266
9267       /* Some symbols may be special in that the fact that they're
9268          undefined can be safely ignored - let backend determine that.  */
9269       if (bed->elf_backend_ignore_undef_symbol)
9270         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9271
9272       /* If we are reporting errors for this situation then do so now.  */
9273       if (!ignore_undef
9274           && h->ref_dynamic
9275           && (!h->ref_regular || flinfo->info->gc_sections)
9276           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9277           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9278         (*flinfo->info->callbacks->undefined_symbol)
9279           (flinfo->info, h->root.root.string,
9280            h->ref_regular ? NULL : h->root.u.undef.abfd,
9281            NULL, 0,
9282            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9283
9284       /* Strip a global symbol defined in a discarded section.  */
9285       if (h->indx == -3)
9286         return TRUE;
9287     }
9288
9289   /* We should also warn if a forced local symbol is referenced from
9290      shared libraries.  */
9291   if (bfd_link_executable (flinfo->info)
9292       && h->forced_local
9293       && h->ref_dynamic
9294       && h->def_regular
9295       && !h->dynamic_def
9296       && h->ref_dynamic_nonweak
9297       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9298     {
9299       bfd *def_bfd;
9300       const char *msg;
9301       struct elf_link_hash_entry *hi = h;
9302
9303       /* Check indirect symbol.  */
9304       while (hi->root.type == bfd_link_hash_indirect)
9305         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9306
9307       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9308         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9309       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9310         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9311       else
9312         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9313       def_bfd = flinfo->output_bfd;
9314       if (hi->root.u.def.section != bfd_abs_section_ptr)
9315         def_bfd = hi->root.u.def.section->owner;
9316       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9317                              h->root.root.string);
9318       bfd_set_error (bfd_error_bad_value);
9319       eoinfo->failed = TRUE;
9320       return FALSE;
9321     }
9322
9323   /* We don't want to output symbols that have never been mentioned by
9324      a regular file, or that we have been told to strip.  However, if
9325      h->indx is set to -2, the symbol is used by a reloc and we must
9326      output it.  */
9327   strip = FALSE;
9328   if (h->indx == -2)
9329     ;
9330   else if ((h->def_dynamic
9331             || h->ref_dynamic
9332             || h->root.type == bfd_link_hash_new)
9333            && !h->def_regular
9334            && !h->ref_regular)
9335     strip = TRUE;
9336   else if (flinfo->info->strip == strip_all)
9337     strip = TRUE;
9338   else if (flinfo->info->strip == strip_some
9339            && bfd_hash_lookup (flinfo->info->keep_hash,
9340                                h->root.root.string, FALSE, FALSE) == NULL)
9341     strip = TRUE;
9342   else if ((h->root.type == bfd_link_hash_defined
9343             || h->root.type == bfd_link_hash_defweak)
9344            && ((flinfo->info->strip_discarded
9345                 && discarded_section (h->root.u.def.section))
9346                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9347                    && h->root.u.def.section->owner != NULL
9348                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9349     strip = TRUE;
9350   else if ((h->root.type == bfd_link_hash_undefined
9351             || h->root.type == bfd_link_hash_undefweak)
9352            && h->root.u.undef.abfd != NULL
9353            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9354     strip = TRUE;
9355
9356   type = h->type;
9357
9358   /* If we're stripping it, and it's not a dynamic symbol, there's
9359      nothing else to do.   However, if it is a forced local symbol or
9360      an ifunc symbol we need to give the backend finish_dynamic_symbol
9361      function a chance to make it dynamic.  */
9362   if (strip
9363       && h->dynindx == -1
9364       && type != STT_GNU_IFUNC
9365       && !h->forced_local)
9366     return TRUE;
9367
9368   sym.st_value = 0;
9369   sym.st_size = h->size;
9370   sym.st_other = h->other;
9371   switch (h->root.type)
9372     {
9373     default:
9374     case bfd_link_hash_new:
9375     case bfd_link_hash_warning:
9376       abort ();
9377       return FALSE;
9378
9379     case bfd_link_hash_undefined:
9380     case bfd_link_hash_undefweak:
9381       input_sec = bfd_und_section_ptr;
9382       sym.st_shndx = SHN_UNDEF;
9383       break;
9384
9385     case bfd_link_hash_defined:
9386     case bfd_link_hash_defweak:
9387       {
9388         input_sec = h->root.u.def.section;
9389         if (input_sec->output_section != NULL)
9390           {
9391             sym.st_shndx =
9392               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9393                                                  input_sec->output_section);
9394             if (sym.st_shndx == SHN_BAD)
9395               {
9396                 (*_bfd_error_handler)
9397                   (_("%B: could not find output section %A for input section %A"),
9398                    flinfo->output_bfd, input_sec->output_section, input_sec);
9399                 bfd_set_error (bfd_error_nonrepresentable_section);
9400                 eoinfo->failed = TRUE;
9401                 return FALSE;
9402               }
9403
9404             /* ELF symbols in relocatable files are section relative,
9405                but in nonrelocatable files they are virtual
9406                addresses.  */
9407             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9408             if (!bfd_link_relocatable (flinfo->info))
9409               {
9410                 sym.st_value += input_sec->output_section->vma;
9411                 if (h->type == STT_TLS)
9412                   {
9413                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9414                     if (tls_sec != NULL)
9415                       sym.st_value -= tls_sec->vma;
9416                   }
9417               }
9418           }
9419         else
9420           {
9421             BFD_ASSERT (input_sec->owner == NULL
9422                         || (input_sec->owner->flags & DYNAMIC) != 0);
9423             sym.st_shndx = SHN_UNDEF;
9424             input_sec = bfd_und_section_ptr;
9425           }
9426       }
9427       break;
9428
9429     case bfd_link_hash_common:
9430       input_sec = h->root.u.c.p->section;
9431       sym.st_shndx = bed->common_section_index (input_sec);
9432       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9433       break;
9434
9435     case bfd_link_hash_indirect:
9436       /* These symbols are created by symbol versioning.  They point
9437          to the decorated version of the name.  For example, if the
9438          symbol foo@@GNU_1.2 is the default, which should be used when
9439          foo is used with no version, then we add an indirect symbol
9440          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9441          since the indirected symbol is already in the hash table.  */
9442       return TRUE;
9443     }
9444
9445   if (type == STT_COMMON || type == STT_OBJECT)
9446     switch (h->root.type)
9447       {
9448       case bfd_link_hash_common:
9449         type = elf_link_convert_common_type (flinfo->info, type);
9450         break;
9451       case bfd_link_hash_defined:
9452       case bfd_link_hash_defweak:
9453         if (bed->common_definition (&sym))
9454           type = elf_link_convert_common_type (flinfo->info, type);
9455         else
9456           type = STT_OBJECT;
9457         break;
9458       case bfd_link_hash_undefined:
9459       case bfd_link_hash_undefweak:
9460         break;
9461       default:
9462         abort ();
9463       }
9464
9465   if (local_bind)
9466     {
9467       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9468       /* Turn off visibility on local symbol.  */
9469       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9470     }
9471   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9472   else if (h->unique_global && h->def_regular)
9473     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9474   else if (h->root.type == bfd_link_hash_undefweak
9475            || h->root.type == bfd_link_hash_defweak)
9476     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9477   else
9478     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9479   sym.st_target_internal = h->target_internal;
9480
9481   /* Give the processor backend a chance to tweak the symbol value,
9482      and also to finish up anything that needs to be done for this
9483      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9484      forced local syms when non-shared is due to a historical quirk.
9485      STT_GNU_IFUNC symbol must go through PLT.  */
9486   if ((h->type == STT_GNU_IFUNC
9487        && h->def_regular
9488        && !bfd_link_relocatable (flinfo->info))
9489       || ((h->dynindx != -1
9490            || h->forced_local)
9491           && ((bfd_link_pic (flinfo->info)
9492                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9493                    || h->root.type != bfd_link_hash_undefweak))
9494               || !h->forced_local)
9495           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9496     {
9497       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9498              (flinfo->output_bfd, flinfo->info, h, &sym)))
9499         {
9500           eoinfo->failed = TRUE;
9501           return FALSE;
9502         }
9503     }
9504
9505   /* If we are marking the symbol as undefined, and there are no
9506      non-weak references to this symbol from a regular object, then
9507      mark the symbol as weak undefined; if there are non-weak
9508      references, mark the symbol as strong.  We can't do this earlier,
9509      because it might not be marked as undefined until the
9510      finish_dynamic_symbol routine gets through with it.  */
9511   if (sym.st_shndx == SHN_UNDEF
9512       && h->ref_regular
9513       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9514           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9515     {
9516       int bindtype;
9517       type = ELF_ST_TYPE (sym.st_info);
9518
9519       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9520       if (type == STT_GNU_IFUNC)
9521         type = STT_FUNC;
9522
9523       if (h->ref_regular_nonweak)
9524         bindtype = STB_GLOBAL;
9525       else
9526         bindtype = STB_WEAK;
9527       sym.st_info = ELF_ST_INFO (bindtype, type);
9528     }
9529
9530   /* If this is a symbol defined in a dynamic library, don't use the
9531      symbol size from the dynamic library.  Relinking an executable
9532      against a new library may introduce gratuitous changes in the
9533      executable's symbols if we keep the size.  */
9534   if (sym.st_shndx == SHN_UNDEF
9535       && !h->def_regular
9536       && h->def_dynamic)
9537     sym.st_size = 0;
9538
9539   /* If a non-weak symbol with non-default visibility is not defined
9540      locally, it is a fatal error.  */
9541   if (!bfd_link_relocatable (flinfo->info)
9542       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9543       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9544       && h->root.type == bfd_link_hash_undefined
9545       && !h->def_regular)
9546     {
9547       const char *msg;
9548
9549       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9550         msg = _("%B: protected symbol `%s' isn't defined");
9551       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9552         msg = _("%B: internal symbol `%s' isn't defined");
9553       else
9554         msg = _("%B: hidden symbol `%s' isn't defined");
9555       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9556       bfd_set_error (bfd_error_bad_value);
9557       eoinfo->failed = TRUE;
9558       return FALSE;
9559     }
9560
9561   /* If this symbol should be put in the .dynsym section, then put it
9562      there now.  We already know the symbol index.  We also fill in
9563      the entry in the .hash section.  */
9564   if (elf_hash_table (flinfo->info)->dynsym != NULL
9565       && h->dynindx != -1
9566       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9567     {
9568       bfd_byte *esym;
9569
9570       /* Since there is no version information in the dynamic string,
9571          if there is no version info in symbol version section, we will
9572          have a run-time problem if not linking executable, referenced
9573          by shared library, not locally defined, or not bound locally.
9574       */
9575       if (h->verinfo.verdef == NULL
9576           && !local_bind
9577           && (!bfd_link_executable (flinfo->info)
9578               || h->ref_dynamic
9579               || !h->def_regular))
9580         {
9581           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9582
9583           if (p && p [1] != '\0')
9584             {
9585               (*_bfd_error_handler)
9586                 (_("%B: No symbol version section for versioned symbol `%s'"),
9587                  flinfo->output_bfd, h->root.root.string);
9588               eoinfo->failed = TRUE;
9589               return FALSE;
9590             }
9591         }
9592
9593       sym.st_name = h->dynstr_index;
9594       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9595               + h->dynindx * bed->s->sizeof_sym);
9596       if (!check_dynsym (flinfo->output_bfd, &sym))
9597         {
9598           eoinfo->failed = TRUE;
9599           return FALSE;
9600         }
9601       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9602
9603       if (flinfo->hash_sec != NULL)
9604         {
9605           size_t hash_entry_size;
9606           bfd_byte *bucketpos;
9607           bfd_vma chain;
9608           size_t bucketcount;
9609           size_t bucket;
9610
9611           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9612           bucket = h->u.elf_hash_value % bucketcount;
9613
9614           hash_entry_size
9615             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9616           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9617                        + (bucket + 2) * hash_entry_size);
9618           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9619           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9620                    bucketpos);
9621           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9622                    ((bfd_byte *) flinfo->hash_sec->contents
9623                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9624         }
9625
9626       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9627         {
9628           Elf_Internal_Versym iversym;
9629           Elf_External_Versym *eversym;
9630
9631           if (!h->def_regular)
9632             {
9633               if (h->verinfo.verdef == NULL
9634                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9635                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9636                 iversym.vs_vers = 0;
9637               else
9638                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9639             }
9640           else
9641             {
9642               if (h->verinfo.vertree == NULL)
9643                 iversym.vs_vers = 1;
9644               else
9645                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9646               if (flinfo->info->create_default_symver)
9647                 iversym.vs_vers++;
9648             }
9649
9650           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9651              defined locally.  */
9652           if (h->versioned == versioned_hidden && h->def_regular)
9653             iversym.vs_vers |= VERSYM_HIDDEN;
9654
9655           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9656           eversym += h->dynindx;
9657           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9658         }
9659     }
9660
9661   /* If the symbol is undefined, and we didn't output it to .dynsym,
9662      strip it from .symtab too.  Obviously we can't do this for
9663      relocatable output or when needed for --emit-relocs.  */
9664   else if (input_sec == bfd_und_section_ptr
9665            && h->indx != -2
9666            && !bfd_link_relocatable (flinfo->info))
9667     return TRUE;
9668   /* Also strip others that we couldn't earlier due to dynamic symbol
9669      processing.  */
9670   if (strip)
9671     return TRUE;
9672   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9673     return TRUE;
9674
9675   /* Output a FILE symbol so that following locals are not associated
9676      with the wrong input file.  We need one for forced local symbols
9677      if we've seen more than one FILE symbol or when we have exactly
9678      one FILE symbol but global symbols are present in a file other
9679      than the one with the FILE symbol.  We also need one if linker
9680      defined symbols are present.  In practice these conditions are
9681      always met, so just emit the FILE symbol unconditionally.  */
9682   if (eoinfo->localsyms
9683       && !eoinfo->file_sym_done
9684       && eoinfo->flinfo->filesym_count != 0)
9685     {
9686       Elf_Internal_Sym fsym;
9687
9688       memset (&fsym, 0, sizeof (fsym));
9689       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9690       fsym.st_shndx = SHN_ABS;
9691       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9692                                       bfd_und_section_ptr, NULL))
9693         return FALSE;
9694
9695       eoinfo->file_sym_done = TRUE;
9696     }
9697
9698   indx = bfd_get_symcount (flinfo->output_bfd);
9699   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9700                                    input_sec, h);
9701   if (ret == 0)
9702     {
9703       eoinfo->failed = TRUE;
9704       return FALSE;
9705     }
9706   else if (ret == 1)
9707     h->indx = indx;
9708   else if (h->indx == -2)
9709     abort();
9710
9711   return TRUE;
9712 }
9713
9714 /* Return TRUE if special handling is done for relocs in SEC against
9715    symbols defined in discarded sections.  */
9716
9717 static bfd_boolean
9718 elf_section_ignore_discarded_relocs (asection *sec)
9719 {
9720   const struct elf_backend_data *bed;
9721
9722   switch (sec->sec_info_type)
9723     {
9724     case SEC_INFO_TYPE_STABS:
9725     case SEC_INFO_TYPE_EH_FRAME:
9726     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9727       return TRUE;
9728     default:
9729       break;
9730     }
9731
9732   bed = get_elf_backend_data (sec->owner);
9733   if (bed->elf_backend_ignore_discarded_relocs != NULL
9734       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9735     return TRUE;
9736
9737   return FALSE;
9738 }
9739
9740 /* Return a mask saying how ld should treat relocations in SEC against
9741    symbols defined in discarded sections.  If this function returns
9742    COMPLAIN set, ld will issue a warning message.  If this function
9743    returns PRETEND set, and the discarded section was link-once and the
9744    same size as the kept link-once section, ld will pretend that the
9745    symbol was actually defined in the kept section.  Otherwise ld will
9746    zero the reloc (at least that is the intent, but some cooperation by
9747    the target dependent code is needed, particularly for REL targets).  */
9748
9749 unsigned int
9750 _bfd_elf_default_action_discarded (asection *sec)
9751 {
9752   if (sec->flags & SEC_DEBUGGING)
9753     return PRETEND;
9754
9755   if (strcmp (".eh_frame", sec->name) == 0)
9756     return 0;
9757
9758   if (strcmp (".gcc_except_table", sec->name) == 0)
9759     return 0;
9760
9761   return COMPLAIN | PRETEND;
9762 }
9763
9764 /* Find a match between a section and a member of a section group.  */
9765
9766 static asection *
9767 match_group_member (asection *sec, asection *group,
9768                     struct bfd_link_info *info)
9769 {
9770   asection *first = elf_next_in_group (group);
9771   asection *s = first;
9772
9773   while (s != NULL)
9774     {
9775       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9776         return s;
9777
9778       s = elf_next_in_group (s);
9779       if (s == first)
9780         break;
9781     }
9782
9783   return NULL;
9784 }
9785
9786 /* Check if the kept section of a discarded section SEC can be used
9787    to replace it.  Return the replacement if it is OK.  Otherwise return
9788    NULL.  */
9789
9790 asection *
9791 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9792 {
9793   asection *kept;
9794
9795   kept = sec->kept_section;
9796   if (kept != NULL)
9797     {
9798       if ((kept->flags & SEC_GROUP) != 0)
9799         kept = match_group_member (sec, kept, info);
9800       if (kept != NULL
9801           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9802               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9803         kept = NULL;
9804       sec->kept_section = kept;
9805     }
9806   return kept;
9807 }
9808
9809 /* Link an input file into the linker output file.  This function
9810    handles all the sections and relocations of the input file at once.
9811    This is so that we only have to read the local symbols once, and
9812    don't have to keep them in memory.  */
9813
9814 static bfd_boolean
9815 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9816 {
9817   int (*relocate_section)
9818     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9819      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9820   bfd *output_bfd;
9821   Elf_Internal_Shdr *symtab_hdr;
9822   size_t locsymcount;
9823   size_t extsymoff;
9824   Elf_Internal_Sym *isymbuf;
9825   Elf_Internal_Sym *isym;
9826   Elf_Internal_Sym *isymend;
9827   long *pindex;
9828   asection **ppsection;
9829   asection *o;
9830   const struct elf_backend_data *bed;
9831   struct elf_link_hash_entry **sym_hashes;
9832   bfd_size_type address_size;
9833   bfd_vma r_type_mask;
9834   int r_sym_shift;
9835   bfd_boolean have_file_sym = FALSE;
9836
9837   output_bfd = flinfo->output_bfd;
9838   bed = get_elf_backend_data (output_bfd);
9839   relocate_section = bed->elf_backend_relocate_section;
9840
9841   /* If this is a dynamic object, we don't want to do anything here:
9842      we don't want the local symbols, and we don't want the section
9843      contents.  */
9844   if ((input_bfd->flags & DYNAMIC) != 0)
9845     return TRUE;
9846
9847   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9848   if (elf_bad_symtab (input_bfd))
9849     {
9850       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9851       extsymoff = 0;
9852     }
9853   else
9854     {
9855       locsymcount = symtab_hdr->sh_info;
9856       extsymoff = symtab_hdr->sh_info;
9857     }
9858
9859   /* Read the local symbols.  */
9860   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9861   if (isymbuf == NULL && locsymcount != 0)
9862     {
9863       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9864                                       flinfo->internal_syms,
9865                                       flinfo->external_syms,
9866                                       flinfo->locsym_shndx);
9867       if (isymbuf == NULL)
9868         return FALSE;
9869     }
9870
9871   /* Find local symbol sections and adjust values of symbols in
9872      SEC_MERGE sections.  Write out those local symbols we know are
9873      going into the output file.  */
9874   isymend = isymbuf + locsymcount;
9875   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9876        isym < isymend;
9877        isym++, pindex++, ppsection++)
9878     {
9879       asection *isec;
9880       const char *name;
9881       Elf_Internal_Sym osym;
9882       long indx;
9883       int ret;
9884
9885       *pindex = -1;
9886
9887       if (elf_bad_symtab (input_bfd))
9888         {
9889           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9890             {
9891               *ppsection = NULL;
9892               continue;
9893             }
9894         }
9895
9896       if (isym->st_shndx == SHN_UNDEF)
9897         isec = bfd_und_section_ptr;
9898       else if (isym->st_shndx == SHN_ABS)
9899         isec = bfd_abs_section_ptr;
9900       else if (isym->st_shndx == SHN_COMMON)
9901         isec = bfd_com_section_ptr;
9902       else
9903         {
9904           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9905           if (isec == NULL)
9906             {
9907               /* Don't attempt to output symbols with st_shnx in the
9908                  reserved range other than SHN_ABS and SHN_COMMON.  */
9909               *ppsection = NULL;
9910               continue;
9911             }
9912           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9913                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9914             isym->st_value =
9915               _bfd_merged_section_offset (output_bfd, &isec,
9916                                           elf_section_data (isec)->sec_info,
9917                                           isym->st_value);
9918         }
9919
9920       *ppsection = isec;
9921
9922       /* Don't output the first, undefined, symbol.  In fact, don't
9923          output any undefined local symbol.  */
9924       if (isec == bfd_und_section_ptr)
9925         continue;
9926
9927       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9928         {
9929           /* We never output section symbols.  Instead, we use the
9930              section symbol of the corresponding section in the output
9931              file.  */
9932           continue;
9933         }
9934
9935       /* If we are stripping all symbols, we don't want to output this
9936          one.  */
9937       if (flinfo->info->strip == strip_all)
9938         continue;
9939
9940       /* If we are discarding all local symbols, we don't want to
9941          output this one.  If we are generating a relocatable output
9942          file, then some of the local symbols may be required by
9943          relocs; we output them below as we discover that they are
9944          needed.  */
9945       if (flinfo->info->discard == discard_all)
9946         continue;
9947
9948       /* If this symbol is defined in a section which we are
9949          discarding, we don't need to keep it.  */
9950       if (isym->st_shndx != SHN_UNDEF
9951           && isym->st_shndx < SHN_LORESERVE
9952           && bfd_section_removed_from_list (output_bfd,
9953                                             isec->output_section))
9954         continue;
9955
9956       /* Get the name of the symbol.  */
9957       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9958                                               isym->st_name);
9959       if (name == NULL)
9960         return FALSE;
9961
9962       /* See if we are discarding symbols with this name.  */
9963       if ((flinfo->info->strip == strip_some
9964            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9965                == NULL))
9966           || (((flinfo->info->discard == discard_sec_merge
9967                 && (isec->flags & SEC_MERGE)
9968                 && !bfd_link_relocatable (flinfo->info))
9969                || flinfo->info->discard == discard_l)
9970               && bfd_is_local_label_name (input_bfd, name)))
9971         continue;
9972
9973       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9974         {
9975           if (input_bfd->lto_output)
9976             /* -flto puts a temp file name here.  This means builds
9977                are not reproducible.  Discard the symbol.  */
9978             continue;
9979           have_file_sym = TRUE;
9980           flinfo->filesym_count += 1;
9981         }
9982       if (!have_file_sym)
9983         {
9984           /* In the absence of debug info, bfd_find_nearest_line uses
9985              FILE symbols to determine the source file for local
9986              function symbols.  Provide a FILE symbol here if input
9987              files lack such, so that their symbols won't be
9988              associated with a previous input file.  It's not the
9989              source file, but the best we can do.  */
9990           have_file_sym = TRUE;
9991           flinfo->filesym_count += 1;
9992           memset (&osym, 0, sizeof (osym));
9993           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9994           osym.st_shndx = SHN_ABS;
9995           if (!elf_link_output_symstrtab (flinfo,
9996                                           (input_bfd->lto_output ? NULL
9997                                            : input_bfd->filename),
9998                                           &osym, bfd_abs_section_ptr,
9999                                           NULL))
10000             return FALSE;
10001         }
10002
10003       osym = *isym;
10004
10005       /* Adjust the section index for the output file.  */
10006       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10007                                                          isec->output_section);
10008       if (osym.st_shndx == SHN_BAD)
10009         return FALSE;
10010
10011       /* ELF symbols in relocatable files are section relative, but
10012          in executable files they are virtual addresses.  Note that
10013          this code assumes that all ELF sections have an associated
10014          BFD section with a reasonable value for output_offset; below
10015          we assume that they also have a reasonable value for
10016          output_section.  Any special sections must be set up to meet
10017          these requirements.  */
10018       osym.st_value += isec->output_offset;
10019       if (!bfd_link_relocatable (flinfo->info))
10020         {
10021           osym.st_value += isec->output_section->vma;
10022           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10023             {
10024               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10025               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10026               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10027             }
10028         }
10029
10030       indx = bfd_get_symcount (output_bfd);
10031       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10032       if (ret == 0)
10033         return FALSE;
10034       else if (ret == 1)
10035         *pindex = indx;
10036     }
10037
10038   if (bed->s->arch_size == 32)
10039     {
10040       r_type_mask = 0xff;
10041       r_sym_shift = 8;
10042       address_size = 4;
10043     }
10044   else
10045     {
10046       r_type_mask = 0xffffffff;
10047       r_sym_shift = 32;
10048       address_size = 8;
10049     }
10050
10051   /* Relocate the contents of each section.  */
10052   sym_hashes = elf_sym_hashes (input_bfd);
10053   for (o = input_bfd->sections; o != NULL; o = o->next)
10054     {
10055       bfd_byte *contents;
10056
10057       if (! o->linker_mark)
10058         {
10059           /* This section was omitted from the link.  */
10060           continue;
10061         }
10062
10063       if (bfd_link_relocatable (flinfo->info)
10064           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10065         {
10066           /* Deal with the group signature symbol.  */
10067           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10068           unsigned long symndx = sec_data->this_hdr.sh_info;
10069           asection *osec = o->output_section;
10070
10071           if (symndx >= locsymcount
10072               || (elf_bad_symtab (input_bfd)
10073                   && flinfo->sections[symndx] == NULL))
10074             {
10075               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10076               while (h->root.type == bfd_link_hash_indirect
10077                      || h->root.type == bfd_link_hash_warning)
10078                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10079               /* Arrange for symbol to be output.  */
10080               h->indx = -2;
10081               elf_section_data (osec)->this_hdr.sh_info = -2;
10082             }
10083           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10084             {
10085               /* We'll use the output section target_index.  */
10086               asection *sec = flinfo->sections[symndx]->output_section;
10087               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10088             }
10089           else
10090             {
10091               if (flinfo->indices[symndx] == -1)
10092                 {
10093                   /* Otherwise output the local symbol now.  */
10094                   Elf_Internal_Sym sym = isymbuf[symndx];
10095                   asection *sec = flinfo->sections[symndx]->output_section;
10096                   const char *name;
10097                   long indx;
10098                   int ret;
10099
10100                   name = bfd_elf_string_from_elf_section (input_bfd,
10101                                                           symtab_hdr->sh_link,
10102                                                           sym.st_name);
10103                   if (name == NULL)
10104                     return FALSE;
10105
10106                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10107                                                                     sec);
10108                   if (sym.st_shndx == SHN_BAD)
10109                     return FALSE;
10110
10111                   sym.st_value += o->output_offset;
10112
10113                   indx = bfd_get_symcount (output_bfd);
10114                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10115                                                    NULL);
10116                   if (ret == 0)
10117                     return FALSE;
10118                   else if (ret == 1)
10119                     flinfo->indices[symndx] = indx;
10120                   else
10121                     abort ();
10122                 }
10123               elf_section_data (osec)->this_hdr.sh_info
10124                 = flinfo->indices[symndx];
10125             }
10126         }
10127
10128       if ((o->flags & SEC_HAS_CONTENTS) == 0
10129           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10130         continue;
10131
10132       if ((o->flags & SEC_LINKER_CREATED) != 0)
10133         {
10134           /* Section was created by _bfd_elf_link_create_dynamic_sections
10135              or somesuch.  */
10136           continue;
10137         }
10138
10139       /* Get the contents of the section.  They have been cached by a
10140          relaxation routine.  Note that o is a section in an input
10141          file, so the contents field will not have been set by any of
10142          the routines which work on output files.  */
10143       if (elf_section_data (o)->this_hdr.contents != NULL)
10144         {
10145           contents = elf_section_data (o)->this_hdr.contents;
10146           if (bed->caches_rawsize
10147               && o->rawsize != 0
10148               && o->rawsize < o->size)
10149             {
10150               memcpy (flinfo->contents, contents, o->rawsize);
10151               contents = flinfo->contents;
10152             }
10153         }
10154       else
10155         {
10156           contents = flinfo->contents;
10157           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10158             return FALSE;
10159         }
10160
10161       if ((o->flags & SEC_RELOC) != 0)
10162         {
10163           Elf_Internal_Rela *internal_relocs;
10164           Elf_Internal_Rela *rel, *relend;
10165           int action_discarded;
10166           int ret;
10167
10168           /* Get the swapped relocs.  */
10169           internal_relocs
10170             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10171                                          flinfo->internal_relocs, FALSE);
10172           if (internal_relocs == NULL
10173               && o->reloc_count > 0)
10174             return FALSE;
10175
10176           /* We need to reverse-copy input .ctors/.dtors sections if
10177              they are placed in .init_array/.finit_array for output.  */
10178           if (o->size > address_size
10179               && ((strncmp (o->name, ".ctors", 6) == 0
10180                    && strcmp (o->output_section->name,
10181                               ".init_array") == 0)
10182                   || (strncmp (o->name, ".dtors", 6) == 0
10183                       && strcmp (o->output_section->name,
10184                                  ".fini_array") == 0))
10185               && (o->name[6] == 0 || o->name[6] == '.'))
10186             {
10187               if (o->size != o->reloc_count * address_size)
10188                 {
10189                   (*_bfd_error_handler)
10190                     (_("error: %B: size of section %A is not "
10191                        "multiple of address size"),
10192                      input_bfd, o);
10193                   bfd_set_error (bfd_error_on_input);
10194                   return FALSE;
10195                 }
10196               o->flags |= SEC_ELF_REVERSE_COPY;
10197             }
10198
10199           action_discarded = -1;
10200           if (!elf_section_ignore_discarded_relocs (o))
10201             action_discarded = (*bed->action_discarded) (o);
10202
10203           /* Run through the relocs evaluating complex reloc symbols and
10204              looking for relocs against symbols from discarded sections
10205              or section symbols from removed link-once sections.
10206              Complain about relocs against discarded sections.  Zero
10207              relocs against removed link-once sections.  */
10208
10209           rel = internal_relocs;
10210           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10211           for ( ; rel < relend; rel++)
10212             {
10213               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10214               unsigned int s_type;
10215               asection **ps, *sec;
10216               struct elf_link_hash_entry *h = NULL;
10217               const char *sym_name;
10218
10219               if (r_symndx == STN_UNDEF)
10220                 continue;
10221
10222               if (r_symndx >= locsymcount
10223                   || (elf_bad_symtab (input_bfd)
10224                       && flinfo->sections[r_symndx] == NULL))
10225                 {
10226                   h = sym_hashes[r_symndx - extsymoff];
10227
10228                   /* Badly formatted input files can contain relocs that
10229                      reference non-existant symbols.  Check here so that
10230                      we do not seg fault.  */
10231                   if (h == NULL)
10232                     {
10233                       char buffer [32];
10234
10235                       sprintf_vma (buffer, rel->r_info);
10236                       (*_bfd_error_handler)
10237                         (_("error: %B contains a reloc (0x%s) for section %A "
10238                            "that references a non-existent global symbol"),
10239                          input_bfd, o, buffer);
10240                       bfd_set_error (bfd_error_bad_value);
10241                       return FALSE;
10242                     }
10243
10244                   while (h->root.type == bfd_link_hash_indirect
10245                          || h->root.type == bfd_link_hash_warning)
10246                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10247
10248                   s_type = h->type;
10249
10250                   /* If a plugin symbol is referenced from a non-IR file,
10251                      mark the symbol as undefined.  Note that the
10252                      linker may attach linker created dynamic sections
10253                      to the plugin bfd.  Symbols defined in linker
10254                      created sections are not plugin symbols.  */
10255                   if (h->root.non_ir_ref
10256                       && (h->root.type == bfd_link_hash_defined
10257                           || h->root.type == bfd_link_hash_defweak)
10258                       && (h->root.u.def.section->flags
10259                           & SEC_LINKER_CREATED) == 0
10260                       && h->root.u.def.section->owner != NULL
10261                       && (h->root.u.def.section->owner->flags
10262                           & BFD_PLUGIN) != 0)
10263                     {
10264                       h->root.type = bfd_link_hash_undefined;
10265                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10266                     }
10267
10268                   ps = NULL;
10269                   if (h->root.type == bfd_link_hash_defined
10270                       || h->root.type == bfd_link_hash_defweak)
10271                     ps = &h->root.u.def.section;
10272
10273                   sym_name = h->root.root.string;
10274                 }
10275               else
10276                 {
10277                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10278
10279                   s_type = ELF_ST_TYPE (sym->st_info);
10280                   ps = &flinfo->sections[r_symndx];
10281                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10282                                                sym, *ps);
10283                 }
10284
10285               if ((s_type == STT_RELC || s_type == STT_SRELC)
10286                   && !bfd_link_relocatable (flinfo->info))
10287                 {
10288                   bfd_vma val;
10289                   bfd_vma dot = (rel->r_offset
10290                                  + o->output_offset + o->output_section->vma);
10291 #ifdef DEBUG
10292                   printf ("Encountered a complex symbol!");
10293                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10294                           input_bfd->filename, o->name,
10295                           (long) (rel - internal_relocs));
10296                   printf (" symbol: idx  %8.8lx, name %s\n",
10297                           r_symndx, sym_name);
10298                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10299                           (unsigned long) rel->r_info,
10300                           (unsigned long) rel->r_offset);
10301 #endif
10302                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10303                                     isymbuf, locsymcount, s_type == STT_SRELC))
10304                     return FALSE;
10305
10306                   /* Symbol evaluated OK.  Update to absolute value.  */
10307                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10308                                     r_symndx, val);
10309                   continue;
10310                 }
10311
10312               if (action_discarded != -1 && ps != NULL)
10313                 {
10314                   /* Complain if the definition comes from a
10315                      discarded section.  */
10316                   if ((sec = *ps) != NULL && discarded_section (sec))
10317                     {
10318                       BFD_ASSERT (r_symndx != STN_UNDEF);
10319                       if (action_discarded & COMPLAIN)
10320                         (*flinfo->info->callbacks->einfo)
10321                           (_("%X`%s' referenced in section `%A' of %B: "
10322                              "defined in discarded section `%A' of %B\n"),
10323                            sym_name, o, input_bfd, sec, sec->owner);
10324
10325                       /* Try to do the best we can to support buggy old
10326                          versions of gcc.  Pretend that the symbol is
10327                          really defined in the kept linkonce section.
10328                          FIXME: This is quite broken.  Modifying the
10329                          symbol here means we will be changing all later
10330                          uses of the symbol, not just in this section.  */
10331                       if (action_discarded & PRETEND)
10332                         {
10333                           asection *kept;
10334
10335                           kept = _bfd_elf_check_kept_section (sec,
10336                                                               flinfo->info);
10337                           if (kept != NULL)
10338                             {
10339                               *ps = kept;
10340                               continue;
10341                             }
10342                         }
10343                     }
10344                 }
10345             }
10346
10347           /* Relocate the section by invoking a back end routine.
10348
10349              The back end routine is responsible for adjusting the
10350              section contents as necessary, and (if using Rela relocs
10351              and generating a relocatable output file) adjusting the
10352              reloc addend as necessary.
10353
10354              The back end routine does not have to worry about setting
10355              the reloc address or the reloc symbol index.
10356
10357              The back end routine is given a pointer to the swapped in
10358              internal symbols, and can access the hash table entries
10359              for the external symbols via elf_sym_hashes (input_bfd).
10360
10361              When generating relocatable output, the back end routine
10362              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10363              output symbol is going to be a section symbol
10364              corresponding to the output section, which will require
10365              the addend to be adjusted.  */
10366
10367           ret = (*relocate_section) (output_bfd, flinfo->info,
10368                                      input_bfd, o, contents,
10369                                      internal_relocs,
10370                                      isymbuf,
10371                                      flinfo->sections);
10372           if (!ret)
10373             return FALSE;
10374
10375           if (ret == 2
10376               || bfd_link_relocatable (flinfo->info)
10377               || flinfo->info->emitrelocations)
10378             {
10379               Elf_Internal_Rela *irela;
10380               Elf_Internal_Rela *irelaend, *irelamid;
10381               bfd_vma last_offset;
10382               struct elf_link_hash_entry **rel_hash;
10383               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10384               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10385               unsigned int next_erel;
10386               bfd_boolean rela_normal;
10387               struct bfd_elf_section_data *esdi, *esdo;
10388
10389               esdi = elf_section_data (o);
10390               esdo = elf_section_data (o->output_section);
10391               rela_normal = FALSE;
10392
10393               /* Adjust the reloc addresses and symbol indices.  */
10394
10395               irela = internal_relocs;
10396               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10397               rel_hash = esdo->rel.hashes + esdo->rel.count;
10398               /* We start processing the REL relocs, if any.  When we reach
10399                  IRELAMID in the loop, we switch to the RELA relocs.  */
10400               irelamid = irela;
10401               if (esdi->rel.hdr != NULL)
10402                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10403                              * bed->s->int_rels_per_ext_rel);
10404               rel_hash_list = rel_hash;
10405               rela_hash_list = NULL;
10406               last_offset = o->output_offset;
10407               if (!bfd_link_relocatable (flinfo->info))
10408                 last_offset += o->output_section->vma;
10409               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10410                 {
10411                   unsigned long r_symndx;
10412                   asection *sec;
10413                   Elf_Internal_Sym sym;
10414
10415                   if (next_erel == bed->s->int_rels_per_ext_rel)
10416                     {
10417                       rel_hash++;
10418                       next_erel = 0;
10419                     }
10420
10421                   if (irela == irelamid)
10422                     {
10423                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10424                       rela_hash_list = rel_hash;
10425                       rela_normal = bed->rela_normal;
10426                     }
10427
10428                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10429                                                              flinfo->info, o,
10430                                                              irela->r_offset);
10431                   if (irela->r_offset >= (bfd_vma) -2)
10432                     {
10433                       /* This is a reloc for a deleted entry or somesuch.
10434                          Turn it into an R_*_NONE reloc, at the same
10435                          offset as the last reloc.  elf_eh_frame.c and
10436                          bfd_elf_discard_info rely on reloc offsets
10437                          being ordered.  */
10438                       irela->r_offset = last_offset;
10439                       irela->r_info = 0;
10440                       irela->r_addend = 0;
10441                       continue;
10442                     }
10443
10444                   irela->r_offset += o->output_offset;
10445
10446                   /* Relocs in an executable have to be virtual addresses.  */
10447                   if (!bfd_link_relocatable (flinfo->info))
10448                     irela->r_offset += o->output_section->vma;
10449
10450                   last_offset = irela->r_offset;
10451
10452                   r_symndx = irela->r_info >> r_sym_shift;
10453                   if (r_symndx == STN_UNDEF)
10454                     continue;
10455
10456                   if (r_symndx >= locsymcount
10457                       || (elf_bad_symtab (input_bfd)
10458                           && flinfo->sections[r_symndx] == NULL))
10459                     {
10460                       struct elf_link_hash_entry *rh;
10461                       unsigned long indx;
10462
10463                       /* This is a reloc against a global symbol.  We
10464                          have not yet output all the local symbols, so
10465                          we do not know the symbol index of any global
10466                          symbol.  We set the rel_hash entry for this
10467                          reloc to point to the global hash table entry
10468                          for this symbol.  The symbol index is then
10469                          set at the end of bfd_elf_final_link.  */
10470                       indx = r_symndx - extsymoff;
10471                       rh = elf_sym_hashes (input_bfd)[indx];
10472                       while (rh->root.type == bfd_link_hash_indirect
10473                              || rh->root.type == bfd_link_hash_warning)
10474                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10475
10476                       /* Setting the index to -2 tells
10477                          elf_link_output_extsym that this symbol is
10478                          used by a reloc.  */
10479                       BFD_ASSERT (rh->indx < 0);
10480                       rh->indx = -2;
10481
10482                       *rel_hash = rh;
10483
10484                       continue;
10485                     }
10486
10487                   /* This is a reloc against a local symbol.  */
10488
10489                   *rel_hash = NULL;
10490                   sym = isymbuf[r_symndx];
10491                   sec = flinfo->sections[r_symndx];
10492                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10493                     {
10494                       /* I suppose the backend ought to fill in the
10495                          section of any STT_SECTION symbol against a
10496                          processor specific section.  */
10497                       r_symndx = STN_UNDEF;
10498                       if (bfd_is_abs_section (sec))
10499                         ;
10500                       else if (sec == NULL || sec->owner == NULL)
10501                         {
10502                           bfd_set_error (bfd_error_bad_value);
10503                           return FALSE;
10504                         }
10505                       else
10506                         {
10507                           asection *osec = sec->output_section;
10508
10509                           /* If we have discarded a section, the output
10510                              section will be the absolute section.  In
10511                              case of discarded SEC_MERGE sections, use
10512                              the kept section.  relocate_section should
10513                              have already handled discarded linkonce
10514                              sections.  */
10515                           if (bfd_is_abs_section (osec)
10516                               && sec->kept_section != NULL
10517                               && sec->kept_section->output_section != NULL)
10518                             {
10519                               osec = sec->kept_section->output_section;
10520                               irela->r_addend -= osec->vma;
10521                             }
10522
10523                           if (!bfd_is_abs_section (osec))
10524                             {
10525                               r_symndx = osec->target_index;
10526                               if (r_symndx == STN_UNDEF)
10527                                 {
10528                                   irela->r_addend += osec->vma;
10529                                   osec = _bfd_nearby_section (output_bfd, osec,
10530                                                               osec->vma);
10531                                   irela->r_addend -= osec->vma;
10532                                   r_symndx = osec->target_index;
10533                                 }
10534                             }
10535                         }
10536
10537                       /* Adjust the addend according to where the
10538                          section winds up in the output section.  */
10539                       if (rela_normal)
10540                         irela->r_addend += sec->output_offset;
10541                     }
10542                   else
10543                     {
10544                       if (flinfo->indices[r_symndx] == -1)
10545                         {
10546                           unsigned long shlink;
10547                           const char *name;
10548                           asection *osec;
10549                           long indx;
10550
10551                           if (flinfo->info->strip == strip_all)
10552                             {
10553                               /* You can't do ld -r -s.  */
10554                               bfd_set_error (bfd_error_invalid_operation);
10555                               return FALSE;
10556                             }
10557
10558                           /* This symbol was skipped earlier, but
10559                              since it is needed by a reloc, we
10560                              must output it now.  */
10561                           shlink = symtab_hdr->sh_link;
10562                           name = (bfd_elf_string_from_elf_section
10563                                   (input_bfd, shlink, sym.st_name));
10564                           if (name == NULL)
10565                             return FALSE;
10566
10567                           osec = sec->output_section;
10568                           sym.st_shndx =
10569                             _bfd_elf_section_from_bfd_section (output_bfd,
10570                                                                osec);
10571                           if (sym.st_shndx == SHN_BAD)
10572                             return FALSE;
10573
10574                           sym.st_value += sec->output_offset;
10575                           if (!bfd_link_relocatable (flinfo->info))
10576                             {
10577                               sym.st_value += osec->vma;
10578                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10579                                 {
10580                                   /* STT_TLS symbols are relative to PT_TLS
10581                                      segment base.  */
10582                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10583                                               ->tls_sec != NULL);
10584                                   sym.st_value -= (elf_hash_table (flinfo->info)
10585                                                    ->tls_sec->vma);
10586                                 }
10587                             }
10588
10589                           indx = bfd_get_symcount (output_bfd);
10590                           ret = elf_link_output_symstrtab (flinfo, name,
10591                                                            &sym, sec,
10592                                                            NULL);
10593                           if (ret == 0)
10594                             return FALSE;
10595                           else if (ret == 1)
10596                             flinfo->indices[r_symndx] = indx;
10597                           else
10598                             abort ();
10599                         }
10600
10601                       r_symndx = flinfo->indices[r_symndx];
10602                     }
10603
10604                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10605                                    | (irela->r_info & r_type_mask));
10606                 }
10607
10608               /* Swap out the relocs.  */
10609               input_rel_hdr = esdi->rel.hdr;
10610               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10611                 {
10612                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10613                                                      input_rel_hdr,
10614                                                      internal_relocs,
10615                                                      rel_hash_list))
10616                     return FALSE;
10617                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10618                                       * bed->s->int_rels_per_ext_rel);
10619                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10620                 }
10621
10622               input_rela_hdr = esdi->rela.hdr;
10623               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10624                 {
10625                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10626                                                      input_rela_hdr,
10627                                                      internal_relocs,
10628                                                      rela_hash_list))
10629                     return FALSE;
10630                 }
10631             }
10632         }
10633
10634       /* Write out the modified section contents.  */
10635       if (bed->elf_backend_write_section
10636           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10637                                                 contents))
10638         {
10639           /* Section written out.  */
10640         }
10641       else switch (o->sec_info_type)
10642         {
10643         case SEC_INFO_TYPE_STABS:
10644           if (! (_bfd_write_section_stabs
10645                  (output_bfd,
10646                   &elf_hash_table (flinfo->info)->stab_info,
10647                   o, &elf_section_data (o)->sec_info, contents)))
10648             return FALSE;
10649           break;
10650         case SEC_INFO_TYPE_MERGE:
10651           if (! _bfd_write_merged_section (output_bfd, o,
10652                                            elf_section_data (o)->sec_info))
10653             return FALSE;
10654           break;
10655         case SEC_INFO_TYPE_EH_FRAME:
10656           {
10657             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10658                                                    o, contents))
10659               return FALSE;
10660           }
10661           break;
10662         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10663           {
10664             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10665                                                          flinfo->info,
10666                                                          o, contents))
10667               return FALSE;
10668           }
10669           break;
10670         default:
10671           {
10672             if (! (o->flags & SEC_EXCLUDE))
10673               {
10674                 file_ptr offset = (file_ptr) o->output_offset;
10675                 bfd_size_type todo = o->size;
10676
10677                 offset *= bfd_octets_per_byte (output_bfd);
10678
10679                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10680                   {
10681                     /* Reverse-copy input section to output.  */
10682                     do
10683                       {
10684                         todo -= address_size;
10685                         if (! bfd_set_section_contents (output_bfd,
10686                                                         o->output_section,
10687                                                         contents + todo,
10688                                                         offset,
10689                                                         address_size))
10690                           return FALSE;
10691                         if (todo == 0)
10692                           break;
10693                         offset += address_size;
10694                       }
10695                     while (1);
10696                   }
10697                 else if (! bfd_set_section_contents (output_bfd,
10698                                                      o->output_section,
10699                                                      contents,
10700                                                      offset, todo))
10701                   return FALSE;
10702               }
10703           }
10704           break;
10705         }
10706     }
10707
10708   return TRUE;
10709 }
10710
10711 /* Generate a reloc when linking an ELF file.  This is a reloc
10712    requested by the linker, and does not come from any input file.  This
10713    is used to build constructor and destructor tables when linking
10714    with -Ur.  */
10715
10716 static bfd_boolean
10717 elf_reloc_link_order (bfd *output_bfd,
10718                       struct bfd_link_info *info,
10719                       asection *output_section,
10720                       struct bfd_link_order *link_order)
10721 {
10722   reloc_howto_type *howto;
10723   long indx;
10724   bfd_vma offset;
10725   bfd_vma addend;
10726   struct bfd_elf_section_reloc_data *reldata;
10727   struct elf_link_hash_entry **rel_hash_ptr;
10728   Elf_Internal_Shdr *rel_hdr;
10729   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10730   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10731   bfd_byte *erel;
10732   unsigned int i;
10733   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10734
10735   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10736   if (howto == NULL)
10737     {
10738       bfd_set_error (bfd_error_bad_value);
10739       return FALSE;
10740     }
10741
10742   addend = link_order->u.reloc.p->addend;
10743
10744   if (esdo->rel.hdr)
10745     reldata = &esdo->rel;
10746   else if (esdo->rela.hdr)
10747     reldata = &esdo->rela;
10748   else
10749     {
10750       reldata = NULL;
10751       BFD_ASSERT (0);
10752     }
10753
10754   /* Figure out the symbol index.  */
10755   rel_hash_ptr = reldata->hashes + reldata->count;
10756   if (link_order->type == bfd_section_reloc_link_order)
10757     {
10758       indx = link_order->u.reloc.p->u.section->target_index;
10759       BFD_ASSERT (indx != 0);
10760       *rel_hash_ptr = NULL;
10761     }
10762   else
10763     {
10764       struct elf_link_hash_entry *h;
10765
10766       /* Treat a reloc against a defined symbol as though it were
10767          actually against the section.  */
10768       h = ((struct elf_link_hash_entry *)
10769            bfd_wrapped_link_hash_lookup (output_bfd, info,
10770                                          link_order->u.reloc.p->u.name,
10771                                          FALSE, FALSE, TRUE));
10772       if (h != NULL
10773           && (h->root.type == bfd_link_hash_defined
10774               || h->root.type == bfd_link_hash_defweak))
10775         {
10776           asection *section;
10777
10778           section = h->root.u.def.section;
10779           indx = section->output_section->target_index;
10780           *rel_hash_ptr = NULL;
10781           /* It seems that we ought to add the symbol value to the
10782              addend here, but in practice it has already been added
10783              because it was passed to constructor_callback.  */
10784           addend += section->output_section->vma + section->output_offset;
10785         }
10786       else if (h != NULL)
10787         {
10788           /* Setting the index to -2 tells elf_link_output_extsym that
10789              this symbol is used by a reloc.  */
10790           h->indx = -2;
10791           *rel_hash_ptr = h;
10792           indx = 0;
10793         }
10794       else
10795         {
10796           (*info->callbacks->unattached_reloc)
10797             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
10798           indx = 0;
10799         }
10800     }
10801
10802   /* If this is an inplace reloc, we must write the addend into the
10803      object file.  */
10804   if (howto->partial_inplace && addend != 0)
10805     {
10806       bfd_size_type size;
10807       bfd_reloc_status_type rstat;
10808       bfd_byte *buf;
10809       bfd_boolean ok;
10810       const char *sym_name;
10811
10812       size = (bfd_size_type) bfd_get_reloc_size (howto);
10813       buf = (bfd_byte *) bfd_zmalloc (size);
10814       if (buf == NULL && size != 0)
10815         return FALSE;
10816       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10817       switch (rstat)
10818         {
10819         case bfd_reloc_ok:
10820           break;
10821
10822         default:
10823         case bfd_reloc_outofrange:
10824           abort ();
10825
10826         case bfd_reloc_overflow:
10827           if (link_order->type == bfd_section_reloc_link_order)
10828             sym_name = bfd_section_name (output_bfd,
10829                                          link_order->u.reloc.p->u.section);
10830           else
10831             sym_name = link_order->u.reloc.p->u.name;
10832           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
10833                                               howto->name, addend, NULL, NULL,
10834                                               (bfd_vma) 0);
10835           break;
10836         }
10837
10838       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10839                                      link_order->offset
10840                                      * bfd_octets_per_byte (output_bfd),
10841                                      size);
10842       free (buf);
10843       if (! ok)
10844         return FALSE;
10845     }
10846
10847   /* The address of a reloc is relative to the section in a
10848      relocatable file, and is a virtual address in an executable
10849      file.  */
10850   offset = link_order->offset;
10851   if (! bfd_link_relocatable (info))
10852     offset += output_section->vma;
10853
10854   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10855     {
10856       irel[i].r_offset = offset;
10857       irel[i].r_info = 0;
10858       irel[i].r_addend = 0;
10859     }
10860   if (bed->s->arch_size == 32)
10861     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10862   else
10863     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10864
10865   rel_hdr = reldata->hdr;
10866   erel = rel_hdr->contents;
10867   if (rel_hdr->sh_type == SHT_REL)
10868     {
10869       erel += reldata->count * bed->s->sizeof_rel;
10870       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10871     }
10872   else
10873     {
10874       irel[0].r_addend = addend;
10875       erel += reldata->count * bed->s->sizeof_rela;
10876       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10877     }
10878
10879   ++reldata->count;
10880
10881   return TRUE;
10882 }
10883
10884
10885 /* Get the output vma of the section pointed to by the sh_link field.  */
10886
10887 static bfd_vma
10888 elf_get_linked_section_vma (struct bfd_link_order *p)
10889 {
10890   Elf_Internal_Shdr **elf_shdrp;
10891   asection *s;
10892   int elfsec;
10893
10894   s = p->u.indirect.section;
10895   elf_shdrp = elf_elfsections (s->owner);
10896   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10897   elfsec = elf_shdrp[elfsec]->sh_link;
10898   /* PR 290:
10899      The Intel C compiler generates SHT_IA_64_UNWIND with
10900      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10901      sh_info fields.  Hence we could get the situation
10902      where elfsec is 0.  */
10903   if (elfsec == 0)
10904     {
10905       const struct elf_backend_data *bed
10906         = get_elf_backend_data (s->owner);
10907       if (bed->link_order_error_handler)
10908         bed->link_order_error_handler
10909           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10910       return 0;
10911     }
10912   else
10913     {
10914       s = elf_shdrp[elfsec]->bfd_section;
10915       return s->output_section->vma + s->output_offset;
10916     }
10917 }
10918
10919
10920 /* Compare two sections based on the locations of the sections they are
10921    linked to.  Used by elf_fixup_link_order.  */
10922
10923 static int
10924 compare_link_order (const void * a, const void * b)
10925 {
10926   bfd_vma apos;
10927   bfd_vma bpos;
10928
10929   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10930   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10931   if (apos < bpos)
10932     return -1;
10933   return apos > bpos;
10934 }
10935
10936
10937 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10938    order as their linked sections.  Returns false if this could not be done
10939    because an output section includes both ordered and unordered
10940    sections.  Ideally we'd do this in the linker proper.  */
10941
10942 static bfd_boolean
10943 elf_fixup_link_order (bfd *abfd, asection *o)
10944 {
10945   int seen_linkorder;
10946   int seen_other;
10947   int n;
10948   struct bfd_link_order *p;
10949   bfd *sub;
10950   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10951   unsigned elfsec;
10952   struct bfd_link_order **sections;
10953   asection *s, *other_sec, *linkorder_sec;
10954   bfd_vma offset;
10955
10956   other_sec = NULL;
10957   linkorder_sec = NULL;
10958   seen_other = 0;
10959   seen_linkorder = 0;
10960   for (p = o->map_head.link_order; p != NULL; p = p->next)
10961     {
10962       if (p->type == bfd_indirect_link_order)
10963         {
10964           s = p->u.indirect.section;
10965           sub = s->owner;
10966           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10967               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10968               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10969               && elfsec < elf_numsections (sub)
10970               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10971               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10972             {
10973               seen_linkorder++;
10974               linkorder_sec = s;
10975             }
10976           else
10977             {
10978               seen_other++;
10979               other_sec = s;
10980             }
10981         }
10982       else
10983         seen_other++;
10984
10985       if (seen_other && seen_linkorder)
10986         {
10987           if (other_sec && linkorder_sec)
10988             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10989                                    o, linkorder_sec,
10990                                    linkorder_sec->owner, other_sec,
10991                                    other_sec->owner);
10992           else
10993             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10994                                    o);
10995           bfd_set_error (bfd_error_bad_value);
10996           return FALSE;
10997         }
10998     }
10999
11000   if (!seen_linkorder)
11001     return TRUE;
11002
11003   sections = (struct bfd_link_order **)
11004     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11005   if (sections == NULL)
11006     return FALSE;
11007   seen_linkorder = 0;
11008
11009   for (p = o->map_head.link_order; p != NULL; p = p->next)
11010     {
11011       sections[seen_linkorder++] = p;
11012     }
11013   /* Sort the input sections in the order of their linked section.  */
11014   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11015          compare_link_order);
11016
11017   /* Change the offsets of the sections.  */
11018   offset = 0;
11019   for (n = 0; n < seen_linkorder; n++)
11020     {
11021       s = sections[n]->u.indirect.section;
11022       offset &= ~(bfd_vma) 0 << s->alignment_power;
11023       s->output_offset = offset / bfd_octets_per_byte (abfd);
11024       sections[n]->offset = offset;
11025       offset += sections[n]->size;
11026     }
11027
11028   free (sections);
11029   return TRUE;
11030 }
11031
11032 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11033    Returns TRUE upon success, FALSE otherwise.  */
11034
11035 static bfd_boolean
11036 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11037 {
11038   bfd_boolean ret = FALSE;
11039   bfd *implib_bfd;
11040   const struct elf_backend_data *bed;
11041   flagword flags;
11042   enum bfd_architecture arch;
11043   unsigned int mach;
11044   asymbol **sympp = NULL;
11045   long symsize;
11046   long symcount;
11047   long src_count;
11048   elf_symbol_type *osymbuf;
11049
11050   implib_bfd = info->out_implib_bfd;
11051   bed = get_elf_backend_data (abfd);
11052
11053   if (!bfd_set_format (implib_bfd, bfd_object))
11054     return FALSE;
11055
11056   flags = bfd_get_file_flags (abfd);
11057   flags &= ~HAS_RELOC;
11058   if (!bfd_set_start_address (implib_bfd, 0)
11059       || !bfd_set_file_flags (implib_bfd, flags))
11060     return FALSE;
11061
11062   /* Copy architecture of output file to import library file.  */
11063   arch = bfd_get_arch (abfd);
11064   mach = bfd_get_mach (abfd);
11065   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11066       && (abfd->target_defaulted
11067           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11068     return FALSE;
11069
11070   /* Get symbol table size.  */
11071   symsize = bfd_get_symtab_upper_bound (abfd);
11072   if (symsize < 0)
11073     return FALSE;
11074
11075   /* Read in the symbol table.  */
11076   sympp = (asymbol **) xmalloc (symsize);
11077   symcount = bfd_canonicalize_symtab (abfd, sympp);
11078   if (symcount < 0)
11079     goto free_sym_buf;
11080
11081   /* Allow the BFD backend to copy any private header data it
11082      understands from the output BFD to the import library BFD.  */
11083   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11084     goto free_sym_buf;
11085
11086   /* Filter symbols to appear in the import library.  */
11087   if (bed->elf_backend_filter_implib_symbols)
11088     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11089                                                        symcount);
11090   else
11091     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11092   if (symcount == 0)
11093     {
11094       bfd_set_error (bfd_error_no_symbols);
11095       (*_bfd_error_handler) (_("%B: no symbol found for import library"),
11096                              implib_bfd);
11097       goto free_sym_buf;
11098     }
11099
11100
11101   /* Make symbols absolute.  */
11102   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11103                                             sizeof (*osymbuf));
11104   for (src_count = 0; src_count < symcount; src_count++)
11105     {
11106       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11107               sizeof (*osymbuf));
11108       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11109       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11110       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11111       osymbuf[src_count].internal_elf_sym.st_value =
11112         osymbuf[src_count].symbol.value;
11113       sympp[src_count] = &osymbuf[src_count].symbol;
11114     }
11115
11116   bfd_set_symtab (implib_bfd, sympp, symcount);
11117
11118   /* Allow the BFD backend to copy any private data it understands
11119      from the output BFD to the import library BFD.  This is done last
11120      to permit the routine to look at the filtered symbol table.  */
11121   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11122     goto free_sym_buf;
11123
11124   if (!bfd_close (implib_bfd))
11125     goto free_sym_buf;
11126
11127   ret = TRUE;
11128
11129 free_sym_buf:
11130   free (sympp);
11131   return ret;
11132 }
11133
11134 static void
11135 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11136 {
11137   asection *o;
11138
11139   if (flinfo->symstrtab != NULL)
11140     _bfd_elf_strtab_free (flinfo->symstrtab);
11141   if (flinfo->contents != NULL)
11142     free (flinfo->contents);
11143   if (flinfo->external_relocs != NULL)
11144     free (flinfo->external_relocs);
11145   if (flinfo->internal_relocs != NULL)
11146     free (flinfo->internal_relocs);
11147   if (flinfo->external_syms != NULL)
11148     free (flinfo->external_syms);
11149   if (flinfo->locsym_shndx != NULL)
11150     free (flinfo->locsym_shndx);
11151   if (flinfo->internal_syms != NULL)
11152     free (flinfo->internal_syms);
11153   if (flinfo->indices != NULL)
11154     free (flinfo->indices);
11155   if (flinfo->sections != NULL)
11156     free (flinfo->sections);
11157   if (flinfo->symshndxbuf != NULL)
11158     free (flinfo->symshndxbuf);
11159   for (o = obfd->sections; o != NULL; o = o->next)
11160     {
11161       struct bfd_elf_section_data *esdo = elf_section_data (o);
11162       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11163         free (esdo->rel.hashes);
11164       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11165         free (esdo->rela.hashes);
11166     }
11167 }
11168
11169 /* Do the final step of an ELF link.  */
11170
11171 bfd_boolean
11172 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11173 {
11174   bfd_boolean dynamic;
11175   bfd_boolean emit_relocs;
11176   bfd *dynobj;
11177   struct elf_final_link_info flinfo;
11178   asection *o;
11179   struct bfd_link_order *p;
11180   bfd *sub;
11181   bfd_size_type max_contents_size;
11182   bfd_size_type max_external_reloc_size;
11183   bfd_size_type max_internal_reloc_count;
11184   bfd_size_type max_sym_count;
11185   bfd_size_type max_sym_shndx_count;
11186   Elf_Internal_Sym elfsym;
11187   unsigned int i;
11188   Elf_Internal_Shdr *symtab_hdr;
11189   Elf_Internal_Shdr *symtab_shndx_hdr;
11190   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11191   struct elf_outext_info eoinfo;
11192   bfd_boolean merged;
11193   size_t relativecount = 0;
11194   asection *reldyn = 0;
11195   bfd_size_type amt;
11196   asection *attr_section = NULL;
11197   bfd_vma attr_size = 0;
11198   const char *std_attrs_section;
11199
11200   if (! is_elf_hash_table (info->hash))
11201     return FALSE;
11202
11203   if (bfd_link_pic (info))
11204     abfd->flags |= DYNAMIC;
11205
11206   dynamic = elf_hash_table (info)->dynamic_sections_created;
11207   dynobj = elf_hash_table (info)->dynobj;
11208
11209   emit_relocs = (bfd_link_relocatable (info)
11210                  || info->emitrelocations);
11211
11212   flinfo.info = info;
11213   flinfo.output_bfd = abfd;
11214   flinfo.symstrtab = _bfd_elf_strtab_init ();
11215   if (flinfo.symstrtab == NULL)
11216     return FALSE;
11217
11218   if (! dynamic)
11219     {
11220       flinfo.hash_sec = NULL;
11221       flinfo.symver_sec = NULL;
11222     }
11223   else
11224     {
11225       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11226       /* Note that dynsym_sec can be NULL (on VMS).  */
11227       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11228       /* Note that it is OK if symver_sec is NULL.  */
11229     }
11230
11231   flinfo.contents = NULL;
11232   flinfo.external_relocs = NULL;
11233   flinfo.internal_relocs = NULL;
11234   flinfo.external_syms = NULL;
11235   flinfo.locsym_shndx = NULL;
11236   flinfo.internal_syms = NULL;
11237   flinfo.indices = NULL;
11238   flinfo.sections = NULL;
11239   flinfo.symshndxbuf = NULL;
11240   flinfo.filesym_count = 0;
11241
11242   /* The object attributes have been merged.  Remove the input
11243      sections from the link, and set the contents of the output
11244      secton.  */
11245   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11246   for (o = abfd->sections; o != NULL; o = o->next)
11247     {
11248       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11249           || strcmp (o->name, ".gnu.attributes") == 0)
11250         {
11251           for (p = o->map_head.link_order; p != NULL; p = p->next)
11252             {
11253               asection *input_section;
11254
11255               if (p->type != bfd_indirect_link_order)
11256                 continue;
11257               input_section = p->u.indirect.section;
11258               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11259                  elf_link_input_bfd ignores this section.  */
11260               input_section->flags &= ~SEC_HAS_CONTENTS;
11261             }
11262
11263           attr_size = bfd_elf_obj_attr_size (abfd);
11264           if (attr_size)
11265             {
11266               bfd_set_section_size (abfd, o, attr_size);
11267               attr_section = o;
11268               /* Skip this section later on.  */
11269               o->map_head.link_order = NULL;
11270             }
11271           else
11272             o->flags |= SEC_EXCLUDE;
11273         }
11274     }
11275
11276   /* Count up the number of relocations we will output for each output
11277      section, so that we know the sizes of the reloc sections.  We
11278      also figure out some maximum sizes.  */
11279   max_contents_size = 0;
11280   max_external_reloc_size = 0;
11281   max_internal_reloc_count = 0;
11282   max_sym_count = 0;
11283   max_sym_shndx_count = 0;
11284   merged = FALSE;
11285   for (o = abfd->sections; o != NULL; o = o->next)
11286     {
11287       struct bfd_elf_section_data *esdo = elf_section_data (o);
11288       o->reloc_count = 0;
11289
11290       for (p = o->map_head.link_order; p != NULL; p = p->next)
11291         {
11292           unsigned int reloc_count = 0;
11293           unsigned int additional_reloc_count = 0;
11294           struct bfd_elf_section_data *esdi = NULL;
11295
11296           if (p->type == bfd_section_reloc_link_order
11297               || p->type == bfd_symbol_reloc_link_order)
11298             reloc_count = 1;
11299           else if (p->type == bfd_indirect_link_order)
11300             {
11301               asection *sec;
11302
11303               sec = p->u.indirect.section;
11304               esdi = elf_section_data (sec);
11305
11306               /* Mark all sections which are to be included in the
11307                  link.  This will normally be every section.  We need
11308                  to do this so that we can identify any sections which
11309                  the linker has decided to not include.  */
11310               sec->linker_mark = TRUE;
11311
11312               if (sec->flags & SEC_MERGE)
11313                 merged = TRUE;
11314
11315               if (esdo->this_hdr.sh_type == SHT_REL
11316                   || esdo->this_hdr.sh_type == SHT_RELA)
11317                 /* Some backends use reloc_count in relocation sections
11318                    to count particular types of relocs.  Of course,
11319                    reloc sections themselves can't have relocations.  */
11320                 reloc_count = 0;
11321               else if (emit_relocs)
11322                 {
11323                   reloc_count = sec->reloc_count;
11324                   if (bed->elf_backend_count_additional_relocs)
11325                     {
11326                       int c;
11327                       c = (*bed->elf_backend_count_additional_relocs) (sec);
11328                       additional_reloc_count += c;
11329                     }
11330                 }
11331               else if (bed->elf_backend_count_relocs)
11332                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11333
11334               if (sec->rawsize > max_contents_size)
11335                 max_contents_size = sec->rawsize;
11336               if (sec->size > max_contents_size)
11337                 max_contents_size = sec->size;
11338
11339               /* We are interested in just local symbols, not all
11340                  symbols.  */
11341               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11342                   && (sec->owner->flags & DYNAMIC) == 0)
11343                 {
11344                   size_t sym_count;
11345
11346                   if (elf_bad_symtab (sec->owner))
11347                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11348                                  / bed->s->sizeof_sym);
11349                   else
11350                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11351
11352                   if (sym_count > max_sym_count)
11353                     max_sym_count = sym_count;
11354
11355                   if (sym_count > max_sym_shndx_count
11356                       && elf_symtab_shndx_list (sec->owner) != NULL)
11357                     max_sym_shndx_count = sym_count;
11358
11359                   if ((sec->flags & SEC_RELOC) != 0)
11360                     {
11361                       size_t ext_size = 0;
11362
11363                       if (esdi->rel.hdr != NULL)
11364                         ext_size = esdi->rel.hdr->sh_size;
11365                       if (esdi->rela.hdr != NULL)
11366                         ext_size += esdi->rela.hdr->sh_size;
11367
11368                       if (ext_size > max_external_reloc_size)
11369                         max_external_reloc_size = ext_size;
11370                       if (sec->reloc_count > max_internal_reloc_count)
11371                         max_internal_reloc_count = sec->reloc_count;
11372                     }
11373                 }
11374             }
11375
11376           if (reloc_count == 0)
11377             continue;
11378
11379           reloc_count += additional_reloc_count;
11380           o->reloc_count += reloc_count;
11381
11382           if (p->type == bfd_indirect_link_order && emit_relocs)
11383             {
11384               if (esdi->rel.hdr)
11385                 {
11386                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11387                   esdo->rel.count += additional_reloc_count;
11388                 }
11389               if (esdi->rela.hdr)
11390                 {
11391                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11392                   esdo->rela.count += additional_reloc_count;
11393                 }
11394             }
11395           else
11396             {
11397               if (o->use_rela_p)
11398                 esdo->rela.count += reloc_count;
11399               else
11400                 esdo->rel.count += reloc_count;
11401             }
11402         }
11403
11404       if (o->reloc_count > 0)
11405         o->flags |= SEC_RELOC;
11406       else
11407         {
11408           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11409              set it (this is probably a bug) and if it is set
11410              assign_section_numbers will create a reloc section.  */
11411           o->flags &=~ SEC_RELOC;
11412         }
11413
11414       /* If the SEC_ALLOC flag is not set, force the section VMA to
11415          zero.  This is done in elf_fake_sections as well, but forcing
11416          the VMA to 0 here will ensure that relocs against these
11417          sections are handled correctly.  */
11418       if ((o->flags & SEC_ALLOC) == 0
11419           && ! o->user_set_vma)
11420         o->vma = 0;
11421     }
11422
11423   if (! bfd_link_relocatable (info) && merged)
11424     elf_link_hash_traverse (elf_hash_table (info),
11425                             _bfd_elf_link_sec_merge_syms, abfd);
11426
11427   /* Figure out the file positions for everything but the symbol table
11428      and the relocs.  We set symcount to force assign_section_numbers
11429      to create a symbol table.  */
11430   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11431   BFD_ASSERT (! abfd->output_has_begun);
11432   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11433     goto error_return;
11434
11435   /* Set sizes, and assign file positions for reloc sections.  */
11436   for (o = abfd->sections; o != NULL; o = o->next)
11437     {
11438       struct bfd_elf_section_data *esdo = elf_section_data (o);
11439       if ((o->flags & SEC_RELOC) != 0)
11440         {
11441           if (esdo->rel.hdr
11442               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11443             goto error_return;
11444
11445           if (esdo->rela.hdr
11446               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11447             goto error_return;
11448         }
11449
11450       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11451          to count upwards while actually outputting the relocations.  */
11452       esdo->rel.count = 0;
11453       esdo->rela.count = 0;
11454
11455       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11456         {
11457           /* Cache the section contents so that they can be compressed
11458              later.  Use bfd_malloc since it will be freed by
11459              bfd_compress_section_contents.  */
11460           unsigned char *contents = esdo->this_hdr.contents;
11461           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11462             abort ();
11463           contents
11464             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11465           if (contents == NULL)
11466             goto error_return;
11467           esdo->this_hdr.contents = contents;
11468         }
11469     }
11470
11471   /* We have now assigned file positions for all the sections except
11472      .symtab, .strtab, and non-loaded reloc sections.  We start the
11473      .symtab section at the current file position, and write directly
11474      to it.  We build the .strtab section in memory.  */
11475   bfd_get_symcount (abfd) = 0;
11476   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11477   /* sh_name is set in prep_headers.  */
11478   symtab_hdr->sh_type = SHT_SYMTAB;
11479   /* sh_flags, sh_addr and sh_size all start off zero.  */
11480   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11481   /* sh_link is set in assign_section_numbers.  */
11482   /* sh_info is set below.  */
11483   /* sh_offset is set just below.  */
11484   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11485
11486   if (max_sym_count < 20)
11487     max_sym_count = 20;
11488   elf_hash_table (info)->strtabsize = max_sym_count;
11489   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11490   elf_hash_table (info)->strtab
11491     = (struct elf_sym_strtab *) bfd_malloc (amt);
11492   if (elf_hash_table (info)->strtab == NULL)
11493     goto error_return;
11494   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11495   flinfo.symshndxbuf
11496     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11497        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11498
11499   if (info->strip != strip_all || emit_relocs)
11500     {
11501       file_ptr off = elf_next_file_pos (abfd);
11502
11503       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11504
11505       /* Note that at this point elf_next_file_pos (abfd) is
11506          incorrect.  We do not yet know the size of the .symtab section.
11507          We correct next_file_pos below, after we do know the size.  */
11508
11509       /* Start writing out the symbol table.  The first symbol is always a
11510          dummy symbol.  */
11511       elfsym.st_value = 0;
11512       elfsym.st_size = 0;
11513       elfsym.st_info = 0;
11514       elfsym.st_other = 0;
11515       elfsym.st_shndx = SHN_UNDEF;
11516       elfsym.st_target_internal = 0;
11517       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11518                                      bfd_und_section_ptr, NULL) != 1)
11519         goto error_return;
11520
11521       /* Output a symbol for each section.  We output these even if we are
11522          discarding local symbols, since they are used for relocs.  These
11523          symbols have no names.  We store the index of each one in the
11524          index field of the section, so that we can find it again when
11525          outputting relocs.  */
11526
11527       elfsym.st_size = 0;
11528       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11529       elfsym.st_other = 0;
11530       elfsym.st_value = 0;
11531       elfsym.st_target_internal = 0;
11532       for (i = 1; i < elf_numsections (abfd); i++)
11533         {
11534           o = bfd_section_from_elf_index (abfd, i);
11535           if (o != NULL)
11536             {
11537               o->target_index = bfd_get_symcount (abfd);
11538               elfsym.st_shndx = i;
11539               if (!bfd_link_relocatable (info))
11540                 elfsym.st_value = o->vma;
11541               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11542                                              NULL) != 1)
11543                 goto error_return;
11544             }
11545         }
11546     }
11547
11548   /* Allocate some memory to hold information read in from the input
11549      files.  */
11550   if (max_contents_size != 0)
11551     {
11552       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11553       if (flinfo.contents == NULL)
11554         goto error_return;
11555     }
11556
11557   if (max_external_reloc_size != 0)
11558     {
11559       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11560       if (flinfo.external_relocs == NULL)
11561         goto error_return;
11562     }
11563
11564   if (max_internal_reloc_count != 0)
11565     {
11566       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11567       amt *= sizeof (Elf_Internal_Rela);
11568       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11569       if (flinfo.internal_relocs == NULL)
11570         goto error_return;
11571     }
11572
11573   if (max_sym_count != 0)
11574     {
11575       amt = max_sym_count * bed->s->sizeof_sym;
11576       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11577       if (flinfo.external_syms == NULL)
11578         goto error_return;
11579
11580       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11581       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11582       if (flinfo.internal_syms == NULL)
11583         goto error_return;
11584
11585       amt = max_sym_count * sizeof (long);
11586       flinfo.indices = (long int *) bfd_malloc (amt);
11587       if (flinfo.indices == NULL)
11588         goto error_return;
11589
11590       amt = max_sym_count * sizeof (asection *);
11591       flinfo.sections = (asection **) bfd_malloc (amt);
11592       if (flinfo.sections == NULL)
11593         goto error_return;
11594     }
11595
11596   if (max_sym_shndx_count != 0)
11597     {
11598       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11599       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11600       if (flinfo.locsym_shndx == NULL)
11601         goto error_return;
11602     }
11603
11604   if (elf_hash_table (info)->tls_sec)
11605     {
11606       bfd_vma base, end = 0;
11607       asection *sec;
11608
11609       for (sec = elf_hash_table (info)->tls_sec;
11610            sec && (sec->flags & SEC_THREAD_LOCAL);
11611            sec = sec->next)
11612         {
11613           bfd_size_type size = sec->size;
11614
11615           if (size == 0
11616               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11617             {
11618               struct bfd_link_order *ord = sec->map_tail.link_order;
11619
11620               if (ord != NULL)
11621                 size = ord->offset + ord->size;
11622             }
11623           end = sec->vma + size;
11624         }
11625       base = elf_hash_table (info)->tls_sec->vma;
11626       /* Only align end of TLS section if static TLS doesn't have special
11627          alignment requirements.  */
11628       if (bed->static_tls_alignment == 1)
11629         end = align_power (end,
11630                            elf_hash_table (info)->tls_sec->alignment_power);
11631       elf_hash_table (info)->tls_size = end - base;
11632     }
11633
11634   /* Reorder SHF_LINK_ORDER sections.  */
11635   for (o = abfd->sections; o != NULL; o = o->next)
11636     {
11637       if (!elf_fixup_link_order (abfd, o))
11638         return FALSE;
11639     }
11640
11641   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11642     return FALSE;
11643
11644   /* Since ELF permits relocations to be against local symbols, we
11645      must have the local symbols available when we do the relocations.
11646      Since we would rather only read the local symbols once, and we
11647      would rather not keep them in memory, we handle all the
11648      relocations for a single input file at the same time.
11649
11650      Unfortunately, there is no way to know the total number of local
11651      symbols until we have seen all of them, and the local symbol
11652      indices precede the global symbol indices.  This means that when
11653      we are generating relocatable output, and we see a reloc against
11654      a global symbol, we can not know the symbol index until we have
11655      finished examining all the local symbols to see which ones we are
11656      going to output.  To deal with this, we keep the relocations in
11657      memory, and don't output them until the end of the link.  This is
11658      an unfortunate waste of memory, but I don't see a good way around
11659      it.  Fortunately, it only happens when performing a relocatable
11660      link, which is not the common case.  FIXME: If keep_memory is set
11661      we could write the relocs out and then read them again; I don't
11662      know how bad the memory loss will be.  */
11663
11664   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11665     sub->output_has_begun = FALSE;
11666   for (o = abfd->sections; o != NULL; o = o->next)
11667     {
11668       for (p = o->map_head.link_order; p != NULL; p = p->next)
11669         {
11670           if (p->type == bfd_indirect_link_order
11671               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11672                   == bfd_target_elf_flavour)
11673               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11674             {
11675               if (! sub->output_has_begun)
11676                 {
11677                   if (! elf_link_input_bfd (&flinfo, sub))
11678                     goto error_return;
11679                   sub->output_has_begun = TRUE;
11680                 }
11681             }
11682           else if (p->type == bfd_section_reloc_link_order
11683                    || p->type == bfd_symbol_reloc_link_order)
11684             {
11685               if (! elf_reloc_link_order (abfd, info, o, p))
11686                 goto error_return;
11687             }
11688           else
11689             {
11690               if (! _bfd_default_link_order (abfd, info, o, p))
11691                 {
11692                   if (p->type == bfd_indirect_link_order
11693                       && (bfd_get_flavour (sub)
11694                           == bfd_target_elf_flavour)
11695                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11696                           != bed->s->elfclass))
11697                     {
11698                       const char *iclass, *oclass;
11699
11700                       switch (bed->s->elfclass)
11701                         {
11702                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11703                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11704                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11705                         default: abort ();
11706                         }
11707
11708                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11709                         {
11710                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11711                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11712                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11713                         default: abort ();
11714                         }
11715
11716                       bfd_set_error (bfd_error_wrong_format);
11717                       (*_bfd_error_handler)
11718                         (_("%B: file class %s incompatible with %s"),
11719                          sub, iclass, oclass);
11720                     }
11721
11722                   goto error_return;
11723                 }
11724             }
11725         }
11726     }
11727
11728   /* Free symbol buffer if needed.  */
11729   if (!info->reduce_memory_overheads)
11730     {
11731       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11732         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11733             && elf_tdata (sub)->symbuf)
11734           {
11735             free (elf_tdata (sub)->symbuf);
11736             elf_tdata (sub)->symbuf = NULL;
11737           }
11738     }
11739
11740   /* Output any global symbols that got converted to local in a
11741      version script or due to symbol visibility.  We do this in a
11742      separate step since ELF requires all local symbols to appear
11743      prior to any global symbols.  FIXME: We should only do this if
11744      some global symbols were, in fact, converted to become local.
11745      FIXME: Will this work correctly with the Irix 5 linker?  */
11746   eoinfo.failed = FALSE;
11747   eoinfo.flinfo = &flinfo;
11748   eoinfo.localsyms = TRUE;
11749   eoinfo.file_sym_done = FALSE;
11750   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11751   if (eoinfo.failed)
11752     return FALSE;
11753
11754   /* If backend needs to output some local symbols not present in the hash
11755      table, do it now.  */
11756   if (bed->elf_backend_output_arch_local_syms
11757       && (info->strip != strip_all || emit_relocs))
11758     {
11759       typedef int (*out_sym_func)
11760         (void *, const char *, Elf_Internal_Sym *, asection *,
11761          struct elf_link_hash_entry *);
11762
11763       if (! ((*bed->elf_backend_output_arch_local_syms)
11764              (abfd, info, &flinfo,
11765               (out_sym_func) elf_link_output_symstrtab)))
11766         return FALSE;
11767     }
11768
11769   /* That wrote out all the local symbols.  Finish up the symbol table
11770      with the global symbols. Even if we want to strip everything we
11771      can, we still need to deal with those global symbols that got
11772      converted to local in a version script.  */
11773
11774   /* The sh_info field records the index of the first non local symbol.  */
11775   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11776
11777   if (dynamic
11778       && elf_hash_table (info)->dynsym != NULL
11779       && (elf_hash_table (info)->dynsym->output_section
11780           != bfd_abs_section_ptr))
11781     {
11782       Elf_Internal_Sym sym;
11783       bfd_byte *dynsym = elf_hash_table (info)->dynsym->contents;
11784       long last_local = 0;
11785
11786       /* Write out the section symbols for the output sections.  */
11787       if (bfd_link_pic (info)
11788           || elf_hash_table (info)->is_relocatable_executable)
11789         {
11790           asection *s;
11791
11792           sym.st_size = 0;
11793           sym.st_name = 0;
11794           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11795           sym.st_other = 0;
11796           sym.st_target_internal = 0;
11797
11798           for (s = abfd->sections; s != NULL; s = s->next)
11799             {
11800               int indx;
11801               bfd_byte *dest;
11802               long dynindx;
11803
11804               dynindx = elf_section_data (s)->dynindx;
11805               if (dynindx <= 0)
11806                 continue;
11807               indx = elf_section_data (s)->this_idx;
11808               BFD_ASSERT (indx > 0);
11809               sym.st_shndx = indx;
11810               if (! check_dynsym (abfd, &sym))
11811                 return FALSE;
11812               sym.st_value = s->vma;
11813               dest = dynsym + dynindx * bed->s->sizeof_sym;
11814               if (last_local < dynindx)
11815                 last_local = dynindx;
11816               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11817             }
11818         }
11819
11820       /* Write out the local dynsyms.  */
11821       if (elf_hash_table (info)->dynlocal)
11822         {
11823           struct elf_link_local_dynamic_entry *e;
11824           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11825             {
11826               asection *s;
11827               bfd_byte *dest;
11828
11829               /* Copy the internal symbol and turn off visibility.
11830                  Note that we saved a word of storage and overwrote
11831                  the original st_name with the dynstr_index.  */
11832               sym = e->isym;
11833               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11834
11835               s = bfd_section_from_elf_index (e->input_bfd,
11836                                               e->isym.st_shndx);
11837               if (s != NULL)
11838                 {
11839                   sym.st_shndx =
11840                     elf_section_data (s->output_section)->this_idx;
11841                   if (! check_dynsym (abfd, &sym))
11842                     return FALSE;
11843                   sym.st_value = (s->output_section->vma
11844                                   + s->output_offset
11845                                   + e->isym.st_value);
11846                 }
11847
11848               if (last_local < e->dynindx)
11849                 last_local = e->dynindx;
11850
11851               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11852               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11853             }
11854         }
11855
11856       elf_section_data (elf_hash_table (info)->dynsym->output_section)->this_hdr.sh_info =
11857         last_local + 1;
11858     }
11859
11860   /* We get the global symbols from the hash table.  */
11861   eoinfo.failed = FALSE;
11862   eoinfo.localsyms = FALSE;
11863   eoinfo.flinfo = &flinfo;
11864   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11865   if (eoinfo.failed)
11866     return FALSE;
11867
11868   /* If backend needs to output some symbols not present in the hash
11869      table, do it now.  */
11870   if (bed->elf_backend_output_arch_syms
11871       && (info->strip != strip_all || emit_relocs))
11872     {
11873       typedef int (*out_sym_func)
11874         (void *, const char *, Elf_Internal_Sym *, asection *,
11875          struct elf_link_hash_entry *);
11876
11877       if (! ((*bed->elf_backend_output_arch_syms)
11878              (abfd, info, &flinfo,
11879               (out_sym_func) elf_link_output_symstrtab)))
11880         return FALSE;
11881     }
11882
11883   /* Finalize the .strtab section.  */
11884   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11885
11886   /* Swap out the .strtab section. */
11887   if (!elf_link_swap_symbols_out (&flinfo))
11888     return FALSE;
11889
11890   /* Now we know the size of the symtab section.  */
11891   if (bfd_get_symcount (abfd) > 0)
11892     {
11893       /* Finish up and write out the symbol string table (.strtab)
11894          section.  */
11895       Elf_Internal_Shdr *symstrtab_hdr;
11896       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11897
11898       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
11899       if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
11900         {
11901           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11902           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11903           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11904           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11905           symtab_shndx_hdr->sh_size = amt;
11906
11907           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11908                                                            off, TRUE);
11909
11910           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11911               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11912             return FALSE;
11913         }
11914
11915       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11916       /* sh_name was set in prep_headers.  */
11917       symstrtab_hdr->sh_type = SHT_STRTAB;
11918       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
11919       symstrtab_hdr->sh_addr = 0;
11920       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11921       symstrtab_hdr->sh_entsize = 0;
11922       symstrtab_hdr->sh_link = 0;
11923       symstrtab_hdr->sh_info = 0;
11924       /* sh_offset is set just below.  */
11925       symstrtab_hdr->sh_addralign = 1;
11926
11927       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11928                                                        off, TRUE);
11929       elf_next_file_pos (abfd) = off;
11930
11931       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11932           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11933         return FALSE;
11934     }
11935
11936   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
11937     {
11938       (*_bfd_error_handler) (_("%B: failed to generate import library"),
11939                              info->out_implib_bfd);
11940       return FALSE;
11941     }
11942
11943   /* Adjust the relocs to have the correct symbol indices.  */
11944   for (o = abfd->sections; o != NULL; o = o->next)
11945     {
11946       struct bfd_elf_section_data *esdo = elf_section_data (o);
11947       bfd_boolean sort;
11948       if ((o->flags & SEC_RELOC) == 0)
11949         continue;
11950
11951       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11952       if (esdo->rel.hdr != NULL
11953           && !elf_link_adjust_relocs (abfd, &esdo->rel, sort))
11954         return FALSE;
11955       if (esdo->rela.hdr != NULL
11956           && !elf_link_adjust_relocs (abfd, &esdo->rela, sort))
11957         return FALSE;
11958
11959       /* Set the reloc_count field to 0 to prevent write_relocs from
11960          trying to swap the relocs out itself.  */
11961       o->reloc_count = 0;
11962     }
11963
11964   if (dynamic && info->combreloc && dynobj != NULL)
11965     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11966
11967   /* If we are linking against a dynamic object, or generating a
11968      shared library, finish up the dynamic linking information.  */
11969   if (dynamic)
11970     {
11971       bfd_byte *dyncon, *dynconend;
11972
11973       /* Fix up .dynamic entries.  */
11974       o = bfd_get_linker_section (dynobj, ".dynamic");
11975       BFD_ASSERT (o != NULL);
11976
11977       dyncon = o->contents;
11978       dynconend = o->contents + o->size;
11979       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11980         {
11981           Elf_Internal_Dyn dyn;
11982           const char *name;
11983           unsigned int type;
11984
11985           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11986
11987           switch (dyn.d_tag)
11988             {
11989             default:
11990               continue;
11991             case DT_NULL:
11992               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11993                 {
11994                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11995                     {
11996                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11997                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11998                     default: continue;
11999                     }
12000                   dyn.d_un.d_val = relativecount;
12001                   relativecount = 0;
12002                   break;
12003                 }
12004               continue;
12005
12006             case DT_INIT:
12007               name = info->init_function;
12008               goto get_sym;
12009             case DT_FINI:
12010               name = info->fini_function;
12011             get_sym:
12012               {
12013                 struct elf_link_hash_entry *h;
12014
12015                 h = elf_link_hash_lookup (elf_hash_table (info), name,
12016                                           FALSE, FALSE, TRUE);
12017                 if (h != NULL
12018                     && (h->root.type == bfd_link_hash_defined
12019                         || h->root.type == bfd_link_hash_defweak))
12020                   {
12021                     dyn.d_un.d_ptr = h->root.u.def.value;
12022                     o = h->root.u.def.section;
12023                     if (o->output_section != NULL)
12024                       dyn.d_un.d_ptr += (o->output_section->vma
12025                                          + o->output_offset);
12026                     else
12027                       {
12028                         /* The symbol is imported from another shared
12029                            library and does not apply to this one.  */
12030                         dyn.d_un.d_ptr = 0;
12031                       }
12032                     break;
12033                   }
12034               }
12035               continue;
12036
12037             case DT_PREINIT_ARRAYSZ:
12038               name = ".preinit_array";
12039               goto get_out_size;
12040             case DT_INIT_ARRAYSZ:
12041               name = ".init_array";
12042               goto get_out_size;
12043             case DT_FINI_ARRAYSZ:
12044               name = ".fini_array";
12045             get_out_size:
12046               o = bfd_get_section_by_name (abfd, name);
12047               if (o == NULL)
12048                 {
12049                   (*_bfd_error_handler)
12050                     (_("could not find section %s"), name);
12051                   goto error_return;
12052                 }
12053               if (o->size == 0)
12054                 (*_bfd_error_handler)
12055                   (_("warning: %s section has zero size"), name);
12056               dyn.d_un.d_val = o->size;
12057               break;
12058
12059             case DT_PREINIT_ARRAY:
12060               name = ".preinit_array";
12061               goto get_out_vma;
12062             case DT_INIT_ARRAY:
12063               name = ".init_array";
12064               goto get_out_vma;
12065             case DT_FINI_ARRAY:
12066               name = ".fini_array";
12067             get_out_vma:
12068               o = bfd_get_section_by_name (abfd, name);
12069               goto do_vma;
12070
12071             case DT_HASH:
12072               name = ".hash";
12073               goto get_vma;
12074             case DT_GNU_HASH:
12075               name = ".gnu.hash";
12076               goto get_vma;
12077             case DT_STRTAB:
12078               name = ".dynstr";
12079               goto get_vma;
12080             case DT_SYMTAB:
12081               name = ".dynsym";
12082               goto get_vma;
12083             case DT_VERDEF:
12084               name = ".gnu.version_d";
12085               goto get_vma;
12086             case DT_VERNEED:
12087               name = ".gnu.version_r";
12088               goto get_vma;
12089             case DT_VERSYM:
12090               name = ".gnu.version";
12091             get_vma:
12092               o = bfd_get_linker_section (dynobj, name);
12093             do_vma:
12094               if (o == NULL)
12095                 {
12096                   (*_bfd_error_handler)
12097                     (_("could not find section %s"), name);
12098                   goto error_return;
12099                 }
12100               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12101                 {
12102                   (*_bfd_error_handler)
12103                     (_("warning: section '%s' is being made into a note"), name);
12104                   bfd_set_error (bfd_error_nonrepresentable_section);
12105                   goto error_return;
12106                 }
12107               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12108               break;
12109
12110             case DT_REL:
12111             case DT_RELA:
12112             case DT_RELSZ:
12113             case DT_RELASZ:
12114               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12115                 type = SHT_REL;
12116               else
12117                 type = SHT_RELA;
12118               dyn.d_un.d_val = 0;
12119               dyn.d_un.d_ptr = 0;
12120               for (i = 1; i < elf_numsections (abfd); i++)
12121                 {
12122                   Elf_Internal_Shdr *hdr;
12123
12124                   hdr = elf_elfsections (abfd)[i];
12125                   if (hdr->sh_type == type
12126                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12127                     {
12128                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12129                         dyn.d_un.d_val += hdr->sh_size;
12130                       else
12131                         {
12132                           if (dyn.d_un.d_ptr == 0
12133                               || hdr->sh_addr < dyn.d_un.d_ptr)
12134                             dyn.d_un.d_ptr = hdr->sh_addr;
12135                         }
12136                     }
12137                 }
12138               break;
12139             }
12140           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12141         }
12142     }
12143
12144   /* If we have created any dynamic sections, then output them.  */
12145   if (dynobj != NULL)
12146     {
12147       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12148         goto error_return;
12149
12150       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12151       if (((info->warn_shared_textrel && bfd_link_pic (info))
12152            || info->error_textrel)
12153           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12154         {
12155           bfd_byte *dyncon, *dynconend;
12156
12157           dyncon = o->contents;
12158           dynconend = o->contents + o->size;
12159           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12160             {
12161               Elf_Internal_Dyn dyn;
12162
12163               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12164
12165               if (dyn.d_tag == DT_TEXTREL)
12166                 {
12167                   if (info->error_textrel)
12168                     info->callbacks->einfo
12169                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12170                   else
12171                     info->callbacks->einfo
12172                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12173                   break;
12174                 }
12175             }
12176         }
12177
12178       for (o = dynobj->sections; o != NULL; o = o->next)
12179         {
12180           if ((o->flags & SEC_HAS_CONTENTS) == 0
12181               || o->size == 0
12182               || o->output_section == bfd_abs_section_ptr)
12183             continue;
12184           if ((o->flags & SEC_LINKER_CREATED) == 0)
12185             {
12186               /* At this point, we are only interested in sections
12187                  created by _bfd_elf_link_create_dynamic_sections.  */
12188               continue;
12189             }
12190           if (elf_hash_table (info)->stab_info.stabstr == o)
12191             continue;
12192           if (elf_hash_table (info)->eh_info.hdr_sec == o)
12193             continue;
12194           if (strcmp (o->name, ".dynstr") != 0)
12195             {
12196               if (! bfd_set_section_contents (abfd, o->output_section,
12197                                               o->contents,
12198                                               (file_ptr) o->output_offset
12199                                               * bfd_octets_per_byte (abfd),
12200                                               o->size))
12201                 goto error_return;
12202             }
12203           else
12204             {
12205               /* The contents of the .dynstr section are actually in a
12206                  stringtab.  */
12207               file_ptr off;
12208
12209               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12210               if (bfd_seek (abfd, off, SEEK_SET) != 0
12211                   || ! _bfd_elf_strtab_emit (abfd,
12212                                              elf_hash_table (info)->dynstr))
12213                 goto error_return;
12214             }
12215         }
12216     }
12217
12218   if (bfd_link_relocatable (info))
12219     {
12220       bfd_boolean failed = FALSE;
12221
12222       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12223       if (failed)
12224         goto error_return;
12225     }
12226
12227   /* If we have optimized stabs strings, output them.  */
12228   if (elf_hash_table (info)->stab_info.stabstr != NULL)
12229     {
12230       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
12231         goto error_return;
12232     }
12233
12234   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12235     goto error_return;
12236
12237   elf_final_link_free (abfd, &flinfo);
12238
12239   elf_linker (abfd) = TRUE;
12240
12241   if (attr_section)
12242     {
12243       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12244       if (contents == NULL)
12245         return FALSE;   /* Bail out and fail.  */
12246       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12247       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12248       free (contents);
12249     }
12250
12251   return TRUE;
12252
12253  error_return:
12254   elf_final_link_free (abfd, &flinfo);
12255   return FALSE;
12256 }
12257 \f
12258 /* Initialize COOKIE for input bfd ABFD.  */
12259
12260 static bfd_boolean
12261 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12262                    struct bfd_link_info *info, bfd *abfd)
12263 {
12264   Elf_Internal_Shdr *symtab_hdr;
12265   const struct elf_backend_data *bed;
12266
12267   bed = get_elf_backend_data (abfd);
12268   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12269
12270   cookie->abfd = abfd;
12271   cookie->sym_hashes = elf_sym_hashes (abfd);
12272   cookie->bad_symtab = elf_bad_symtab (abfd);
12273   if (cookie->bad_symtab)
12274     {
12275       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12276       cookie->extsymoff = 0;
12277     }
12278   else
12279     {
12280       cookie->locsymcount = symtab_hdr->sh_info;
12281       cookie->extsymoff = symtab_hdr->sh_info;
12282     }
12283
12284   if (bed->s->arch_size == 32)
12285     cookie->r_sym_shift = 8;
12286   else
12287     cookie->r_sym_shift = 32;
12288
12289   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12290   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12291     {
12292       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12293                                               cookie->locsymcount, 0,
12294                                               NULL, NULL, NULL);
12295       if (cookie->locsyms == NULL)
12296         {
12297           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12298           return FALSE;
12299         }
12300       if (info->keep_memory)
12301         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12302     }
12303   return TRUE;
12304 }
12305
12306 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12307
12308 static void
12309 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12310 {
12311   Elf_Internal_Shdr *symtab_hdr;
12312
12313   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12314   if (cookie->locsyms != NULL
12315       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12316     free (cookie->locsyms);
12317 }
12318
12319 /* Initialize the relocation information in COOKIE for input section SEC
12320    of input bfd ABFD.  */
12321
12322 static bfd_boolean
12323 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12324                         struct bfd_link_info *info, bfd *abfd,
12325                         asection *sec)
12326 {
12327   const struct elf_backend_data *bed;
12328
12329   if (sec->reloc_count == 0)
12330     {
12331       cookie->rels = NULL;
12332       cookie->relend = NULL;
12333     }
12334   else
12335     {
12336       bed = get_elf_backend_data (abfd);
12337
12338       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12339                                                 info->keep_memory);
12340       if (cookie->rels == NULL)
12341         return FALSE;
12342       cookie->rel = cookie->rels;
12343       cookie->relend = (cookie->rels
12344                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12345     }
12346   cookie->rel = cookie->rels;
12347   return TRUE;
12348 }
12349
12350 /* Free the memory allocated by init_reloc_cookie_rels,
12351    if appropriate.  */
12352
12353 static void
12354 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12355                         asection *sec)
12356 {
12357   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12358     free (cookie->rels);
12359 }
12360
12361 /* Initialize the whole of COOKIE for input section SEC.  */
12362
12363 static bfd_boolean
12364 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12365                                struct bfd_link_info *info,
12366                                asection *sec)
12367 {
12368   if (!init_reloc_cookie (cookie, info, sec->owner))
12369     goto error1;
12370   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12371     goto error2;
12372   return TRUE;
12373
12374  error2:
12375   fini_reloc_cookie (cookie, sec->owner);
12376  error1:
12377   return FALSE;
12378 }
12379
12380 /* Free the memory allocated by init_reloc_cookie_for_section,
12381    if appropriate.  */
12382
12383 static void
12384 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12385                                asection *sec)
12386 {
12387   fini_reloc_cookie_rels (cookie, sec);
12388   fini_reloc_cookie (cookie, sec->owner);
12389 }
12390 \f
12391 /* Garbage collect unused sections.  */
12392
12393 /* Default gc_mark_hook.  */
12394
12395 asection *
12396 _bfd_elf_gc_mark_hook (asection *sec,
12397                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12398                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12399                        struct elf_link_hash_entry *h,
12400                        Elf_Internal_Sym *sym)
12401 {
12402   if (h != NULL)
12403     {
12404       switch (h->root.type)
12405         {
12406         case bfd_link_hash_defined:
12407         case bfd_link_hash_defweak:
12408           return h->root.u.def.section;
12409
12410         case bfd_link_hash_common:
12411           return h->root.u.c.p->section;
12412
12413         default:
12414           break;
12415         }
12416     }
12417   else
12418     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12419
12420   return NULL;
12421 }
12422
12423 /* For undefined __start_<name> and __stop_<name> symbols, return the
12424    first input section matching <name>.  Return NULL otherwise.  */
12425
12426 asection *
12427 _bfd_elf_is_start_stop (const struct bfd_link_info *info,
12428                         struct elf_link_hash_entry *h)
12429 {
12430   asection *s;
12431   const char *sec_name;
12432
12433   if (h->root.type != bfd_link_hash_undefined
12434       && h->root.type != bfd_link_hash_undefweak)
12435     return NULL;
12436
12437   s = h->root.u.undef.section;
12438   if (s != NULL)
12439     {
12440       if (s == (asection *) 0 - 1)
12441         return NULL;
12442       return s;
12443     }
12444
12445   sec_name = NULL;
12446   if (strncmp (h->root.root.string, "__start_", 8) == 0)
12447     sec_name = h->root.root.string + 8;
12448   else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12449     sec_name = h->root.root.string + 7;
12450
12451   if (sec_name != NULL && *sec_name != '\0')
12452     {
12453       bfd *i;
12454
12455       for (i = info->input_bfds; i != NULL; i = i->link.next)
12456         {
12457           s = bfd_get_section_by_name (i, sec_name);
12458           if (s != NULL)
12459             {
12460               h->root.u.undef.section = s;
12461               break;
12462             }
12463         }
12464     }
12465
12466   if (s == NULL)
12467     h->root.u.undef.section = (asection *) 0 - 1;
12468
12469   return s;
12470 }
12471
12472 /* COOKIE->rel describes a relocation against section SEC, which is
12473    a section we've decided to keep.  Return the section that contains
12474    the relocation symbol, or NULL if no section contains it.  */
12475
12476 asection *
12477 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12478                        elf_gc_mark_hook_fn gc_mark_hook,
12479                        struct elf_reloc_cookie *cookie,
12480                        bfd_boolean *start_stop)
12481 {
12482   unsigned long r_symndx;
12483   struct elf_link_hash_entry *h;
12484
12485   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12486   if (r_symndx == STN_UNDEF)
12487     return NULL;
12488
12489   if (r_symndx >= cookie->locsymcount
12490       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12491     {
12492       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12493       if (h == NULL)
12494         {
12495           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12496                                   sec->owner);
12497           return NULL;
12498         }
12499       while (h->root.type == bfd_link_hash_indirect
12500              || h->root.type == bfd_link_hash_warning)
12501         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12502       h->mark = 1;
12503       /* If this symbol is weak and there is a non-weak definition, we
12504          keep the non-weak definition because many backends put
12505          dynamic reloc info on the non-weak definition for code
12506          handling copy relocs.  */
12507       if (h->u.weakdef != NULL)
12508         h->u.weakdef->mark = 1;
12509
12510       if (start_stop != NULL)
12511         {
12512           /* To work around a glibc bug, mark all XXX input sections
12513              when there is an as yet undefined reference to __start_XXX
12514              or __stop_XXX symbols.  The linker will later define such
12515              symbols for orphan input sections that have a name
12516              representable as a C identifier.  */
12517           asection *s = _bfd_elf_is_start_stop (info, h);
12518
12519           if (s != NULL)
12520             {
12521               *start_stop = !s->gc_mark;
12522               return s;
12523             }
12524         }
12525
12526       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12527     }
12528
12529   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12530                           &cookie->locsyms[r_symndx]);
12531 }
12532
12533 /* COOKIE->rel describes a relocation against section SEC, which is
12534    a section we've decided to keep.  Mark the section that contains
12535    the relocation symbol.  */
12536
12537 bfd_boolean
12538 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12539                         asection *sec,
12540                         elf_gc_mark_hook_fn gc_mark_hook,
12541                         struct elf_reloc_cookie *cookie)
12542 {
12543   asection *rsec;
12544   bfd_boolean start_stop = FALSE;
12545
12546   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12547   while (rsec != NULL)
12548     {
12549       if (!rsec->gc_mark)
12550         {
12551           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12552               || (rsec->owner->flags & DYNAMIC) != 0)
12553             rsec->gc_mark = 1;
12554           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12555             return FALSE;
12556         }
12557       if (!start_stop)
12558         break;
12559       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12560     }
12561   return TRUE;
12562 }
12563
12564 /* The mark phase of garbage collection.  For a given section, mark
12565    it and any sections in this section's group, and all the sections
12566    which define symbols to which it refers.  */
12567
12568 bfd_boolean
12569 _bfd_elf_gc_mark (struct bfd_link_info *info,
12570                   asection *sec,
12571                   elf_gc_mark_hook_fn gc_mark_hook)
12572 {
12573   bfd_boolean ret;
12574   asection *group_sec, *eh_frame;
12575
12576   sec->gc_mark = 1;
12577
12578   /* Mark all the sections in the group.  */
12579   group_sec = elf_section_data (sec)->next_in_group;
12580   if (group_sec && !group_sec->gc_mark)
12581     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12582       return FALSE;
12583
12584   /* Look through the section relocs.  */
12585   ret = TRUE;
12586   eh_frame = elf_eh_frame_section (sec->owner);
12587   if ((sec->flags & SEC_RELOC) != 0
12588       && sec->reloc_count > 0
12589       && sec != eh_frame)
12590     {
12591       struct elf_reloc_cookie cookie;
12592
12593       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12594         ret = FALSE;
12595       else
12596         {
12597           for (; cookie.rel < cookie.relend; cookie.rel++)
12598             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12599               {
12600                 ret = FALSE;
12601                 break;
12602               }
12603           fini_reloc_cookie_for_section (&cookie, sec);
12604         }
12605     }
12606
12607   if (ret && eh_frame && elf_fde_list (sec))
12608     {
12609       struct elf_reloc_cookie cookie;
12610
12611       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12612         ret = FALSE;
12613       else
12614         {
12615           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12616                                       gc_mark_hook, &cookie))
12617             ret = FALSE;
12618           fini_reloc_cookie_for_section (&cookie, eh_frame);
12619         }
12620     }
12621
12622   eh_frame = elf_section_eh_frame_entry (sec);
12623   if (ret && eh_frame && !eh_frame->gc_mark)
12624     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12625       ret = FALSE;
12626
12627   return ret;
12628 }
12629
12630 /* Scan and mark sections in a special or debug section group.  */
12631
12632 static void
12633 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12634 {
12635   /* Point to first section of section group.  */
12636   asection *ssec;
12637   /* Used to iterate the section group.  */
12638   asection *msec;
12639
12640   bfd_boolean is_special_grp = TRUE;
12641   bfd_boolean is_debug_grp = TRUE;
12642
12643   /* First scan to see if group contains any section other than debug
12644      and special section.  */
12645   ssec = msec = elf_next_in_group (grp);
12646   do
12647     {
12648       if ((msec->flags & SEC_DEBUGGING) == 0)
12649         is_debug_grp = FALSE;
12650
12651       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12652         is_special_grp = FALSE;
12653
12654       msec = elf_next_in_group (msec);
12655     }
12656   while (msec != ssec);
12657
12658   /* If this is a pure debug section group or pure special section group,
12659      keep all sections in this group.  */
12660   if (is_debug_grp || is_special_grp)
12661     {
12662       do
12663         {
12664           msec->gc_mark = 1;
12665           msec = elf_next_in_group (msec);
12666         }
12667       while (msec != ssec);
12668     }
12669 }
12670
12671 /* Keep debug and special sections.  */
12672
12673 bfd_boolean
12674 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12675                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12676 {
12677   bfd *ibfd;
12678
12679   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12680     {
12681       asection *isec;
12682       bfd_boolean some_kept;
12683       bfd_boolean debug_frag_seen;
12684
12685       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12686         continue;
12687
12688       /* Ensure all linker created sections are kept,
12689          see if any other section is already marked,
12690          and note if we have any fragmented debug sections.  */
12691       debug_frag_seen = some_kept = FALSE;
12692       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12693         {
12694           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12695             isec->gc_mark = 1;
12696           else if (isec->gc_mark)
12697             some_kept = TRUE;
12698
12699           if (debug_frag_seen == FALSE
12700               && (isec->flags & SEC_DEBUGGING)
12701               && CONST_STRNEQ (isec->name, ".debug_line."))
12702             debug_frag_seen = TRUE;
12703         }
12704
12705       /* If no section in this file will be kept, then we can
12706          toss out the debug and special sections.  */
12707       if (!some_kept)
12708         continue;
12709
12710       /* Keep debug and special sections like .comment when they are
12711          not part of a group.  Also keep section groups that contain
12712          just debug sections or special sections.  */
12713       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12714         {
12715           if ((isec->flags & SEC_GROUP) != 0)
12716             _bfd_elf_gc_mark_debug_special_section_group (isec);
12717           else if (((isec->flags & SEC_DEBUGGING) != 0
12718                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12719                    && elf_next_in_group (isec) == NULL)
12720             isec->gc_mark = 1;
12721         }
12722
12723       if (! debug_frag_seen)
12724         continue;
12725
12726       /* Look for CODE sections which are going to be discarded,
12727          and find and discard any fragmented debug sections which
12728          are associated with that code section.  */
12729       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12730         if ((isec->flags & SEC_CODE) != 0
12731             && isec->gc_mark == 0)
12732           {
12733             unsigned int ilen;
12734             asection *dsec;
12735
12736             ilen = strlen (isec->name);
12737
12738             /* Association is determined by the name of the debug section
12739                containing the name of the code section as a suffix.  For
12740                example .debug_line.text.foo is a debug section associated
12741                with .text.foo.  */
12742             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12743               {
12744                 unsigned int dlen;
12745
12746                 if (dsec->gc_mark == 0
12747                     || (dsec->flags & SEC_DEBUGGING) == 0)
12748                   continue;
12749
12750                 dlen = strlen (dsec->name);
12751
12752                 if (dlen > ilen
12753                     && strncmp (dsec->name + (dlen - ilen),
12754                                 isec->name, ilen) == 0)
12755                   {
12756                     dsec->gc_mark = 0;
12757                   }
12758               }
12759           }
12760     }
12761   return TRUE;
12762 }
12763
12764 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12765
12766 struct elf_gc_sweep_symbol_info
12767 {
12768   struct bfd_link_info *info;
12769   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12770                        bfd_boolean);
12771 };
12772
12773 static bfd_boolean
12774 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12775 {
12776   if (!h->mark
12777       && (((h->root.type == bfd_link_hash_defined
12778             || h->root.type == bfd_link_hash_defweak)
12779            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12780                 && h->root.u.def.section->gc_mark))
12781           || h->root.type == bfd_link_hash_undefined
12782           || h->root.type == bfd_link_hash_undefweak))
12783     {
12784       struct elf_gc_sweep_symbol_info *inf;
12785
12786       inf = (struct elf_gc_sweep_symbol_info *) data;
12787       (*inf->hide_symbol) (inf->info, h, TRUE);
12788       h->def_regular = 0;
12789       h->ref_regular = 0;
12790       h->ref_regular_nonweak = 0;
12791     }
12792
12793   return TRUE;
12794 }
12795
12796 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12797
12798 typedef bfd_boolean (*gc_sweep_hook_fn)
12799   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12800
12801 static bfd_boolean
12802 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12803 {
12804   bfd *sub;
12805   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12806   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12807   unsigned long section_sym_count;
12808   struct elf_gc_sweep_symbol_info sweep_info;
12809
12810   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12811     {
12812       asection *o;
12813
12814       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12815           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12816         continue;
12817
12818       for (o = sub->sections; o != NULL; o = o->next)
12819         {
12820           /* When any section in a section group is kept, we keep all
12821              sections in the section group.  If the first member of
12822              the section group is excluded, we will also exclude the
12823              group section.  */
12824           if (o->flags & SEC_GROUP)
12825             {
12826               asection *first = elf_next_in_group (o);
12827               o->gc_mark = first->gc_mark;
12828             }
12829
12830           if (o->gc_mark)
12831             continue;
12832
12833           /* Skip sweeping sections already excluded.  */
12834           if (o->flags & SEC_EXCLUDE)
12835             continue;
12836
12837           /* Since this is early in the link process, it is simple
12838              to remove a section from the output.  */
12839           o->flags |= SEC_EXCLUDE;
12840
12841           if (info->print_gc_sections && o->size != 0)
12842             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12843
12844           /* But we also have to update some of the relocation
12845              info we collected before.  */
12846           if (gc_sweep_hook
12847               && (o->flags & SEC_RELOC) != 0
12848               && o->reloc_count != 0
12849               && !((info->strip == strip_all || info->strip == strip_debugger)
12850                    && (o->flags & SEC_DEBUGGING) != 0)
12851               && !bfd_is_abs_section (o->output_section))
12852             {
12853               Elf_Internal_Rela *internal_relocs;
12854               bfd_boolean r;
12855
12856               internal_relocs
12857                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12858                                              info->keep_memory);
12859               if (internal_relocs == NULL)
12860                 return FALSE;
12861
12862               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12863
12864               if (elf_section_data (o)->relocs != internal_relocs)
12865                 free (internal_relocs);
12866
12867               if (!r)
12868                 return FALSE;
12869             }
12870         }
12871     }
12872
12873   /* Remove the symbols that were in the swept sections from the dynamic
12874      symbol table.  GCFIXME: Anyone know how to get them out of the
12875      static symbol table as well?  */
12876   sweep_info.info = info;
12877   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12878   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12879                           &sweep_info);
12880
12881   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12882   return TRUE;
12883 }
12884
12885 /* Propagate collected vtable information.  This is called through
12886    elf_link_hash_traverse.  */
12887
12888 static bfd_boolean
12889 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12890 {
12891   /* Those that are not vtables.  */
12892   if (h->vtable == NULL || h->vtable->parent == NULL)
12893     return TRUE;
12894
12895   /* Those vtables that do not have parents, we cannot merge.  */
12896   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12897     return TRUE;
12898
12899   /* If we've already been done, exit.  */
12900   if (h->vtable->used && h->vtable->used[-1])
12901     return TRUE;
12902
12903   /* Make sure the parent's table is up to date.  */
12904   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12905
12906   if (h->vtable->used == NULL)
12907     {
12908       /* None of this table's entries were referenced.  Re-use the
12909          parent's table.  */
12910       h->vtable->used = h->vtable->parent->vtable->used;
12911       h->vtable->size = h->vtable->parent->vtable->size;
12912     }
12913   else
12914     {
12915       size_t n;
12916       bfd_boolean *cu, *pu;
12917
12918       /* Or the parent's entries into ours.  */
12919       cu = h->vtable->used;
12920       cu[-1] = TRUE;
12921       pu = h->vtable->parent->vtable->used;
12922       if (pu != NULL)
12923         {
12924           const struct elf_backend_data *bed;
12925           unsigned int log_file_align;
12926
12927           bed = get_elf_backend_data (h->root.u.def.section->owner);
12928           log_file_align = bed->s->log_file_align;
12929           n = h->vtable->parent->vtable->size >> log_file_align;
12930           while (n--)
12931             {
12932               if (*pu)
12933                 *cu = TRUE;
12934               pu++;
12935               cu++;
12936             }
12937         }
12938     }
12939
12940   return TRUE;
12941 }
12942
12943 static bfd_boolean
12944 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12945 {
12946   asection *sec;
12947   bfd_vma hstart, hend;
12948   Elf_Internal_Rela *relstart, *relend, *rel;
12949   const struct elf_backend_data *bed;
12950   unsigned int log_file_align;
12951
12952   /* Take care of both those symbols that do not describe vtables as
12953      well as those that are not loaded.  */
12954   if (h->vtable == NULL || h->vtable->parent == NULL)
12955     return TRUE;
12956
12957   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12958               || h->root.type == bfd_link_hash_defweak);
12959
12960   sec = h->root.u.def.section;
12961   hstart = h->root.u.def.value;
12962   hend = hstart + h->size;
12963
12964   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12965   if (!relstart)
12966     return *(bfd_boolean *) okp = FALSE;
12967   bed = get_elf_backend_data (sec->owner);
12968   log_file_align = bed->s->log_file_align;
12969
12970   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12971
12972   for (rel = relstart; rel < relend; ++rel)
12973     if (rel->r_offset >= hstart && rel->r_offset < hend)
12974       {
12975         /* If the entry is in use, do nothing.  */
12976         if (h->vtable->used
12977             && (rel->r_offset - hstart) < h->vtable->size)
12978           {
12979             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12980             if (h->vtable->used[entry])
12981               continue;
12982           }
12983         /* Otherwise, kill it.  */
12984         rel->r_offset = rel->r_info = rel->r_addend = 0;
12985       }
12986
12987   return TRUE;
12988 }
12989
12990 /* Mark sections containing dynamically referenced symbols.  When
12991    building shared libraries, we must assume that any visible symbol is
12992    referenced.  */
12993
12994 bfd_boolean
12995 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12996 {
12997   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12998   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12999
13000   if ((h->root.type == bfd_link_hash_defined
13001        || h->root.type == bfd_link_hash_defweak)
13002       && (h->ref_dynamic
13003           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13004               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13005               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13006               && (!bfd_link_executable (info)
13007                   || info->export_dynamic
13008                   || (h->dynamic
13009                       && d != NULL
13010                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13011               && (h->versioned >= versioned
13012                   || !bfd_hide_sym_by_version (info->version_info,
13013                                                h->root.root.string)))))
13014     h->root.u.def.section->flags |= SEC_KEEP;
13015
13016   return TRUE;
13017 }
13018
13019 /* Keep all sections containing symbols undefined on the command-line,
13020    and the section containing the entry symbol.  */
13021
13022 void
13023 _bfd_elf_gc_keep (struct bfd_link_info *info)
13024 {
13025   struct bfd_sym_chain *sym;
13026
13027   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13028     {
13029       struct elf_link_hash_entry *h;
13030
13031       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13032                                 FALSE, FALSE, FALSE);
13033
13034       if (h != NULL
13035           && (h->root.type == bfd_link_hash_defined
13036               || h->root.type == bfd_link_hash_defweak)
13037           && !bfd_is_abs_section (h->root.u.def.section))
13038         h->root.u.def.section->flags |= SEC_KEEP;
13039     }
13040 }
13041
13042 bfd_boolean
13043 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13044                                 struct bfd_link_info *info)
13045 {
13046   bfd *ibfd = info->input_bfds;
13047
13048   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13049     {
13050       asection *sec;
13051       struct elf_reloc_cookie cookie;
13052
13053       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13054         continue;
13055
13056       if (!init_reloc_cookie (&cookie, info, ibfd))
13057         return FALSE;
13058
13059       for (sec = ibfd->sections; sec; sec = sec->next)
13060         {
13061           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13062               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13063             {
13064               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13065               fini_reloc_cookie_rels (&cookie, sec);
13066             }
13067         }
13068     }
13069   return TRUE;
13070 }
13071
13072 /* Do mark and sweep of unused sections.  */
13073
13074 bfd_boolean
13075 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13076 {
13077   bfd_boolean ok = TRUE;
13078   bfd *sub;
13079   elf_gc_mark_hook_fn gc_mark_hook;
13080   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13081   struct elf_link_hash_table *htab;
13082
13083   if (!bed->can_gc_sections
13084       || !is_elf_hash_table (info->hash))
13085     {
13086       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
13087       return TRUE;
13088     }
13089
13090   bed->gc_keep (info);
13091   htab = elf_hash_table (info);
13092
13093   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13094      at the .eh_frame section if we can mark the FDEs individually.  */
13095   for (sub = info->input_bfds;
13096        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13097        sub = sub->link.next)
13098     {
13099       asection *sec;
13100       struct elf_reloc_cookie cookie;
13101
13102       sec = bfd_get_section_by_name (sub, ".eh_frame");
13103       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13104         {
13105           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13106           if (elf_section_data (sec)->sec_info
13107               && (sec->flags & SEC_LINKER_CREATED) == 0)
13108             elf_eh_frame_section (sub) = sec;
13109           fini_reloc_cookie_for_section (&cookie, sec);
13110           sec = bfd_get_next_section_by_name (NULL, sec);
13111         }
13112     }
13113
13114   /* Apply transitive closure to the vtable entry usage info.  */
13115   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13116   if (!ok)
13117     return FALSE;
13118
13119   /* Kill the vtable relocations that were not used.  */
13120   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13121   if (!ok)
13122     return FALSE;
13123
13124   /* Mark dynamically referenced symbols.  */
13125   if (htab->dynamic_sections_created)
13126     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13127
13128   /* Grovel through relocs to find out who stays ...  */
13129   gc_mark_hook = bed->gc_mark_hook;
13130   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13131     {
13132       asection *o;
13133
13134       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13135           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13136         continue;
13137
13138       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13139          Also treat note sections as a root, if the section is not part
13140          of a group.  */
13141       for (o = sub->sections; o != NULL; o = o->next)
13142         if (!o->gc_mark
13143             && (o->flags & SEC_EXCLUDE) == 0
13144             && ((o->flags & SEC_KEEP) != 0
13145                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13146                     && elf_next_in_group (o) == NULL )))
13147           {
13148             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13149               return FALSE;
13150           }
13151     }
13152
13153   /* Allow the backend to mark additional target specific sections.  */
13154   bed->gc_mark_extra_sections (info, gc_mark_hook);
13155
13156   /* ... and mark SEC_EXCLUDE for those that go.  */
13157   return elf_gc_sweep (abfd, info);
13158 }
13159 \f
13160 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13161
13162 bfd_boolean
13163 bfd_elf_gc_record_vtinherit (bfd *abfd,
13164                              asection *sec,
13165                              struct elf_link_hash_entry *h,
13166                              bfd_vma offset)
13167 {
13168   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13169   struct elf_link_hash_entry **search, *child;
13170   size_t extsymcount;
13171   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13172
13173   /* The sh_info field of the symtab header tells us where the
13174      external symbols start.  We don't care about the local symbols at
13175      this point.  */
13176   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13177   if (!elf_bad_symtab (abfd))
13178     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13179
13180   sym_hashes = elf_sym_hashes (abfd);
13181   sym_hashes_end = sym_hashes + extsymcount;
13182
13183   /* Hunt down the child symbol, which is in this section at the same
13184      offset as the relocation.  */
13185   for (search = sym_hashes; search != sym_hashes_end; ++search)
13186     {
13187       if ((child = *search) != NULL
13188           && (child->root.type == bfd_link_hash_defined
13189               || child->root.type == bfd_link_hash_defweak)
13190           && child->root.u.def.section == sec
13191           && child->root.u.def.value == offset)
13192         goto win;
13193     }
13194
13195   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
13196                          abfd, sec, (unsigned long) offset);
13197   bfd_set_error (bfd_error_invalid_operation);
13198   return FALSE;
13199
13200  win:
13201   if (!child->vtable)
13202     {
13203       child->vtable = ((struct elf_link_virtual_table_entry *)
13204                        bfd_zalloc (abfd, sizeof (*child->vtable)));
13205       if (!child->vtable)
13206         return FALSE;
13207     }
13208   if (!h)
13209     {
13210       /* This *should* only be the absolute section.  It could potentially
13211          be that someone has defined a non-global vtable though, which
13212          would be bad.  It isn't worth paging in the local symbols to be
13213          sure though; that case should simply be handled by the assembler.  */
13214
13215       child->vtable->parent = (struct elf_link_hash_entry *) -1;
13216     }
13217   else
13218     child->vtable->parent = h;
13219
13220   return TRUE;
13221 }
13222
13223 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13224
13225 bfd_boolean
13226 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13227                            asection *sec ATTRIBUTE_UNUSED,
13228                            struct elf_link_hash_entry *h,
13229                            bfd_vma addend)
13230 {
13231   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13232   unsigned int log_file_align = bed->s->log_file_align;
13233
13234   if (!h->vtable)
13235     {
13236       h->vtable = ((struct elf_link_virtual_table_entry *)
13237                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13238       if (!h->vtable)
13239         return FALSE;
13240     }
13241
13242   if (addend >= h->vtable->size)
13243     {
13244       size_t size, bytes, file_align;
13245       bfd_boolean *ptr = h->vtable->used;
13246
13247       /* While the symbol is undefined, we have to be prepared to handle
13248          a zero size.  */
13249       file_align = 1 << log_file_align;
13250       if (h->root.type == bfd_link_hash_undefined)
13251         size = addend + file_align;
13252       else
13253         {
13254           size = h->size;
13255           if (addend >= size)
13256             {
13257               /* Oops!  We've got a reference past the defined end of
13258                  the table.  This is probably a bug -- shall we warn?  */
13259               size = addend + file_align;
13260             }
13261         }
13262       size = (size + file_align - 1) & -file_align;
13263
13264       /* Allocate one extra entry for use as a "done" flag for the
13265          consolidation pass.  */
13266       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13267
13268       if (ptr)
13269         {
13270           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13271
13272           if (ptr != NULL)
13273             {
13274               size_t oldbytes;
13275
13276               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13277                           * sizeof (bfd_boolean));
13278               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13279             }
13280         }
13281       else
13282         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13283
13284       if (ptr == NULL)
13285         return FALSE;
13286
13287       /* And arrange for that done flag to be at index -1.  */
13288       h->vtable->used = ptr + 1;
13289       h->vtable->size = size;
13290     }
13291
13292   h->vtable->used[addend >> log_file_align] = TRUE;
13293
13294   return TRUE;
13295 }
13296
13297 /* Map an ELF section header flag to its corresponding string.  */
13298 typedef struct
13299 {
13300   char *flag_name;
13301   flagword flag_value;
13302 } elf_flags_to_name_table;
13303
13304 static elf_flags_to_name_table elf_flags_to_names [] =
13305 {
13306   { "SHF_WRITE", SHF_WRITE },
13307   { "SHF_ALLOC", SHF_ALLOC },
13308   { "SHF_EXECINSTR", SHF_EXECINSTR },
13309   { "SHF_MERGE", SHF_MERGE },
13310   { "SHF_STRINGS", SHF_STRINGS },
13311   { "SHF_INFO_LINK", SHF_INFO_LINK},
13312   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13313   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13314   { "SHF_GROUP", SHF_GROUP },
13315   { "SHF_TLS", SHF_TLS },
13316   { "SHF_MASKOS", SHF_MASKOS },
13317   { "SHF_EXCLUDE", SHF_EXCLUDE },
13318 };
13319
13320 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13321 bfd_boolean
13322 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13323                               struct flag_info *flaginfo,
13324                               asection *section)
13325 {
13326   const bfd_vma sh_flags = elf_section_flags (section);
13327
13328   if (!flaginfo->flags_initialized)
13329     {
13330       bfd *obfd = info->output_bfd;
13331       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13332       struct flag_info_list *tf = flaginfo->flag_list;
13333       int with_hex = 0;
13334       int without_hex = 0;
13335
13336       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13337         {
13338           unsigned i;
13339           flagword (*lookup) (char *);
13340
13341           lookup = bed->elf_backend_lookup_section_flags_hook;
13342           if (lookup != NULL)
13343             {
13344               flagword hexval = (*lookup) ((char *) tf->name);
13345
13346               if (hexval != 0)
13347                 {
13348                   if (tf->with == with_flags)
13349                     with_hex |= hexval;
13350                   else if (tf->with == without_flags)
13351                     without_hex |= hexval;
13352                   tf->valid = TRUE;
13353                   continue;
13354                 }
13355             }
13356           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13357             {
13358               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13359                 {
13360                   if (tf->with == with_flags)
13361                     with_hex |= elf_flags_to_names[i].flag_value;
13362                   else if (tf->with == without_flags)
13363                     without_hex |= elf_flags_to_names[i].flag_value;
13364                   tf->valid = TRUE;
13365                   break;
13366                 }
13367             }
13368           if (!tf->valid)
13369             {
13370               info->callbacks->einfo
13371                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13372               return FALSE;
13373             }
13374         }
13375       flaginfo->flags_initialized = TRUE;
13376       flaginfo->only_with_flags |= with_hex;
13377       flaginfo->not_with_flags |= without_hex;
13378     }
13379
13380   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13381     return FALSE;
13382
13383   if ((flaginfo->not_with_flags & sh_flags) != 0)
13384     return FALSE;
13385
13386   return TRUE;
13387 }
13388
13389 struct alloc_got_off_arg {
13390   bfd_vma gotoff;
13391   struct bfd_link_info *info;
13392 };
13393
13394 /* We need a special top-level link routine to convert got reference counts
13395    to real got offsets.  */
13396
13397 static bfd_boolean
13398 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13399 {
13400   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13401   bfd *obfd = gofarg->info->output_bfd;
13402   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13403
13404   if (h->got.refcount > 0)
13405     {
13406       h->got.offset = gofarg->gotoff;
13407       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13408     }
13409   else
13410     h->got.offset = (bfd_vma) -1;
13411
13412   return TRUE;
13413 }
13414
13415 /* And an accompanying bit to work out final got entry offsets once
13416    we're done.  Should be called from final_link.  */
13417
13418 bfd_boolean
13419 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13420                                         struct bfd_link_info *info)
13421 {
13422   bfd *i;
13423   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13424   bfd_vma gotoff;
13425   struct alloc_got_off_arg gofarg;
13426
13427   BFD_ASSERT (abfd == info->output_bfd);
13428
13429   if (! is_elf_hash_table (info->hash))
13430     return FALSE;
13431
13432   /* The GOT offset is relative to the .got section, but the GOT header is
13433      put into the .got.plt section, if the backend uses it.  */
13434   if (bed->want_got_plt)
13435     gotoff = 0;
13436   else
13437     gotoff = bed->got_header_size;
13438
13439   /* Do the local .got entries first.  */
13440   for (i = info->input_bfds; i; i = i->link.next)
13441     {
13442       bfd_signed_vma *local_got;
13443       size_t j, locsymcount;
13444       Elf_Internal_Shdr *symtab_hdr;
13445
13446       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13447         continue;
13448
13449       local_got = elf_local_got_refcounts (i);
13450       if (!local_got)
13451         continue;
13452
13453       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13454       if (elf_bad_symtab (i))
13455         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13456       else
13457         locsymcount = symtab_hdr->sh_info;
13458
13459       for (j = 0; j < locsymcount; ++j)
13460         {
13461           if (local_got[j] > 0)
13462             {
13463               local_got[j] = gotoff;
13464               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13465             }
13466           else
13467             local_got[j] = (bfd_vma) -1;
13468         }
13469     }
13470
13471   /* Then the global .got entries.  .plt refcounts are handled by
13472      adjust_dynamic_symbol  */
13473   gofarg.gotoff = gotoff;
13474   gofarg.info = info;
13475   elf_link_hash_traverse (elf_hash_table (info),
13476                           elf_gc_allocate_got_offsets,
13477                           &gofarg);
13478   return TRUE;
13479 }
13480
13481 /* Many folk need no more in the way of final link than this, once
13482    got entry reference counting is enabled.  */
13483
13484 bfd_boolean
13485 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13486 {
13487   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13488     return FALSE;
13489
13490   /* Invoke the regular ELF backend linker to do all the work.  */
13491   return bfd_elf_final_link (abfd, info);
13492 }
13493
13494 bfd_boolean
13495 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13496 {
13497   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13498
13499   if (rcookie->bad_symtab)
13500     rcookie->rel = rcookie->rels;
13501
13502   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13503     {
13504       unsigned long r_symndx;
13505
13506       if (! rcookie->bad_symtab)
13507         if (rcookie->rel->r_offset > offset)
13508           return FALSE;
13509       if (rcookie->rel->r_offset != offset)
13510         continue;
13511
13512       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13513       if (r_symndx == STN_UNDEF)
13514         return TRUE;
13515
13516       if (r_symndx >= rcookie->locsymcount
13517           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13518         {
13519           struct elf_link_hash_entry *h;
13520
13521           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13522
13523           while (h->root.type == bfd_link_hash_indirect
13524                  || h->root.type == bfd_link_hash_warning)
13525             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13526
13527           if ((h->root.type == bfd_link_hash_defined
13528                || h->root.type == bfd_link_hash_defweak)
13529               && (h->root.u.def.section->owner != rcookie->abfd
13530                   || h->root.u.def.section->kept_section != NULL
13531                   || discarded_section (h->root.u.def.section)))
13532             return TRUE;
13533         }
13534       else
13535         {
13536           /* It's not a relocation against a global symbol,
13537              but it could be a relocation against a local
13538              symbol for a discarded section.  */
13539           asection *isec;
13540           Elf_Internal_Sym *isym;
13541
13542           /* Need to: get the symbol; get the section.  */
13543           isym = &rcookie->locsyms[r_symndx];
13544           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13545           if (isec != NULL
13546               && (isec->kept_section != NULL
13547                   || discarded_section (isec)))
13548             return TRUE;
13549         }
13550       return FALSE;
13551     }
13552   return FALSE;
13553 }
13554
13555 /* Discard unneeded references to discarded sections.
13556    Returns -1 on error, 1 if any section's size was changed, 0 if
13557    nothing changed.  This function assumes that the relocations are in
13558    sorted order, which is true for all known assemblers.  */
13559
13560 int
13561 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13562 {
13563   struct elf_reloc_cookie cookie;
13564   asection *o;
13565   bfd *abfd;
13566   int changed = 0;
13567
13568   if (info->traditional_format
13569       || !is_elf_hash_table (info->hash))
13570     return 0;
13571
13572   o = bfd_get_section_by_name (output_bfd, ".stab");
13573   if (o != NULL)
13574     {
13575       asection *i;
13576
13577       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13578         {
13579           if (i->size == 0
13580               || i->reloc_count == 0
13581               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13582             continue;
13583
13584           abfd = i->owner;
13585           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13586             continue;
13587
13588           if (!init_reloc_cookie_for_section (&cookie, info, i))
13589             return -1;
13590
13591           if (_bfd_discard_section_stabs (abfd, i,
13592                                           elf_section_data (i)->sec_info,
13593                                           bfd_elf_reloc_symbol_deleted_p,
13594                                           &cookie))
13595             changed = 1;
13596
13597           fini_reloc_cookie_for_section (&cookie, i);
13598         }
13599     }
13600
13601   o = NULL;
13602   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13603     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13604   if (o != NULL)
13605     {
13606       asection *i;
13607
13608       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13609         {
13610           if (i->size == 0)
13611             continue;
13612
13613           abfd = i->owner;
13614           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13615             continue;
13616
13617           if (!init_reloc_cookie_for_section (&cookie, info, i))
13618             return -1;
13619
13620           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13621           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13622                                                  bfd_elf_reloc_symbol_deleted_p,
13623                                                  &cookie))
13624             changed = 1;
13625
13626           fini_reloc_cookie_for_section (&cookie, i);
13627         }
13628     }
13629
13630   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13631     {
13632       const struct elf_backend_data *bed;
13633
13634       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13635         continue;
13636
13637       bed = get_elf_backend_data (abfd);
13638
13639       if (bed->elf_backend_discard_info != NULL)
13640         {
13641           if (!init_reloc_cookie (&cookie, info, abfd))
13642             return -1;
13643
13644           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13645             changed = 1;
13646
13647           fini_reloc_cookie (&cookie, abfd);
13648         }
13649     }
13650
13651   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13652     _bfd_elf_end_eh_frame_parsing (info);
13653
13654   if (info->eh_frame_hdr_type
13655       && !bfd_link_relocatable (info)
13656       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13657     changed = 1;
13658
13659   return changed;
13660 }
13661
13662 bfd_boolean
13663 _bfd_elf_section_already_linked (bfd *abfd,
13664                                  asection *sec,
13665                                  struct bfd_link_info *info)
13666 {
13667   flagword flags;
13668   const char *name, *key;
13669   struct bfd_section_already_linked *l;
13670   struct bfd_section_already_linked_hash_entry *already_linked_list;
13671
13672   if (sec->output_section == bfd_abs_section_ptr)
13673     return FALSE;
13674
13675   flags = sec->flags;
13676
13677   /* Return if it isn't a linkonce section.  A comdat group section
13678      also has SEC_LINK_ONCE set.  */
13679   if ((flags & SEC_LINK_ONCE) == 0)
13680     return FALSE;
13681
13682   /* Don't put group member sections on our list of already linked
13683      sections.  They are handled as a group via their group section.  */
13684   if (elf_sec_group (sec) != NULL)
13685     return FALSE;
13686
13687   /* For a SHT_GROUP section, use the group signature as the key.  */
13688   name = sec->name;
13689   if ((flags & SEC_GROUP) != 0
13690       && elf_next_in_group (sec) != NULL
13691       && elf_group_name (elf_next_in_group (sec)) != NULL)
13692     key = elf_group_name (elf_next_in_group (sec));
13693   else
13694     {
13695       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13696       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13697           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13698         key++;
13699       else
13700         /* Must be a user linkonce section that doesn't follow gcc's
13701            naming convention.  In this case we won't be matching
13702            single member groups.  */
13703         key = name;
13704     }
13705
13706   already_linked_list = bfd_section_already_linked_table_lookup (key);
13707
13708   for (l = already_linked_list->entry; l != NULL; l = l->next)
13709     {
13710       /* We may have 2 different types of sections on the list: group
13711          sections with a signature of <key> (<key> is some string),
13712          and linkonce sections named .gnu.linkonce.<type>.<key>.
13713          Match like sections.  LTO plugin sections are an exception.
13714          They are always named .gnu.linkonce.t.<key> and match either
13715          type of section.  */
13716       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13717            && ((flags & SEC_GROUP) != 0
13718                || strcmp (name, l->sec->name) == 0))
13719           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13720         {
13721           /* The section has already been linked.  See if we should
13722              issue a warning.  */
13723           if (!_bfd_handle_already_linked (sec, l, info))
13724             return FALSE;
13725
13726           if (flags & SEC_GROUP)
13727             {
13728               asection *first = elf_next_in_group (sec);
13729               asection *s = first;
13730
13731               while (s != NULL)
13732                 {
13733                   s->output_section = bfd_abs_section_ptr;
13734                   /* Record which group discards it.  */
13735                   s->kept_section = l->sec;
13736                   s = elf_next_in_group (s);
13737                   /* These lists are circular.  */
13738                   if (s == first)
13739                     break;
13740                 }
13741             }
13742
13743           return TRUE;
13744         }
13745     }
13746
13747   /* A single member comdat group section may be discarded by a
13748      linkonce section and vice versa.  */
13749   if ((flags & SEC_GROUP) != 0)
13750     {
13751       asection *first = elf_next_in_group (sec);
13752
13753       if (first != NULL && elf_next_in_group (first) == first)
13754         /* Check this single member group against linkonce sections.  */
13755         for (l = already_linked_list->entry; l != NULL; l = l->next)
13756           if ((l->sec->flags & SEC_GROUP) == 0
13757               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13758             {
13759               first->output_section = bfd_abs_section_ptr;
13760               first->kept_section = l->sec;
13761               sec->output_section = bfd_abs_section_ptr;
13762               break;
13763             }
13764     }
13765   else
13766     /* Check this linkonce section against single member groups.  */
13767     for (l = already_linked_list->entry; l != NULL; l = l->next)
13768       if (l->sec->flags & SEC_GROUP)
13769         {
13770           asection *first = elf_next_in_group (l->sec);
13771
13772           if (first != NULL
13773               && elf_next_in_group (first) == first
13774               && bfd_elf_match_symbols_in_sections (first, sec, info))
13775             {
13776               sec->output_section = bfd_abs_section_ptr;
13777               sec->kept_section = first;
13778               break;
13779             }
13780         }
13781
13782   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13783      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13784      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13785      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13786      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13787      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13788      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13789      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13790      The reverse order cannot happen as there is never a bfd with only the
13791      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13792      matter as here were are looking only for cross-bfd sections.  */
13793
13794   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13795     for (l = already_linked_list->entry; l != NULL; l = l->next)
13796       if ((l->sec->flags & SEC_GROUP) == 0
13797           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13798         {
13799           if (abfd != l->sec->owner)
13800             sec->output_section = bfd_abs_section_ptr;
13801           break;
13802         }
13803
13804   /* This is the first section with this name.  Record it.  */
13805   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13806     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13807   return sec->output_section == bfd_abs_section_ptr;
13808 }
13809
13810 bfd_boolean
13811 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13812 {
13813   return sym->st_shndx == SHN_COMMON;
13814 }
13815
13816 unsigned int
13817 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13818 {
13819   return SHN_COMMON;
13820 }
13821
13822 asection *
13823 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13824 {
13825   return bfd_com_section_ptr;
13826 }
13827
13828 bfd_vma
13829 _bfd_elf_default_got_elt_size (bfd *abfd,
13830                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13831                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13832                                bfd *ibfd ATTRIBUTE_UNUSED,
13833                                unsigned long symndx ATTRIBUTE_UNUSED)
13834 {
13835   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13836   return bed->s->arch_size / 8;
13837 }
13838
13839 /* Routines to support the creation of dynamic relocs.  */
13840
13841 /* Returns the name of the dynamic reloc section associated with SEC.  */
13842
13843 static const char *
13844 get_dynamic_reloc_section_name (bfd *       abfd,
13845                                 asection *  sec,
13846                                 bfd_boolean is_rela)
13847 {
13848   char *name;
13849   const char *old_name = bfd_get_section_name (NULL, sec);
13850   const char *prefix = is_rela ? ".rela" : ".rel";
13851
13852   if (old_name == NULL)
13853     return NULL;
13854
13855   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13856   sprintf (name, "%s%s", prefix, old_name);
13857
13858   return name;
13859 }
13860
13861 /* Returns the dynamic reloc section associated with SEC.
13862    If necessary compute the name of the dynamic reloc section based
13863    on SEC's name (looked up in ABFD's string table) and the setting
13864    of IS_RELA.  */
13865
13866 asection *
13867 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13868                                     asection *  sec,
13869                                     bfd_boolean is_rela)
13870 {
13871   asection * reloc_sec = elf_section_data (sec)->sreloc;
13872
13873   if (reloc_sec == NULL)
13874     {
13875       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13876
13877       if (name != NULL)
13878         {
13879           reloc_sec = bfd_get_linker_section (abfd, name);
13880
13881           if (reloc_sec != NULL)
13882             elf_section_data (sec)->sreloc = reloc_sec;
13883         }
13884     }
13885
13886   return reloc_sec;
13887 }
13888
13889 /* Returns the dynamic reloc section associated with SEC.  If the
13890    section does not exist it is created and attached to the DYNOBJ
13891    bfd and stored in the SRELOC field of SEC's elf_section_data
13892    structure.
13893
13894    ALIGNMENT is the alignment for the newly created section and
13895    IS_RELA defines whether the name should be .rela.<SEC's name>
13896    or .rel.<SEC's name>.  The section name is looked up in the
13897    string table associated with ABFD.  */
13898
13899 asection *
13900 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13901                                      bfd *dynobj,
13902                                      unsigned int alignment,
13903                                      bfd *abfd,
13904                                      bfd_boolean is_rela)
13905 {
13906   asection * reloc_sec = elf_section_data (sec)->sreloc;
13907
13908   if (reloc_sec == NULL)
13909     {
13910       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13911
13912       if (name == NULL)
13913         return NULL;
13914
13915       reloc_sec = bfd_get_linker_section (dynobj, name);
13916
13917       if (reloc_sec == NULL)
13918         {
13919           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13920                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13921           if ((sec->flags & SEC_ALLOC) != 0)
13922             flags |= SEC_ALLOC | SEC_LOAD;
13923
13924           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13925           if (reloc_sec != NULL)
13926             {
13927               /* _bfd_elf_get_sec_type_attr chooses a section type by
13928                  name.  Override as it may be wrong, eg. for a user
13929                  section named "auto" we'll get ".relauto" which is
13930                  seen to be a .rela section.  */
13931               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13932               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13933                 reloc_sec = NULL;
13934             }
13935         }
13936
13937       elf_section_data (sec)->sreloc = reloc_sec;
13938     }
13939
13940   return reloc_sec;
13941 }
13942
13943 /* Copy the ELF symbol type and other attributes for a linker script
13944    assignment from HSRC to HDEST.  Generally this should be treated as
13945    if we found a strong non-dynamic definition for HDEST (except that
13946    ld ignores multiple definition errors).  */
13947 void
13948 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13949                                      struct bfd_link_hash_entry *hdest,
13950                                      struct bfd_link_hash_entry *hsrc)
13951 {
13952   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13953   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13954   Elf_Internal_Sym isym;
13955
13956   ehdest->type = ehsrc->type;
13957   ehdest->target_internal = ehsrc->target_internal;
13958
13959   isym.st_other = ehsrc->other;
13960   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13961 }
13962
13963 /* Append a RELA relocation REL to section S in BFD.  */
13964
13965 void
13966 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13967 {
13968   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13969   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13970   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13971   bed->s->swap_reloca_out (abfd, rel, loc);
13972 }
13973
13974 /* Append a REL relocation REL to section S in BFD.  */
13975
13976 void
13977 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13978 {
13979   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13980   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13981   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13982   bed->s->swap_reloc_out (abfd, rel, loc);
13983 }