Set dynobj to a normal input file if possible
[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
32 /* This struct is used to pass information to routines called via
33    elf_link_hash_traverse which must return failure.  */
34
35 struct elf_info_failed
36 {
37   struct bfd_link_info *info;
38   bfd_boolean failed;
39 };
40
41 /* This structure is used to pass information to
42    _bfd_elf_link_find_version_dependencies.  */
43
44 struct elf_find_verdep_info
45 {
46   /* General link information.  */
47   struct bfd_link_info *info;
48   /* The number of dependencies.  */
49   unsigned int vers;
50   /* Whether we had a failure.  */
51   bfd_boolean failed;
52 };
53
54 static bfd_boolean _bfd_elf_fix_symbol_flags
55   (struct elf_link_hash_entry *, struct elf_info_failed *);
56
57 asection *
58 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
59                              unsigned long r_symndx,
60                              bfd_boolean discard)
61 {
62   if (r_symndx >= cookie->locsymcount
63       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
64     {
65       struct elf_link_hash_entry *h;
66
67       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
68
69       while (h->root.type == bfd_link_hash_indirect
70              || h->root.type == bfd_link_hash_warning)
71         h = (struct elf_link_hash_entry *) h->root.u.i.link;
72
73       if ((h->root.type == bfd_link_hash_defined
74            || h->root.type == bfd_link_hash_defweak)
75            && discarded_section (h->root.u.def.section))
76         return h->root.u.def.section;
77       else
78         return NULL;
79     }
80   else
81     {
82       /* It's not a relocation against a global symbol,
83          but it could be a relocation against a local
84          symbol for a discarded section.  */
85       asection *isec;
86       Elf_Internal_Sym *isym;
87
88       /* Need to: get the symbol; get the section.  */
89       isym = &cookie->locsyms[r_symndx];
90       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
91       if (isec != NULL
92           && discard ? discarded_section (isec) : 1)
93         return isec;
94      }
95   return NULL;
96 }
97
98 /* Define a symbol in a dynamic linkage section.  */
99
100 struct elf_link_hash_entry *
101 _bfd_elf_define_linkage_sym (bfd *abfd,
102                              struct bfd_link_info *info,
103                              asection *sec,
104                              const char *name)
105 {
106   struct elf_link_hash_entry *h;
107   struct bfd_link_hash_entry *bh;
108   const struct elf_backend_data *bed;
109
110   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
111   if (h != NULL)
112     {
113       /* Zap symbol defined in an as-needed lib that wasn't linked.
114          This is a symptom of a larger problem:  Absolute symbols
115          defined in shared libraries can't be overridden, because we
116          lose the link to the bfd which is via the symbol section.  */
117       h->root.type = bfd_link_hash_new;
118     }
119
120   bh = &h->root;
121   bed = get_elf_backend_data (abfd);
122   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
123                                          sec, 0, NULL, FALSE, bed->collect,
124                                          &bh))
125     return NULL;
126   h = (struct elf_link_hash_entry *) bh;
127   h->def_regular = 1;
128   h->non_elf = 0;
129   h->root.linker_def = 1;
130   h->type = STT_OBJECT;
131   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
132     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
133
134   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
135   return h;
136 }
137
138 bfd_boolean
139 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
140 {
141   flagword flags;
142   asection *s;
143   struct elf_link_hash_entry *h;
144   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
145   struct elf_link_hash_table *htab = elf_hash_table (info);
146
147   /* This function may be called more than once.  */
148   s = bfd_get_linker_section (abfd, ".got");
149   if (s != NULL)
150     return TRUE;
151
152   flags = bed->dynamic_sec_flags;
153
154   s = bfd_make_section_anyway_with_flags (abfd,
155                                           (bed->rela_plts_and_copies_p
156                                            ? ".rela.got" : ".rel.got"),
157                                           (bed->dynamic_sec_flags
158                                            | SEC_READONLY));
159   if (s == NULL
160       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
161     return FALSE;
162   htab->srelgot = s;
163
164   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
165   if (s == NULL
166       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->sgot = s;
169
170   if (bed->want_got_plt)
171     {
172       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
173       if (s == NULL
174           || !bfd_set_section_alignment (abfd, s,
175                                          bed->s->log_file_align))
176         return FALSE;
177       htab->sgotplt = s;
178     }
179
180   /* The first bit of the global offset table is the header.  */
181   s->size += bed->got_header_size;
182
183   if (bed->want_got_sym)
184     {
185       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
186          (or .got.plt) section.  We don't do this in the linker script
187          because we don't want to define the symbol if we are not creating
188          a global offset table.  */
189       h = _bfd_elf_define_linkage_sym (abfd, info, s,
190                                        "_GLOBAL_OFFSET_TABLE_");
191       elf_hash_table (info)->hgot = h;
192       if (h == NULL)
193         return FALSE;
194     }
195
196   return TRUE;
197 }
198 \f
199 /* Create a strtab to hold the dynamic symbol names.  */
200 static bfd_boolean
201 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
202 {
203   struct elf_link_hash_table *hash_table;
204
205   hash_table = elf_hash_table (info);
206   if (hash_table->dynobj == NULL)
207     {
208       /* We may not set dynobj, an input file holding linker created
209          dynamic sections to abfd, which may be a dynamic object with
210          its own dynamic sections.  We need to find a normal input file
211          to hold linker created sections if possible.  */
212       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
213         {
214           bfd *ibfd;
215           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
216             if ((ibfd->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
217               {
218                 abfd = ibfd;
219                 break;
220               }
221         }
222       hash_table->dynobj = abfd;
223     }
224
225   if (hash_table->dynstr == NULL)
226     {
227       hash_table->dynstr = _bfd_elf_strtab_init ();
228       if (hash_table->dynstr == NULL)
229         return FALSE;
230     }
231   return TRUE;
232 }
233
234 /* Create some sections which will be filled in with dynamic linking
235    information.  ABFD is an input file which requires dynamic sections
236    to be created.  The dynamic sections take up virtual memory space
237    when the final executable is run, so we need to create them before
238    addresses are assigned to the output sections.  We work out the
239    actual contents and size of these sections later.  */
240
241 bfd_boolean
242 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
243 {
244   flagword flags;
245   asection *s;
246   const struct elf_backend_data *bed;
247   struct elf_link_hash_entry *h;
248
249   if (! is_elf_hash_table (info->hash))
250     return FALSE;
251
252   if (elf_hash_table (info)->dynamic_sections_created)
253     return TRUE;
254
255   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
256     return FALSE;
257
258   abfd = elf_hash_table (info)->dynobj;
259   bed = get_elf_backend_data (abfd);
260
261   flags = bed->dynamic_sec_flags;
262
263   /* A dynamically linked executable has a .interp section, but a
264      shared library does not.  */
265   if (bfd_link_executable (info) && !info->nointerp)
266     {
267       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
268                                               flags | SEC_READONLY);
269       if (s == NULL)
270         return FALSE;
271     }
272
273   /* Create sections to hold version informations.  These are removed
274      if they are not needed.  */
275   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
276                                           flags | SEC_READONLY);
277   if (s == NULL
278       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
279     return FALSE;
280
281   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
282                                           flags | SEC_READONLY);
283   if (s == NULL
284       || ! bfd_set_section_alignment (abfd, s, 1))
285     return FALSE;
286
287   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
288                                           flags | SEC_READONLY);
289   if (s == NULL
290       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
291     return FALSE;
292
293   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
294                                           flags | SEC_READONLY);
295   if (s == NULL
296       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
297     return FALSE;
298   elf_hash_table (info)->dynsym = s;
299
300   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
301                                           flags | SEC_READONLY);
302   if (s == NULL)
303     return FALSE;
304
305   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309
310   /* The special symbol _DYNAMIC is always set to the start of the
311      .dynamic section.  We could set _DYNAMIC in a linker script, but we
312      only want to define it if we are, in fact, creating a .dynamic
313      section.  We don't want to define it if there is no .dynamic
314      section, since on some ELF platforms the start up code examines it
315      to decide how to initialize the process.  */
316   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
317   elf_hash_table (info)->hdynamic = h;
318   if (h == NULL)
319     return FALSE;
320
321   if (info->emit_hash)
322     {
323       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
324                                               flags | SEC_READONLY);
325       if (s == NULL
326           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
327         return FALSE;
328       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
329     }
330
331   if (info->emit_gnu_hash)
332     {
333       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
334                                               flags | SEC_READONLY);
335       if (s == NULL
336           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
337         return FALSE;
338       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
339          4 32-bit words followed by variable count of 64-bit words, then
340          variable count of 32-bit words.  */
341       if (bed->s->arch_size == 64)
342         elf_section_data (s)->this_hdr.sh_entsize = 0;
343       else
344         elf_section_data (s)->this_hdr.sh_entsize = 4;
345     }
346
347   /* Let the backend create the rest of the sections.  This lets the
348      backend set the right flags.  The backend will normally create
349      the .got and .plt sections.  */
350   if (bed->elf_backend_create_dynamic_sections == NULL
351       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
352     return FALSE;
353
354   elf_hash_table (info)->dynamic_sections_created = TRUE;
355
356   return TRUE;
357 }
358
359 /* Create dynamic sections when linking against a dynamic object.  */
360
361 bfd_boolean
362 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
363 {
364   flagword flags, pltflags;
365   struct elf_link_hash_entry *h;
366   asection *s;
367   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
368   struct elf_link_hash_table *htab = elf_hash_table (info);
369
370   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
371      .rel[a].bss sections.  */
372   flags = bed->dynamic_sec_flags;
373
374   pltflags = flags;
375   if (bed->plt_not_loaded)
376     /* We do not clear SEC_ALLOC here because we still want the OS to
377        allocate space for the section; it's just that there's nothing
378        to read in from the object file.  */
379     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
380   else
381     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
382   if (bed->plt_readonly)
383     pltflags |= SEC_READONLY;
384
385   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
386   if (s == NULL
387       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
388     return FALSE;
389   htab->splt = s;
390
391   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
392      .plt section.  */
393   if (bed->want_plt_sym)
394     {
395       h = _bfd_elf_define_linkage_sym (abfd, info, s,
396                                        "_PROCEDURE_LINKAGE_TABLE_");
397       elf_hash_table (info)->hplt = h;
398       if (h == NULL)
399         return FALSE;
400     }
401
402   s = bfd_make_section_anyway_with_flags (abfd,
403                                           (bed->rela_plts_and_copies_p
404                                            ? ".rela.plt" : ".rel.plt"),
405                                           flags | SEC_READONLY);
406   if (s == NULL
407       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
408     return FALSE;
409   htab->srelplt = s;
410
411   if (! _bfd_elf_create_got_section (abfd, info))
412     return FALSE;
413
414   if (bed->want_dynbss)
415     {
416       /* The .dynbss section is a place to put symbols which are defined
417          by dynamic objects, are referenced by regular objects, and are
418          not functions.  We must allocate space for them in the process
419          image and use a R_*_COPY reloc to tell the dynamic linker to
420          initialize them at run time.  The linker script puts the .dynbss
421          section into the .bss section of the final image.  */
422       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
423                                               (SEC_ALLOC | SEC_LINKER_CREATED));
424       if (s == NULL)
425         return FALSE;
426
427       /* The .rel[a].bss section holds copy relocs.  This section is not
428          normally needed.  We need to create it here, though, so that the
429          linker will map it to an output section.  We can't just create it
430          only if we need it, because we will not know whether we need it
431          until we have seen all the input files, and the first time the
432          main linker code calls BFD after examining all the input files
433          (size_dynamic_sections) the input sections have already been
434          mapped to the output sections.  If the section turns out not to
435          be needed, we can discard it later.  We will never need this
436          section when generating a shared object, since they do not use
437          copy relocs.  */
438       if (! bfd_link_pic (info))
439         {
440           s = bfd_make_section_anyway_with_flags (abfd,
441                                                   (bed->rela_plts_and_copies_p
442                                                    ? ".rela.bss" : ".rel.bss"),
443                                                   flags | SEC_READONLY);
444           if (s == NULL
445               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
446             return FALSE;
447         }
448     }
449
450   return TRUE;
451 }
452 \f
453 /* Record a new dynamic symbol.  We record the dynamic symbols as we
454    read the input files, since we need to have a list of all of them
455    before we can determine the final sizes of the output sections.
456    Note that we may actually call this function even though we are not
457    going to output any dynamic symbols; in some cases we know that a
458    symbol should be in the dynamic symbol table, but only if there is
459    one.  */
460
461 bfd_boolean
462 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
463                                     struct elf_link_hash_entry *h)
464 {
465   if (h->dynindx == -1)
466     {
467       struct elf_strtab_hash *dynstr;
468       char *p;
469       const char *name;
470       bfd_size_type indx;
471
472       /* XXX: The ABI draft says the linker must turn hidden and
473          internal symbols into STB_LOCAL symbols when producing the
474          DSO. However, if ld.so honors st_other in the dynamic table,
475          this would not be necessary.  */
476       switch (ELF_ST_VISIBILITY (h->other))
477         {
478         case STV_INTERNAL:
479         case STV_HIDDEN:
480           if (h->root.type != bfd_link_hash_undefined
481               && h->root.type != bfd_link_hash_undefweak)
482             {
483               h->forced_local = 1;
484               if (!elf_hash_table (info)->is_relocatable_executable)
485                 return TRUE;
486             }
487
488         default:
489           break;
490         }
491
492       h->dynindx = elf_hash_table (info)->dynsymcount;
493       ++elf_hash_table (info)->dynsymcount;
494
495       dynstr = elf_hash_table (info)->dynstr;
496       if (dynstr == NULL)
497         {
498           /* Create a strtab to hold the dynamic symbol names.  */
499           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
500           if (dynstr == NULL)
501             return FALSE;
502         }
503
504       /* We don't put any version information in the dynamic string
505          table.  */
506       name = h->root.root.string;
507       p = strchr (name, ELF_VER_CHR);
508       if (p != NULL)
509         /* We know that the p points into writable memory.  In fact,
510            there are only a few symbols that have read-only names, being
511            those like _GLOBAL_OFFSET_TABLE_ that are created specially
512            by the backends.  Most symbols will have names pointing into
513            an ELF string table read from a file, or to objalloc memory.  */
514         *p = 0;
515
516       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
517
518       if (p != NULL)
519         *p = ELF_VER_CHR;
520
521       if (indx == (bfd_size_type) -1)
522         return FALSE;
523       h->dynstr_index = indx;
524     }
525
526   return TRUE;
527 }
528 \f
529 /* Mark a symbol dynamic.  */
530
531 static void
532 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
533                                   struct elf_link_hash_entry *h,
534                                   Elf_Internal_Sym *sym)
535 {
536   struct bfd_elf_dynamic_list *d = info->dynamic_list;
537
538   /* It may be called more than once on the same H.  */
539   if(h->dynamic || bfd_link_relocatable (info))
540     return;
541
542   if ((info->dynamic_data
543        && (h->type == STT_OBJECT
544            || h->type == STT_COMMON
545            || (sym != NULL
546                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
547                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
548       || (d != NULL
549           && h->root.type == bfd_link_hash_new
550           && (*d->match) (&d->head, NULL, h->root.root.string)))
551     h->dynamic = 1;
552 }
553
554 /* Record an assignment to a symbol made by a linker script.  We need
555    this in case some dynamic object refers to this symbol.  */
556
557 bfd_boolean
558 bfd_elf_record_link_assignment (bfd *output_bfd,
559                                 struct bfd_link_info *info,
560                                 const char *name,
561                                 bfd_boolean provide,
562                                 bfd_boolean hidden)
563 {
564   struct elf_link_hash_entry *h, *hv;
565   struct elf_link_hash_table *htab;
566   const struct elf_backend_data *bed;
567
568   if (!is_elf_hash_table (info->hash))
569     return TRUE;
570
571   htab = elf_hash_table (info);
572   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
573   if (h == NULL)
574     return provide;
575
576   if (h->versioned == unknown)
577     {
578       /* Set versioned if symbol version is unknown.  */
579       char *version = strrchr (name, ELF_VER_CHR);
580       if (version)
581         {
582           if (version > name && version[-1] != ELF_VER_CHR)
583             h->versioned = versioned_hidden;
584           else
585             h->versioned = versioned;
586         }
587     }
588
589   switch (h->root.type)
590     {
591     case bfd_link_hash_defined:
592     case bfd_link_hash_defweak:
593     case bfd_link_hash_common:
594       break;
595     case bfd_link_hash_undefweak:
596     case bfd_link_hash_undefined:
597       /* Since we're defining the symbol, don't let it seem to have not
598          been defined.  record_dynamic_symbol and size_dynamic_sections
599          may depend on this.  */
600       h->root.type = bfd_link_hash_new;
601       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
602         bfd_link_repair_undef_list (&htab->root);
603       break;
604     case bfd_link_hash_new:
605       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
606       h->non_elf = 0;
607       break;
608     case bfd_link_hash_indirect:
609       /* We had a versioned symbol in a dynamic library.  We make the
610          the versioned symbol point to this one.  */
611       bed = get_elf_backend_data (output_bfd);
612       hv = h;
613       while (hv->root.type == bfd_link_hash_indirect
614              || hv->root.type == bfd_link_hash_warning)
615         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
616       /* We don't need to update h->root.u since linker will set them
617          later.  */
618       h->root.type = bfd_link_hash_undefined;
619       hv->root.type = bfd_link_hash_indirect;
620       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
621       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
622       break;
623     case bfd_link_hash_warning:
624       abort ();
625       break;
626     }
627
628   /* If this symbol is being provided by the linker script, and it is
629      currently defined by a dynamic object, but not by a regular
630      object, then mark it as undefined so that the generic linker will
631      force the correct value.  */
632   if (provide
633       && h->def_dynamic
634       && !h->def_regular)
635     h->root.type = bfd_link_hash_undefined;
636
637   /* If this symbol is not being provided by the linker script, and it is
638      currently defined by a dynamic object, but not by a regular object,
639      then clear out any version information because the symbol will not be
640      associated with the dynamic object any more.  */
641   if (!provide
642       && h->def_dynamic
643       && !h->def_regular)
644     h->verinfo.verdef = NULL;
645
646   h->def_regular = 1;
647
648   if (hidden)
649     {
650       bed = get_elf_backend_data (output_bfd);
651       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
652         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
653       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
654     }
655
656   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
657      and executables.  */
658   if (!bfd_link_relocatable (info)
659       && h->dynindx != -1
660       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
661           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
662     h->forced_local = 1;
663
664   if ((h->def_dynamic
665        || h->ref_dynamic
666        || bfd_link_dll (info)
667        || elf_hash_table (info)->is_relocatable_executable)
668       && h->dynindx == -1)
669     {
670       if (! bfd_elf_link_record_dynamic_symbol (info, h))
671         return FALSE;
672
673       /* If this is a weak defined symbol, and we know a corresponding
674          real symbol from the same dynamic object, make sure the real
675          symbol is also made into a dynamic symbol.  */
676       if (h->u.weakdef != NULL
677           && h->u.weakdef->dynindx == -1)
678         {
679           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
680             return FALSE;
681         }
682     }
683
684   return TRUE;
685 }
686
687 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
688    success, and 2 on a failure caused by attempting to record a symbol
689    in a discarded section, eg. a discarded link-once section symbol.  */
690
691 int
692 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
693                                           bfd *input_bfd,
694                                           long input_indx)
695 {
696   bfd_size_type amt;
697   struct elf_link_local_dynamic_entry *entry;
698   struct elf_link_hash_table *eht;
699   struct elf_strtab_hash *dynstr;
700   unsigned long dynstr_index;
701   char *name;
702   Elf_External_Sym_Shndx eshndx;
703   char esym[sizeof (Elf64_External_Sym)];
704
705   if (! is_elf_hash_table (info->hash))
706     return 0;
707
708   /* See if the entry exists already.  */
709   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
710     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
711       return 1;
712
713   amt = sizeof (*entry);
714   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
715   if (entry == NULL)
716     return 0;
717
718   /* Go find the symbol, so that we can find it's name.  */
719   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
720                              1, input_indx, &entry->isym, esym, &eshndx))
721     {
722       bfd_release (input_bfd, entry);
723       return 0;
724     }
725
726   if (entry->isym.st_shndx != SHN_UNDEF
727       && entry->isym.st_shndx < SHN_LORESERVE)
728     {
729       asection *s;
730
731       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
732       if (s == NULL || bfd_is_abs_section (s->output_section))
733         {
734           /* We can still bfd_release here as nothing has done another
735              bfd_alloc.  We can't do this later in this function.  */
736           bfd_release (input_bfd, entry);
737           return 2;
738         }
739     }
740
741   name = (bfd_elf_string_from_elf_section
742           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
743            entry->isym.st_name));
744
745   dynstr = elf_hash_table (info)->dynstr;
746   if (dynstr == NULL)
747     {
748       /* Create a strtab to hold the dynamic symbol names.  */
749       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
750       if (dynstr == NULL)
751         return 0;
752     }
753
754   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
755   if (dynstr_index == (unsigned long) -1)
756     return 0;
757   entry->isym.st_name = dynstr_index;
758
759   eht = elf_hash_table (info);
760
761   entry->next = eht->dynlocal;
762   eht->dynlocal = entry;
763   entry->input_bfd = input_bfd;
764   entry->input_indx = input_indx;
765   eht->dynsymcount++;
766
767   /* Whatever binding the symbol had before, it's now local.  */
768   entry->isym.st_info
769     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
770
771   /* The dynindx will be set at the end of size_dynamic_sections.  */
772
773   return 1;
774 }
775
776 /* Return the dynindex of a local dynamic symbol.  */
777
778 long
779 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
780                                     bfd *input_bfd,
781                                     long input_indx)
782 {
783   struct elf_link_local_dynamic_entry *e;
784
785   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
786     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
787       return e->dynindx;
788   return -1;
789 }
790
791 /* This function is used to renumber the dynamic symbols, if some of
792    them are removed because they are marked as local.  This is called
793    via elf_link_hash_traverse.  */
794
795 static bfd_boolean
796 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
797                                       void *data)
798 {
799   size_t *count = (size_t *) data;
800
801   if (h->forced_local)
802     return TRUE;
803
804   if (h->dynindx != -1)
805     h->dynindx = ++(*count);
806
807   return TRUE;
808 }
809
810
811 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
812    STB_LOCAL binding.  */
813
814 static bfd_boolean
815 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
816                                             void *data)
817 {
818   size_t *count = (size_t *) data;
819
820   if (!h->forced_local)
821     return TRUE;
822
823   if (h->dynindx != -1)
824     h->dynindx = ++(*count);
825
826   return TRUE;
827 }
828
829 /* Return true if the dynamic symbol for a given section should be
830    omitted when creating a shared library.  */
831 bfd_boolean
832 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
833                                    struct bfd_link_info *info,
834                                    asection *p)
835 {
836   struct elf_link_hash_table *htab;
837   asection *ip;
838
839   switch (elf_section_data (p)->this_hdr.sh_type)
840     {
841     case SHT_PROGBITS:
842     case SHT_NOBITS:
843       /* If sh_type is yet undecided, assume it could be
844          SHT_PROGBITS/SHT_NOBITS.  */
845     case SHT_NULL:
846       htab = elf_hash_table (info);
847       if (p == htab->tls_sec)
848         return FALSE;
849
850       if (htab->text_index_section != NULL)
851         return p != htab->text_index_section && p != htab->data_index_section;
852
853       return (htab->dynobj != NULL
854               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
855               && ip->output_section == p);
856
857       /* There shouldn't be section relative relocations
858          against any other section.  */
859     default:
860       return TRUE;
861     }
862 }
863
864 /* Assign dynsym indices.  In a shared library we generate a section
865    symbol for each output section, which come first.  Next come symbols
866    which have been forced to local binding.  Then all of the back-end
867    allocated local dynamic syms, followed by the rest of the global
868    symbols.  */
869
870 static unsigned long
871 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
872                                 struct bfd_link_info *info,
873                                 unsigned long *section_sym_count)
874 {
875   unsigned long dynsymcount = 0;
876
877   if (bfd_link_pic (info)
878       || elf_hash_table (info)->is_relocatable_executable)
879     {
880       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
881       asection *p;
882       for (p = output_bfd->sections; p ; p = p->next)
883         if ((p->flags & SEC_EXCLUDE) == 0
884             && (p->flags & SEC_ALLOC) != 0
885             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
886           elf_section_data (p)->dynindx = ++dynsymcount;
887         else
888           elf_section_data (p)->dynindx = 0;
889     }
890   *section_sym_count = dynsymcount;
891
892   elf_link_hash_traverse (elf_hash_table (info),
893                           elf_link_renumber_local_hash_table_dynsyms,
894                           &dynsymcount);
895
896   if (elf_hash_table (info)->dynlocal)
897     {
898       struct elf_link_local_dynamic_entry *p;
899       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
900         p->dynindx = ++dynsymcount;
901     }
902
903   elf_link_hash_traverse (elf_hash_table (info),
904                           elf_link_renumber_hash_table_dynsyms,
905                           &dynsymcount);
906
907   /* There is an unused NULL entry at the head of the table which
908      we must account for in our count.  We always create the dynsym
909      section, even if it is empty, with dynamic sections.  */
910   if (elf_hash_table (info)->dynamic_sections_created)
911     ++dynsymcount;
912
913   elf_hash_table (info)->dynsymcount = dynsymcount;
914   return dynsymcount;
915 }
916
917 /* Merge st_other field.  */
918
919 static void
920 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
921                     const Elf_Internal_Sym *isym, asection *sec,
922                     bfd_boolean definition, bfd_boolean dynamic)
923 {
924   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
925
926   /* If st_other has a processor-specific meaning, specific
927      code might be needed here.  */
928   if (bed->elf_backend_merge_symbol_attribute)
929     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
930                                                 dynamic);
931
932   if (!dynamic)
933     {
934       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
935       unsigned hvis = ELF_ST_VISIBILITY (h->other);
936
937       /* Keep the most constraining visibility.  Leave the remainder
938          of the st_other field to elf_backend_merge_symbol_attribute.  */
939       if (symvis - 1 < hvis - 1)
940         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
941     }
942   else if (definition
943            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
944            && (sec->flags & SEC_READONLY) == 0)
945     h->protected_def = 1;
946 }
947
948 /* This function is called when we want to merge a new symbol with an
949    existing symbol.  It handles the various cases which arise when we
950    find a definition in a dynamic object, or when there is already a
951    definition in a dynamic object.  The new symbol is described by
952    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
953    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
954    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
955    of an old common symbol.  We set OVERRIDE if the old symbol is
956    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
957    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
958    to change.  By OK to change, we mean that we shouldn't warn if the
959    type or size does change.  */
960
961 static bfd_boolean
962 _bfd_elf_merge_symbol (bfd *abfd,
963                        struct bfd_link_info *info,
964                        const char *name,
965                        Elf_Internal_Sym *sym,
966                        asection **psec,
967                        bfd_vma *pvalue,
968                        struct elf_link_hash_entry **sym_hash,
969                        bfd **poldbfd,
970                        bfd_boolean *pold_weak,
971                        unsigned int *pold_alignment,
972                        bfd_boolean *skip,
973                        bfd_boolean *override,
974                        bfd_boolean *type_change_ok,
975                        bfd_boolean *size_change_ok,
976                        bfd_boolean *matched)
977 {
978   asection *sec, *oldsec;
979   struct elf_link_hash_entry *h;
980   struct elf_link_hash_entry *hi;
981   struct elf_link_hash_entry *flip;
982   int bind;
983   bfd *oldbfd;
984   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
985   bfd_boolean newweak, oldweak, newfunc, oldfunc;
986   const struct elf_backend_data *bed;
987   char *new_version;
988
989   *skip = FALSE;
990   *override = FALSE;
991
992   sec = *psec;
993   bind = ELF_ST_BIND (sym->st_info);
994
995   if (! bfd_is_und_section (sec))
996     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
997   else
998     h = ((struct elf_link_hash_entry *)
999          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1000   if (h == NULL)
1001     return FALSE;
1002   *sym_hash = h;
1003
1004   bed = get_elf_backend_data (abfd);
1005
1006   /* NEW_VERSION is the symbol version of the new symbol.  */
1007   if (h->versioned != unversioned)
1008     {
1009       /* Symbol version is unknown or versioned.  */
1010       new_version = strrchr (name, ELF_VER_CHR);
1011       if (new_version)
1012         {
1013           if (h->versioned == unknown)
1014             {
1015               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1016                 h->versioned = versioned_hidden;
1017               else
1018                 h->versioned = versioned;
1019             }
1020           new_version += 1;
1021           if (new_version[0] == '\0')
1022             new_version = NULL;
1023         }
1024       else
1025         h->versioned = unversioned;
1026     }
1027   else
1028     new_version = NULL;
1029
1030   /* For merging, we only care about real symbols.  But we need to make
1031      sure that indirect symbol dynamic flags are updated.  */
1032   hi = h;
1033   while (h->root.type == bfd_link_hash_indirect
1034          || h->root.type == bfd_link_hash_warning)
1035     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1036
1037   if (!*matched)
1038     {
1039       if (hi == h || h->root.type == bfd_link_hash_new)
1040         *matched = TRUE;
1041       else
1042         {
1043           /* OLD_HIDDEN is true if the existing symbol is only visible
1044              to the symbol with the same symbol version.  NEW_HIDDEN is
1045              true if the new symbol is only visible to the symbol with
1046              the same symbol version.  */
1047           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1048           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1049           if (!old_hidden && !new_hidden)
1050             /* The new symbol matches the existing symbol if both
1051                aren't hidden.  */
1052             *matched = TRUE;
1053           else
1054             {
1055               /* OLD_VERSION is the symbol version of the existing
1056                  symbol. */
1057               char *old_version;
1058
1059               if (h->versioned >= versioned)
1060                 old_version = strrchr (h->root.root.string,
1061                                        ELF_VER_CHR) + 1;
1062               else
1063                  old_version = NULL;
1064
1065               /* The new symbol matches the existing symbol if they
1066                  have the same symbol version.  */
1067               *matched = (old_version == new_version
1068                           || (old_version != NULL
1069                               && new_version != NULL
1070                               && strcmp (old_version, new_version) == 0));
1071             }
1072         }
1073     }
1074
1075   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1076      existing symbol.  */
1077
1078   oldbfd = NULL;
1079   oldsec = NULL;
1080   switch (h->root.type)
1081     {
1082     default:
1083       break;
1084
1085     case bfd_link_hash_undefined:
1086     case bfd_link_hash_undefweak:
1087       oldbfd = h->root.u.undef.abfd;
1088       break;
1089
1090     case bfd_link_hash_defined:
1091     case bfd_link_hash_defweak:
1092       oldbfd = h->root.u.def.section->owner;
1093       oldsec = h->root.u.def.section;
1094       break;
1095
1096     case bfd_link_hash_common:
1097       oldbfd = h->root.u.c.p->section->owner;
1098       oldsec = h->root.u.c.p->section;
1099       if (pold_alignment)
1100         *pold_alignment = h->root.u.c.p->alignment_power;
1101       break;
1102     }
1103   if (poldbfd && *poldbfd == NULL)
1104     *poldbfd = oldbfd;
1105
1106   /* Differentiate strong and weak symbols.  */
1107   newweak = bind == STB_WEAK;
1108   oldweak = (h->root.type == bfd_link_hash_defweak
1109              || h->root.type == bfd_link_hash_undefweak);
1110   if (pold_weak)
1111     *pold_weak = oldweak;
1112
1113   /* This code is for coping with dynamic objects, and is only useful
1114      if we are doing an ELF link.  */
1115   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1116     return TRUE;
1117
1118   /* We have to check it for every instance since the first few may be
1119      references and not all compilers emit symbol type for undefined
1120      symbols.  */
1121   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1122
1123   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1124      respectively, is from a dynamic object.  */
1125
1126   newdyn = (abfd->flags & DYNAMIC) != 0;
1127
1128   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1129      syms and defined syms in dynamic libraries respectively.
1130      ref_dynamic on the other hand can be set for a symbol defined in
1131      a dynamic library, and def_dynamic may not be set;  When the
1132      definition in a dynamic lib is overridden by a definition in the
1133      executable use of the symbol in the dynamic lib becomes a
1134      reference to the executable symbol.  */
1135   if (newdyn)
1136     {
1137       if (bfd_is_und_section (sec))
1138         {
1139           if (bind != STB_WEAK)
1140             {
1141               h->ref_dynamic_nonweak = 1;
1142               hi->ref_dynamic_nonweak = 1;
1143             }
1144         }
1145       else
1146         {
1147           /* Update the existing symbol only if they match. */
1148           if (*matched)
1149             h->dynamic_def = 1;
1150           hi->dynamic_def = 1;
1151         }
1152     }
1153
1154   /* If we just created the symbol, mark it as being an ELF symbol.
1155      Other than that, there is nothing to do--there is no merge issue
1156      with a newly defined symbol--so we just return.  */
1157
1158   if (h->root.type == bfd_link_hash_new)
1159     {
1160       h->non_elf = 0;
1161       return TRUE;
1162     }
1163
1164   /* In cases involving weak versioned symbols, we may wind up trying
1165      to merge a symbol with itself.  Catch that here, to avoid the
1166      confusion that results if we try to override a symbol with
1167      itself.  The additional tests catch cases like
1168      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1169      dynamic object, which we do want to handle here.  */
1170   if (abfd == oldbfd
1171       && (newweak || oldweak)
1172       && ((abfd->flags & DYNAMIC) == 0
1173           || !h->def_regular))
1174     return TRUE;
1175
1176   olddyn = FALSE;
1177   if (oldbfd != NULL)
1178     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1179   else if (oldsec != NULL)
1180     {
1181       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1182          indices used by MIPS ELF.  */
1183       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1184     }
1185
1186   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1187      respectively, appear to be a definition rather than reference.  */
1188
1189   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1190
1191   olddef = (h->root.type != bfd_link_hash_undefined
1192             && h->root.type != bfd_link_hash_undefweak
1193             && h->root.type != bfd_link_hash_common);
1194
1195   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1196      respectively, appear to be a function.  */
1197
1198   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1199              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1200
1201   oldfunc = (h->type != STT_NOTYPE
1202              && bed->is_function_type (h->type));
1203
1204   /* When we try to create a default indirect symbol from the dynamic
1205      definition with the default version, we skip it if its type and
1206      the type of existing regular definition mismatch.  */
1207   if (pold_alignment == NULL
1208       && newdyn
1209       && newdef
1210       && !olddyn
1211       && (((olddef || h->root.type == bfd_link_hash_common)
1212            && ELF_ST_TYPE (sym->st_info) != h->type
1213            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1214            && h->type != STT_NOTYPE
1215            && !(newfunc && oldfunc))
1216           || (olddef
1217               && ((h->type == STT_GNU_IFUNC)
1218                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1219     {
1220       *skip = TRUE;
1221       return TRUE;
1222     }
1223
1224   /* Check TLS symbols.  We don't check undefined symbols introduced
1225      by "ld -u" which have no type (and oldbfd NULL), and we don't
1226      check symbols from plugins because they also have no type.  */
1227   if (oldbfd != NULL
1228       && (oldbfd->flags & BFD_PLUGIN) == 0
1229       && (abfd->flags & BFD_PLUGIN) == 0
1230       && ELF_ST_TYPE (sym->st_info) != h->type
1231       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1232     {
1233       bfd *ntbfd, *tbfd;
1234       bfd_boolean ntdef, tdef;
1235       asection *ntsec, *tsec;
1236
1237       if (h->type == STT_TLS)
1238         {
1239           ntbfd = abfd;
1240           ntsec = sec;
1241           ntdef = newdef;
1242           tbfd = oldbfd;
1243           tsec = oldsec;
1244           tdef = olddef;
1245         }
1246       else
1247         {
1248           ntbfd = oldbfd;
1249           ntsec = oldsec;
1250           ntdef = olddef;
1251           tbfd = abfd;
1252           tsec = sec;
1253           tdef = newdef;
1254         }
1255
1256       if (tdef && ntdef)
1257         (*_bfd_error_handler)
1258           (_("%s: TLS definition in %B section %A "
1259              "mismatches non-TLS definition in %B section %A"),
1260            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1261       else if (!tdef && !ntdef)
1262         (*_bfd_error_handler)
1263           (_("%s: TLS reference in %B "
1264              "mismatches non-TLS reference in %B"),
1265            tbfd, ntbfd, h->root.root.string);
1266       else if (tdef)
1267         (*_bfd_error_handler)
1268           (_("%s: TLS definition in %B section %A "
1269              "mismatches non-TLS reference in %B"),
1270            tbfd, tsec, ntbfd, h->root.root.string);
1271       else
1272         (*_bfd_error_handler)
1273           (_("%s: TLS reference in %B "
1274              "mismatches non-TLS definition in %B section %A"),
1275            tbfd, ntbfd, ntsec, h->root.root.string);
1276
1277       bfd_set_error (bfd_error_bad_value);
1278       return FALSE;
1279     }
1280
1281   /* If the old symbol has non-default visibility, we ignore the new
1282      definition from a dynamic object.  */
1283   if (newdyn
1284       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1285       && !bfd_is_und_section (sec))
1286     {
1287       *skip = TRUE;
1288       /* Make sure this symbol is dynamic.  */
1289       h->ref_dynamic = 1;
1290       hi->ref_dynamic = 1;
1291       /* A protected symbol has external availability. Make sure it is
1292          recorded as dynamic.
1293
1294          FIXME: Should we check type and size for protected symbol?  */
1295       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1296         return bfd_elf_link_record_dynamic_symbol (info, h);
1297       else
1298         return TRUE;
1299     }
1300   else if (!newdyn
1301            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1302            && h->def_dynamic)
1303     {
1304       /* If the new symbol with non-default visibility comes from a
1305          relocatable file and the old definition comes from a dynamic
1306          object, we remove the old definition.  */
1307       if (hi->root.type == bfd_link_hash_indirect)
1308         {
1309           /* Handle the case where the old dynamic definition is
1310              default versioned.  We need to copy the symbol info from
1311              the symbol with default version to the normal one if it
1312              was referenced before.  */
1313           if (h->ref_regular)
1314             {
1315               hi->root.type = h->root.type;
1316               h->root.type = bfd_link_hash_indirect;
1317               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1318
1319               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1320               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1321                 {
1322                   /* If the new symbol is hidden or internal, completely undo
1323                      any dynamic link state.  */
1324                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1325                   h->forced_local = 0;
1326                   h->ref_dynamic = 0;
1327                 }
1328               else
1329                 h->ref_dynamic = 1;
1330
1331               h->def_dynamic = 0;
1332               /* FIXME: Should we check type and size for protected symbol?  */
1333               h->size = 0;
1334               h->type = 0;
1335
1336               h = hi;
1337             }
1338           else
1339             h = hi;
1340         }
1341
1342       /* If the old symbol was undefined before, then it will still be
1343          on the undefs list.  If the new symbol is undefined or
1344          common, we can't make it bfd_link_hash_new here, because new
1345          undefined or common symbols will be added to the undefs list
1346          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1347          added twice to the undefs list.  Also, if the new symbol is
1348          undefweak then we don't want to lose the strong undef.  */
1349       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1350         {
1351           h->root.type = bfd_link_hash_undefined;
1352           h->root.u.undef.abfd = abfd;
1353         }
1354       else
1355         {
1356           h->root.type = bfd_link_hash_new;
1357           h->root.u.undef.abfd = NULL;
1358         }
1359
1360       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1361         {
1362           /* If the new symbol is hidden or internal, completely undo
1363              any dynamic link state.  */
1364           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1365           h->forced_local = 0;
1366           h->ref_dynamic = 0;
1367         }
1368       else
1369         h->ref_dynamic = 1;
1370       h->def_dynamic = 0;
1371       /* FIXME: Should we check type and size for protected symbol?  */
1372       h->size = 0;
1373       h->type = 0;
1374       return TRUE;
1375     }
1376
1377   /* If a new weak symbol definition comes from a regular file and the
1378      old symbol comes from a dynamic library, we treat the new one as
1379      strong.  Similarly, an old weak symbol definition from a regular
1380      file is treated as strong when the new symbol comes from a dynamic
1381      library.  Further, an old weak symbol from a dynamic library is
1382      treated as strong if the new symbol is from a dynamic library.
1383      This reflects the way glibc's ld.so works.
1384
1385      Do this before setting *type_change_ok or *size_change_ok so that
1386      we warn properly when dynamic library symbols are overridden.  */
1387
1388   if (newdef && !newdyn && olddyn)
1389     newweak = FALSE;
1390   if (olddef && newdyn)
1391     oldweak = FALSE;
1392
1393   /* Allow changes between different types of function symbol.  */
1394   if (newfunc && oldfunc)
1395     *type_change_ok = TRUE;
1396
1397   /* It's OK to change the type if either the existing symbol or the
1398      new symbol is weak.  A type change is also OK if the old symbol
1399      is undefined and the new symbol is defined.  */
1400
1401   if (oldweak
1402       || newweak
1403       || (newdef
1404           && h->root.type == bfd_link_hash_undefined))
1405     *type_change_ok = TRUE;
1406
1407   /* It's OK to change the size if either the existing symbol or the
1408      new symbol is weak, or if the old symbol is undefined.  */
1409
1410   if (*type_change_ok
1411       || h->root.type == bfd_link_hash_undefined)
1412     *size_change_ok = TRUE;
1413
1414   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1415      symbol, respectively, appears to be a common symbol in a dynamic
1416      object.  If a symbol appears in an uninitialized section, and is
1417      not weak, and is not a function, then it may be a common symbol
1418      which was resolved when the dynamic object was created.  We want
1419      to treat such symbols specially, because they raise special
1420      considerations when setting the symbol size: if the symbol
1421      appears as a common symbol in a regular object, and the size in
1422      the regular object is larger, we must make sure that we use the
1423      larger size.  This problematic case can always be avoided in C,
1424      but it must be handled correctly when using Fortran shared
1425      libraries.
1426
1427      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1428      likewise for OLDDYNCOMMON and OLDDEF.
1429
1430      Note that this test is just a heuristic, and that it is quite
1431      possible to have an uninitialized symbol in a shared object which
1432      is really a definition, rather than a common symbol.  This could
1433      lead to some minor confusion when the symbol really is a common
1434      symbol in some regular object.  However, I think it will be
1435      harmless.  */
1436
1437   if (newdyn
1438       && newdef
1439       && !newweak
1440       && (sec->flags & SEC_ALLOC) != 0
1441       && (sec->flags & SEC_LOAD) == 0
1442       && sym->st_size > 0
1443       && !newfunc)
1444     newdyncommon = TRUE;
1445   else
1446     newdyncommon = FALSE;
1447
1448   if (olddyn
1449       && olddef
1450       && h->root.type == bfd_link_hash_defined
1451       && h->def_dynamic
1452       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1453       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1454       && h->size > 0
1455       && !oldfunc)
1456     olddyncommon = TRUE;
1457   else
1458     olddyncommon = FALSE;
1459
1460   /* We now know everything about the old and new symbols.  We ask the
1461      backend to check if we can merge them.  */
1462   if (bed->merge_symbol != NULL)
1463     {
1464       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1465         return FALSE;
1466       sec = *psec;
1467     }
1468
1469   /* If both the old and the new symbols look like common symbols in a
1470      dynamic object, set the size of the symbol to the larger of the
1471      two.  */
1472
1473   if (olddyncommon
1474       && newdyncommon
1475       && sym->st_size != h->size)
1476     {
1477       /* Since we think we have two common symbols, issue a multiple
1478          common warning if desired.  Note that we only warn if the
1479          size is different.  If the size is the same, we simply let
1480          the old symbol override the new one as normally happens with
1481          symbols defined in dynamic objects.  */
1482
1483       if (! ((*info->callbacks->multiple_common)
1484              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1485         return FALSE;
1486
1487       if (sym->st_size > h->size)
1488         h->size = sym->st_size;
1489
1490       *size_change_ok = TRUE;
1491     }
1492
1493   /* If we are looking at a dynamic object, and we have found a
1494      definition, we need to see if the symbol was already defined by
1495      some other object.  If so, we want to use the existing
1496      definition, and we do not want to report a multiple symbol
1497      definition error; we do this by clobbering *PSEC to be
1498      bfd_und_section_ptr.
1499
1500      We treat a common symbol as a definition if the symbol in the
1501      shared library is a function, since common symbols always
1502      represent variables; this can cause confusion in principle, but
1503      any such confusion would seem to indicate an erroneous program or
1504      shared library.  We also permit a common symbol in a regular
1505      object to override a weak symbol in a shared object.  A common
1506      symbol in executable also overrides a symbol in a shared object.  */
1507
1508   if (newdyn
1509       && newdef
1510       && (olddef
1511           || (h->root.type == bfd_link_hash_common
1512               && (newweak
1513                   || newfunc
1514                   || (!olddyn && bfd_link_executable (info))))))
1515     {
1516       *override = TRUE;
1517       newdef = FALSE;
1518       newdyncommon = FALSE;
1519
1520       *psec = sec = bfd_und_section_ptr;
1521       *size_change_ok = TRUE;
1522
1523       /* If we get here when the old symbol is a common symbol, then
1524          we are explicitly letting it override a weak symbol or
1525          function in a dynamic object, and we don't want to warn about
1526          a type change.  If the old symbol is a defined symbol, a type
1527          change warning may still be appropriate.  */
1528
1529       if (h->root.type == bfd_link_hash_common)
1530         *type_change_ok = TRUE;
1531     }
1532
1533   /* Handle the special case of an old common symbol merging with a
1534      new symbol which looks like a common symbol in a shared object.
1535      We change *PSEC and *PVALUE to make the new symbol look like a
1536      common symbol, and let _bfd_generic_link_add_one_symbol do the
1537      right thing.  */
1538
1539   if (newdyncommon
1540       && h->root.type == bfd_link_hash_common)
1541     {
1542       *override = TRUE;
1543       newdef = FALSE;
1544       newdyncommon = FALSE;
1545       *pvalue = sym->st_size;
1546       *psec = sec = bed->common_section (oldsec);
1547       *size_change_ok = TRUE;
1548     }
1549
1550   /* Skip weak definitions of symbols that are already defined.  */
1551   if (newdef && olddef && newweak)
1552     {
1553       /* Don't skip new non-IR weak syms.  */
1554       if (!(oldbfd != NULL
1555             && (oldbfd->flags & BFD_PLUGIN) != 0
1556             && (abfd->flags & BFD_PLUGIN) == 0))
1557         {
1558           newdef = FALSE;
1559           *skip = TRUE;
1560         }
1561
1562       /* Merge st_other.  If the symbol already has a dynamic index,
1563          but visibility says it should not be visible, turn it into a
1564          local symbol.  */
1565       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1566       if (h->dynindx != -1)
1567         switch (ELF_ST_VISIBILITY (h->other))
1568           {
1569           case STV_INTERNAL:
1570           case STV_HIDDEN:
1571             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1572             break;
1573           }
1574     }
1575
1576   /* If the old symbol is from a dynamic object, and the new symbol is
1577      a definition which is not from a dynamic object, then the new
1578      symbol overrides the old symbol.  Symbols from regular files
1579      always take precedence over symbols from dynamic objects, even if
1580      they are defined after the dynamic object in the link.
1581
1582      As above, we again permit a common symbol in a regular object to
1583      override a definition in a shared object if the shared object
1584      symbol is a function or is weak.  */
1585
1586   flip = NULL;
1587   if (!newdyn
1588       && (newdef
1589           || (bfd_is_com_section (sec)
1590               && (oldweak || oldfunc)))
1591       && olddyn
1592       && olddef
1593       && h->def_dynamic)
1594     {
1595       /* Change the hash table entry to undefined, and let
1596          _bfd_generic_link_add_one_symbol do the right thing with the
1597          new definition.  */
1598
1599       h->root.type = bfd_link_hash_undefined;
1600       h->root.u.undef.abfd = h->root.u.def.section->owner;
1601       *size_change_ok = TRUE;
1602
1603       olddef = FALSE;
1604       olddyncommon = FALSE;
1605
1606       /* We again permit a type change when a common symbol may be
1607          overriding a function.  */
1608
1609       if (bfd_is_com_section (sec))
1610         {
1611           if (oldfunc)
1612             {
1613               /* If a common symbol overrides a function, make sure
1614                  that it isn't defined dynamically nor has type
1615                  function.  */
1616               h->def_dynamic = 0;
1617               h->type = STT_NOTYPE;
1618             }
1619           *type_change_ok = TRUE;
1620         }
1621
1622       if (hi->root.type == bfd_link_hash_indirect)
1623         flip = hi;
1624       else
1625         /* This union may have been set to be non-NULL when this symbol
1626            was seen in a dynamic object.  We must force the union to be
1627            NULL, so that it is correct for a regular symbol.  */
1628         h->verinfo.vertree = NULL;
1629     }
1630
1631   /* Handle the special case of a new common symbol merging with an
1632      old symbol that looks like it might be a common symbol defined in
1633      a shared object.  Note that we have already handled the case in
1634      which a new common symbol should simply override the definition
1635      in the shared library.  */
1636
1637   if (! newdyn
1638       && bfd_is_com_section (sec)
1639       && olddyncommon)
1640     {
1641       /* It would be best if we could set the hash table entry to a
1642          common symbol, but we don't know what to use for the section
1643          or the alignment.  */
1644       if (! ((*info->callbacks->multiple_common)
1645              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1646         return FALSE;
1647
1648       /* If the presumed common symbol in the dynamic object is
1649          larger, pretend that the new symbol has its size.  */
1650
1651       if (h->size > *pvalue)
1652         *pvalue = h->size;
1653
1654       /* We need to remember the alignment required by the symbol
1655          in the dynamic object.  */
1656       BFD_ASSERT (pold_alignment);
1657       *pold_alignment = h->root.u.def.section->alignment_power;
1658
1659       olddef = FALSE;
1660       olddyncommon = FALSE;
1661
1662       h->root.type = bfd_link_hash_undefined;
1663       h->root.u.undef.abfd = h->root.u.def.section->owner;
1664
1665       *size_change_ok = TRUE;
1666       *type_change_ok = TRUE;
1667
1668       if (hi->root.type == bfd_link_hash_indirect)
1669         flip = hi;
1670       else
1671         h->verinfo.vertree = NULL;
1672     }
1673
1674   if (flip != NULL)
1675     {
1676       /* Handle the case where we had a versioned symbol in a dynamic
1677          library and now find a definition in a normal object.  In this
1678          case, we make the versioned symbol point to the normal one.  */
1679       flip->root.type = h->root.type;
1680       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1681       h->root.type = bfd_link_hash_indirect;
1682       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1683       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1684       if (h->def_dynamic)
1685         {
1686           h->def_dynamic = 0;
1687           flip->ref_dynamic = 1;
1688         }
1689     }
1690
1691   return TRUE;
1692 }
1693
1694 /* This function is called to create an indirect symbol from the
1695    default for the symbol with the default version if needed. The
1696    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1697    set DYNSYM if the new indirect symbol is dynamic.  */
1698
1699 static bfd_boolean
1700 _bfd_elf_add_default_symbol (bfd *abfd,
1701                              struct bfd_link_info *info,
1702                              struct elf_link_hash_entry *h,
1703                              const char *name,
1704                              Elf_Internal_Sym *sym,
1705                              asection *sec,
1706                              bfd_vma value,
1707                              bfd **poldbfd,
1708                              bfd_boolean *dynsym)
1709 {
1710   bfd_boolean type_change_ok;
1711   bfd_boolean size_change_ok;
1712   bfd_boolean skip;
1713   char *shortname;
1714   struct elf_link_hash_entry *hi;
1715   struct bfd_link_hash_entry *bh;
1716   const struct elf_backend_data *bed;
1717   bfd_boolean collect;
1718   bfd_boolean dynamic;
1719   bfd_boolean override;
1720   char *p;
1721   size_t len, shortlen;
1722   asection *tmp_sec;
1723   bfd_boolean matched;
1724
1725   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1726     return TRUE;
1727
1728   /* If this symbol has a version, and it is the default version, we
1729      create an indirect symbol from the default name to the fully
1730      decorated name.  This will cause external references which do not
1731      specify a version to be bound to this version of the symbol.  */
1732   p = strchr (name, ELF_VER_CHR);
1733   if (h->versioned == unknown)
1734     {
1735       if (p == NULL)
1736         {
1737           h->versioned = unversioned;
1738           return TRUE;
1739         }
1740       else
1741         {
1742           if (p[1] != ELF_VER_CHR)
1743             {
1744               h->versioned = versioned_hidden;
1745               return TRUE;
1746             }
1747           else
1748             h->versioned = versioned;
1749         }
1750     }
1751   else
1752     {
1753       /* PR ld/19073: We may see an unversioned definition after the
1754          default version.  */
1755       if (p == NULL)
1756         return TRUE;
1757     }
1758
1759   bed = get_elf_backend_data (abfd);
1760   collect = bed->collect;
1761   dynamic = (abfd->flags & DYNAMIC) != 0;
1762
1763   shortlen = p - name;
1764   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1765   if (shortname == NULL)
1766     return FALSE;
1767   memcpy (shortname, name, shortlen);
1768   shortname[shortlen] = '\0';
1769
1770   /* We are going to create a new symbol.  Merge it with any existing
1771      symbol with this name.  For the purposes of the merge, act as
1772      though we were defining the symbol we just defined, although we
1773      actually going to define an indirect symbol.  */
1774   type_change_ok = FALSE;
1775   size_change_ok = FALSE;
1776   matched = TRUE;
1777   tmp_sec = sec;
1778   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1779                               &hi, poldbfd, NULL, NULL, &skip, &override,
1780                               &type_change_ok, &size_change_ok, &matched))
1781     return FALSE;
1782
1783   if (skip)
1784     goto nondefault;
1785
1786   if (! override)
1787     {
1788       /* Add the default symbol if not performing a relocatable link.  */
1789       if (! bfd_link_relocatable (info))
1790         {
1791           bh = &hi->root;
1792           if (! (_bfd_generic_link_add_one_symbol
1793                  (info, abfd, shortname, BSF_INDIRECT,
1794                   bfd_ind_section_ptr,
1795                   0, name, FALSE, collect, &bh)))
1796             return FALSE;
1797           hi = (struct elf_link_hash_entry *) bh;
1798         }
1799     }
1800   else
1801     {
1802       /* In this case the symbol named SHORTNAME is overriding the
1803          indirect symbol we want to add.  We were planning on making
1804          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1805          is the name without a version.  NAME is the fully versioned
1806          name, and it is the default version.
1807
1808          Overriding means that we already saw a definition for the
1809          symbol SHORTNAME in a regular object, and it is overriding
1810          the symbol defined in the dynamic object.
1811
1812          When this happens, we actually want to change NAME, the
1813          symbol we just added, to refer to SHORTNAME.  This will cause
1814          references to NAME in the shared object to become references
1815          to SHORTNAME in the regular object.  This is what we expect
1816          when we override a function in a shared object: that the
1817          references in the shared object will be mapped to the
1818          definition in the regular object.  */
1819
1820       while (hi->root.type == bfd_link_hash_indirect
1821              || hi->root.type == bfd_link_hash_warning)
1822         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1823
1824       h->root.type = bfd_link_hash_indirect;
1825       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1826       if (h->def_dynamic)
1827         {
1828           h->def_dynamic = 0;
1829           hi->ref_dynamic = 1;
1830           if (hi->ref_regular
1831               || hi->def_regular)
1832             {
1833               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1834                 return FALSE;
1835             }
1836         }
1837
1838       /* Now set HI to H, so that the following code will set the
1839          other fields correctly.  */
1840       hi = h;
1841     }
1842
1843   /* Check if HI is a warning symbol.  */
1844   if (hi->root.type == bfd_link_hash_warning)
1845     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1846
1847   /* If there is a duplicate definition somewhere, then HI may not
1848      point to an indirect symbol.  We will have reported an error to
1849      the user in that case.  */
1850
1851   if (hi->root.type == bfd_link_hash_indirect)
1852     {
1853       struct elf_link_hash_entry *ht;
1854
1855       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1856       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1857
1858       /* A reference to the SHORTNAME symbol from a dynamic library
1859          will be satisfied by the versioned symbol at runtime.  In
1860          effect, we have a reference to the versioned symbol.  */
1861       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1862       hi->dynamic_def |= ht->dynamic_def;
1863
1864       /* See if the new flags lead us to realize that the symbol must
1865          be dynamic.  */
1866       if (! *dynsym)
1867         {
1868           if (! dynamic)
1869             {
1870               if (! bfd_link_executable (info)
1871                   || hi->def_dynamic
1872                   || hi->ref_dynamic)
1873                 *dynsym = TRUE;
1874             }
1875           else
1876             {
1877               if (hi->ref_regular)
1878                 *dynsym = TRUE;
1879             }
1880         }
1881     }
1882
1883   /* We also need to define an indirection from the nondefault version
1884      of the symbol.  */
1885
1886 nondefault:
1887   len = strlen (name);
1888   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1889   if (shortname == NULL)
1890     return FALSE;
1891   memcpy (shortname, name, shortlen);
1892   memcpy (shortname + shortlen, p + 1, len - shortlen);
1893
1894   /* Once again, merge with any existing symbol.  */
1895   type_change_ok = FALSE;
1896   size_change_ok = FALSE;
1897   tmp_sec = sec;
1898   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1899                               &hi, poldbfd, NULL, NULL, &skip, &override,
1900                               &type_change_ok, &size_change_ok, &matched))
1901     return FALSE;
1902
1903   if (skip)
1904     return TRUE;
1905
1906   if (override)
1907     {
1908       /* Here SHORTNAME is a versioned name, so we don't expect to see
1909          the type of override we do in the case above unless it is
1910          overridden by a versioned definition.  */
1911       if (hi->root.type != bfd_link_hash_defined
1912           && hi->root.type != bfd_link_hash_defweak)
1913         (*_bfd_error_handler)
1914           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1915            abfd, shortname);
1916     }
1917   else
1918     {
1919       bh = &hi->root;
1920       if (! (_bfd_generic_link_add_one_symbol
1921              (info, abfd, shortname, BSF_INDIRECT,
1922               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1923         return FALSE;
1924       hi = (struct elf_link_hash_entry *) bh;
1925
1926       /* If there is a duplicate definition somewhere, then HI may not
1927          point to an indirect symbol.  We will have reported an error
1928          to the user in that case.  */
1929
1930       if (hi->root.type == bfd_link_hash_indirect)
1931         {
1932           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1933           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1934           hi->dynamic_def |= h->dynamic_def;
1935
1936           /* See if the new flags lead us to realize that the symbol
1937              must be dynamic.  */
1938           if (! *dynsym)
1939             {
1940               if (! dynamic)
1941                 {
1942                   if (! bfd_link_executable (info)
1943                       || hi->ref_dynamic)
1944                     *dynsym = TRUE;
1945                 }
1946               else
1947                 {
1948                   if (hi->ref_regular)
1949                     *dynsym = TRUE;
1950                 }
1951             }
1952         }
1953     }
1954
1955   return TRUE;
1956 }
1957 \f
1958 /* This routine is used to export all defined symbols into the dynamic
1959    symbol table.  It is called via elf_link_hash_traverse.  */
1960
1961 static bfd_boolean
1962 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1963 {
1964   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1965
1966   /* Ignore indirect symbols.  These are added by the versioning code.  */
1967   if (h->root.type == bfd_link_hash_indirect)
1968     return TRUE;
1969
1970   /* Ignore this if we won't export it.  */
1971   if (!eif->info->export_dynamic && !h->dynamic)
1972     return TRUE;
1973
1974   if (h->dynindx == -1
1975       && (h->def_regular || h->ref_regular)
1976       && ! bfd_hide_sym_by_version (eif->info->version_info,
1977                                     h->root.root.string))
1978     {
1979       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1980         {
1981           eif->failed = TRUE;
1982           return FALSE;
1983         }
1984     }
1985
1986   return TRUE;
1987 }
1988 \f
1989 /* Look through the symbols which are defined in other shared
1990    libraries and referenced here.  Update the list of version
1991    dependencies.  This will be put into the .gnu.version_r section.
1992    This function is called via elf_link_hash_traverse.  */
1993
1994 static bfd_boolean
1995 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1996                                          void *data)
1997 {
1998   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
1999   Elf_Internal_Verneed *t;
2000   Elf_Internal_Vernaux *a;
2001   bfd_size_type amt;
2002
2003   /* We only care about symbols defined in shared objects with version
2004      information.  */
2005   if (!h->def_dynamic
2006       || h->def_regular
2007       || h->dynindx == -1
2008       || h->verinfo.verdef == NULL
2009       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2010           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2011     return TRUE;
2012
2013   /* See if we already know about this version.  */
2014   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2015        t != NULL;
2016        t = t->vn_nextref)
2017     {
2018       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2019         continue;
2020
2021       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2022         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2023           return TRUE;
2024
2025       break;
2026     }
2027
2028   /* This is a new version.  Add it to tree we are building.  */
2029
2030   if (t == NULL)
2031     {
2032       amt = sizeof *t;
2033       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2034       if (t == NULL)
2035         {
2036           rinfo->failed = TRUE;
2037           return FALSE;
2038         }
2039
2040       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2041       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2042       elf_tdata (rinfo->info->output_bfd)->verref = t;
2043     }
2044
2045   amt = sizeof *a;
2046   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2047   if (a == NULL)
2048     {
2049       rinfo->failed = TRUE;
2050       return FALSE;
2051     }
2052
2053   /* Note that we are copying a string pointer here, and testing it
2054      above.  If bfd_elf_string_from_elf_section is ever changed to
2055      discard the string data when low in memory, this will have to be
2056      fixed.  */
2057   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2058
2059   a->vna_flags = h->verinfo.verdef->vd_flags;
2060   a->vna_nextptr = t->vn_auxptr;
2061
2062   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2063   ++rinfo->vers;
2064
2065   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2066
2067   t->vn_auxptr = a;
2068
2069   return TRUE;
2070 }
2071
2072 /* Figure out appropriate versions for all the symbols.  We may not
2073    have the version number script until we have read all of the input
2074    files, so until that point we don't know which symbols should be
2075    local.  This function is called via elf_link_hash_traverse.  */
2076
2077 static bfd_boolean
2078 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2079 {
2080   struct elf_info_failed *sinfo;
2081   struct bfd_link_info *info;
2082   const struct elf_backend_data *bed;
2083   struct elf_info_failed eif;
2084   char *p;
2085   bfd_size_type amt;
2086
2087   sinfo = (struct elf_info_failed *) data;
2088   info = sinfo->info;
2089
2090   /* Fix the symbol flags.  */
2091   eif.failed = FALSE;
2092   eif.info = info;
2093   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2094     {
2095       if (eif.failed)
2096         sinfo->failed = TRUE;
2097       return FALSE;
2098     }
2099
2100   /* We only need version numbers for symbols defined in regular
2101      objects.  */
2102   if (!h->def_regular)
2103     return TRUE;
2104
2105   bed = get_elf_backend_data (info->output_bfd);
2106   p = strchr (h->root.root.string, ELF_VER_CHR);
2107   if (p != NULL && h->verinfo.vertree == NULL)
2108     {
2109       struct bfd_elf_version_tree *t;
2110
2111       ++p;
2112       if (*p == ELF_VER_CHR)
2113         ++p;
2114
2115       /* If there is no version string, we can just return out.  */
2116       if (*p == '\0')
2117         return TRUE;
2118
2119       /* Look for the version.  If we find it, it is no longer weak.  */
2120       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2121         {
2122           if (strcmp (t->name, p) == 0)
2123             {
2124               size_t len;
2125               char *alc;
2126               struct bfd_elf_version_expr *d;
2127
2128               len = p - h->root.root.string;
2129               alc = (char *) bfd_malloc (len);
2130               if (alc == NULL)
2131                 {
2132                   sinfo->failed = TRUE;
2133                   return FALSE;
2134                 }
2135               memcpy (alc, h->root.root.string, len - 1);
2136               alc[len - 1] = '\0';
2137               if (alc[len - 2] == ELF_VER_CHR)
2138                 alc[len - 2] = '\0';
2139
2140               h->verinfo.vertree = t;
2141               t->used = TRUE;
2142               d = NULL;
2143
2144               if (t->globals.list != NULL)
2145                 d = (*t->match) (&t->globals, NULL, alc);
2146
2147               /* See if there is anything to force this symbol to
2148                  local scope.  */
2149               if (d == NULL && t->locals.list != NULL)
2150                 {
2151                   d = (*t->match) (&t->locals, NULL, alc);
2152                   if (d != NULL
2153                       && h->dynindx != -1
2154                       && ! info->export_dynamic)
2155                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2156                 }
2157
2158               free (alc);
2159               break;
2160             }
2161         }
2162
2163       /* If we are building an application, we need to create a
2164          version node for this version.  */
2165       if (t == NULL && bfd_link_executable (info))
2166         {
2167           struct bfd_elf_version_tree **pp;
2168           int version_index;
2169
2170           /* If we aren't going to export this symbol, we don't need
2171              to worry about it.  */
2172           if (h->dynindx == -1)
2173             return TRUE;
2174
2175           amt = sizeof *t;
2176           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2177           if (t == NULL)
2178             {
2179               sinfo->failed = TRUE;
2180               return FALSE;
2181             }
2182
2183           t->name = p;
2184           t->name_indx = (unsigned int) -1;
2185           t->used = TRUE;
2186
2187           version_index = 1;
2188           /* Don't count anonymous version tag.  */
2189           if (sinfo->info->version_info != NULL
2190               && sinfo->info->version_info->vernum == 0)
2191             version_index = 0;
2192           for (pp = &sinfo->info->version_info;
2193                *pp != NULL;
2194                pp = &(*pp)->next)
2195             ++version_index;
2196           t->vernum = version_index;
2197
2198           *pp = t;
2199
2200           h->verinfo.vertree = t;
2201         }
2202       else if (t == NULL)
2203         {
2204           /* We could not find the version for a symbol when
2205              generating a shared archive.  Return an error.  */
2206           (*_bfd_error_handler)
2207             (_("%B: version node not found for symbol %s"),
2208              info->output_bfd, h->root.root.string);
2209           bfd_set_error (bfd_error_bad_value);
2210           sinfo->failed = TRUE;
2211           return FALSE;
2212         }
2213     }
2214
2215   /* If we don't have a version for this symbol, see if we can find
2216      something.  */
2217   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2218     {
2219       bfd_boolean hide;
2220
2221       h->verinfo.vertree
2222         = bfd_find_version_for_sym (sinfo->info->version_info,
2223                                     h->root.root.string, &hide);
2224       if (h->verinfo.vertree != NULL && hide)
2225         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2226     }
2227
2228   return TRUE;
2229 }
2230 \f
2231 /* Read and swap the relocs from the section indicated by SHDR.  This
2232    may be either a REL or a RELA section.  The relocations are
2233    translated into RELA relocations and stored in INTERNAL_RELOCS,
2234    which should have already been allocated to contain enough space.
2235    The EXTERNAL_RELOCS are a buffer where the external form of the
2236    relocations should be stored.
2237
2238    Returns FALSE if something goes wrong.  */
2239
2240 static bfd_boolean
2241 elf_link_read_relocs_from_section (bfd *abfd,
2242                                    asection *sec,
2243                                    Elf_Internal_Shdr *shdr,
2244                                    void *external_relocs,
2245                                    Elf_Internal_Rela *internal_relocs)
2246 {
2247   const struct elf_backend_data *bed;
2248   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2249   const bfd_byte *erela;
2250   const bfd_byte *erelaend;
2251   Elf_Internal_Rela *irela;
2252   Elf_Internal_Shdr *symtab_hdr;
2253   size_t nsyms;
2254
2255   /* Position ourselves at the start of the section.  */
2256   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2257     return FALSE;
2258
2259   /* Read the relocations.  */
2260   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2261     return FALSE;
2262
2263   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2264   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2265
2266   bed = get_elf_backend_data (abfd);
2267
2268   /* Convert the external relocations to the internal format.  */
2269   if (shdr->sh_entsize == bed->s->sizeof_rel)
2270     swap_in = bed->s->swap_reloc_in;
2271   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2272     swap_in = bed->s->swap_reloca_in;
2273   else
2274     {
2275       bfd_set_error (bfd_error_wrong_format);
2276       return FALSE;
2277     }
2278
2279   erela = (const bfd_byte *) external_relocs;
2280   erelaend = erela + shdr->sh_size;
2281   irela = internal_relocs;
2282   while (erela < erelaend)
2283     {
2284       bfd_vma r_symndx;
2285
2286       (*swap_in) (abfd, erela, irela);
2287       r_symndx = ELF32_R_SYM (irela->r_info);
2288       if (bed->s->arch_size == 64)
2289         r_symndx >>= 24;
2290       if (nsyms > 0)
2291         {
2292           if ((size_t) r_symndx >= nsyms)
2293             {
2294               (*_bfd_error_handler)
2295                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2296                    " for offset 0x%lx in section `%A'"),
2297                  abfd, sec,
2298                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2299               bfd_set_error (bfd_error_bad_value);
2300               return FALSE;
2301             }
2302         }
2303       else if (r_symndx != STN_UNDEF)
2304         {
2305           (*_bfd_error_handler)
2306             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2307                " when the object file has no symbol table"),
2308              abfd, sec,
2309              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2310           bfd_set_error (bfd_error_bad_value);
2311           return FALSE;
2312         }
2313       irela += bed->s->int_rels_per_ext_rel;
2314       erela += shdr->sh_entsize;
2315     }
2316
2317   return TRUE;
2318 }
2319
2320 /* Read and swap the relocs for a section O.  They may have been
2321    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2322    not NULL, they are used as buffers to read into.  They are known to
2323    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2324    the return value is allocated using either malloc or bfd_alloc,
2325    according to the KEEP_MEMORY argument.  If O has two relocation
2326    sections (both REL and RELA relocations), then the REL_HDR
2327    relocations will appear first in INTERNAL_RELOCS, followed by the
2328    RELA_HDR relocations.  */
2329
2330 Elf_Internal_Rela *
2331 _bfd_elf_link_read_relocs (bfd *abfd,
2332                            asection *o,
2333                            void *external_relocs,
2334                            Elf_Internal_Rela *internal_relocs,
2335                            bfd_boolean keep_memory)
2336 {
2337   void *alloc1 = NULL;
2338   Elf_Internal_Rela *alloc2 = NULL;
2339   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2340   struct bfd_elf_section_data *esdo = elf_section_data (o);
2341   Elf_Internal_Rela *internal_rela_relocs;
2342
2343   if (esdo->relocs != NULL)
2344     return esdo->relocs;
2345
2346   if (o->reloc_count == 0)
2347     return NULL;
2348
2349   if (internal_relocs == NULL)
2350     {
2351       bfd_size_type size;
2352
2353       size = o->reloc_count;
2354       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2355       if (keep_memory)
2356         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2357       else
2358         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2359       if (internal_relocs == NULL)
2360         goto error_return;
2361     }
2362
2363   if (external_relocs == NULL)
2364     {
2365       bfd_size_type size = 0;
2366
2367       if (esdo->rel.hdr)
2368         size += esdo->rel.hdr->sh_size;
2369       if (esdo->rela.hdr)
2370         size += esdo->rela.hdr->sh_size;
2371
2372       alloc1 = bfd_malloc (size);
2373       if (alloc1 == NULL)
2374         goto error_return;
2375       external_relocs = alloc1;
2376     }
2377
2378   internal_rela_relocs = internal_relocs;
2379   if (esdo->rel.hdr)
2380     {
2381       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2382                                               external_relocs,
2383                                               internal_relocs))
2384         goto error_return;
2385       external_relocs = (((bfd_byte *) external_relocs)
2386                          + esdo->rel.hdr->sh_size);
2387       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2388                                * bed->s->int_rels_per_ext_rel);
2389     }
2390
2391   if (esdo->rela.hdr
2392       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2393                                               external_relocs,
2394                                               internal_rela_relocs)))
2395     goto error_return;
2396
2397   /* Cache the results for next time, if we can.  */
2398   if (keep_memory)
2399     esdo->relocs = internal_relocs;
2400
2401   if (alloc1 != NULL)
2402     free (alloc1);
2403
2404   /* Don't free alloc2, since if it was allocated we are passing it
2405      back (under the name of internal_relocs).  */
2406
2407   return internal_relocs;
2408
2409  error_return:
2410   if (alloc1 != NULL)
2411     free (alloc1);
2412   if (alloc2 != NULL)
2413     {
2414       if (keep_memory)
2415         bfd_release (abfd, alloc2);
2416       else
2417         free (alloc2);
2418     }
2419   return NULL;
2420 }
2421
2422 /* Compute the size of, and allocate space for, REL_HDR which is the
2423    section header for a section containing relocations for O.  */
2424
2425 static bfd_boolean
2426 _bfd_elf_link_size_reloc_section (bfd *abfd,
2427                                   struct bfd_elf_section_reloc_data *reldata)
2428 {
2429   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2430
2431   /* That allows us to calculate the size of the section.  */
2432   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2433
2434   /* The contents field must last into write_object_contents, so we
2435      allocate it with bfd_alloc rather than malloc.  Also since we
2436      cannot be sure that the contents will actually be filled in,
2437      we zero the allocated space.  */
2438   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2439   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2440     return FALSE;
2441
2442   if (reldata->hashes == NULL && reldata->count)
2443     {
2444       struct elf_link_hash_entry **p;
2445
2446       p = ((struct elf_link_hash_entry **)
2447            bfd_zmalloc (reldata->count * sizeof (*p)));
2448       if (p == NULL)
2449         return FALSE;
2450
2451       reldata->hashes = p;
2452     }
2453
2454   return TRUE;
2455 }
2456
2457 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2458    originated from the section given by INPUT_REL_HDR) to the
2459    OUTPUT_BFD.  */
2460
2461 bfd_boolean
2462 _bfd_elf_link_output_relocs (bfd *output_bfd,
2463                              asection *input_section,
2464                              Elf_Internal_Shdr *input_rel_hdr,
2465                              Elf_Internal_Rela *internal_relocs,
2466                              struct elf_link_hash_entry **rel_hash
2467                                ATTRIBUTE_UNUSED)
2468 {
2469   Elf_Internal_Rela *irela;
2470   Elf_Internal_Rela *irelaend;
2471   bfd_byte *erel;
2472   struct bfd_elf_section_reloc_data *output_reldata;
2473   asection *output_section;
2474   const struct elf_backend_data *bed;
2475   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2476   struct bfd_elf_section_data *esdo;
2477
2478   output_section = input_section->output_section;
2479
2480   bed = get_elf_backend_data (output_bfd);
2481   esdo = elf_section_data (output_section);
2482   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2483     {
2484       output_reldata = &esdo->rel;
2485       swap_out = bed->s->swap_reloc_out;
2486     }
2487   else if (esdo->rela.hdr
2488            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2489     {
2490       output_reldata = &esdo->rela;
2491       swap_out = bed->s->swap_reloca_out;
2492     }
2493   else
2494     {
2495       (*_bfd_error_handler)
2496         (_("%B: relocation size mismatch in %B section %A"),
2497          output_bfd, input_section->owner, input_section);
2498       bfd_set_error (bfd_error_wrong_format);
2499       return FALSE;
2500     }
2501
2502   erel = output_reldata->hdr->contents;
2503   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2504   irela = internal_relocs;
2505   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2506                       * bed->s->int_rels_per_ext_rel);
2507   while (irela < irelaend)
2508     {
2509       (*swap_out) (output_bfd, irela, erel);
2510       irela += bed->s->int_rels_per_ext_rel;
2511       erel += input_rel_hdr->sh_entsize;
2512     }
2513
2514   /* Bump the counter, so that we know where to add the next set of
2515      relocations.  */
2516   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2517
2518   return TRUE;
2519 }
2520 \f
2521 /* Make weak undefined symbols in PIE dynamic.  */
2522
2523 bfd_boolean
2524 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2525                                  struct elf_link_hash_entry *h)
2526 {
2527   if (bfd_link_pie (info)
2528       && h->dynindx == -1
2529       && h->root.type == bfd_link_hash_undefweak)
2530     return bfd_elf_link_record_dynamic_symbol (info, h);
2531
2532   return TRUE;
2533 }
2534
2535 /* Fix up the flags for a symbol.  This handles various cases which
2536    can only be fixed after all the input files are seen.  This is
2537    currently called by both adjust_dynamic_symbol and
2538    assign_sym_version, which is unnecessary but perhaps more robust in
2539    the face of future changes.  */
2540
2541 static bfd_boolean
2542 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2543                            struct elf_info_failed *eif)
2544 {
2545   const struct elf_backend_data *bed;
2546
2547   /* If this symbol was mentioned in a non-ELF file, try to set
2548      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2549      permit a non-ELF file to correctly refer to a symbol defined in
2550      an ELF dynamic object.  */
2551   if (h->non_elf)
2552     {
2553       while (h->root.type == bfd_link_hash_indirect)
2554         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2555
2556       if (h->root.type != bfd_link_hash_defined
2557           && h->root.type != bfd_link_hash_defweak)
2558         {
2559           h->ref_regular = 1;
2560           h->ref_regular_nonweak = 1;
2561         }
2562       else
2563         {
2564           if (h->root.u.def.section->owner != NULL
2565               && (bfd_get_flavour (h->root.u.def.section->owner)
2566                   == bfd_target_elf_flavour))
2567             {
2568               h->ref_regular = 1;
2569               h->ref_regular_nonweak = 1;
2570             }
2571           else
2572             h->def_regular = 1;
2573         }
2574
2575       if (h->dynindx == -1
2576           && (h->def_dynamic
2577               || h->ref_dynamic))
2578         {
2579           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2580             {
2581               eif->failed = TRUE;
2582               return FALSE;
2583             }
2584         }
2585     }
2586   else
2587     {
2588       /* Unfortunately, NON_ELF is only correct if the symbol
2589          was first seen in a non-ELF file.  Fortunately, if the symbol
2590          was first seen in an ELF file, we're probably OK unless the
2591          symbol was defined in a non-ELF file.  Catch that case here.
2592          FIXME: We're still in trouble if the symbol was first seen in
2593          a dynamic object, and then later in a non-ELF regular object.  */
2594       if ((h->root.type == bfd_link_hash_defined
2595            || h->root.type == bfd_link_hash_defweak)
2596           && !h->def_regular
2597           && (h->root.u.def.section->owner != NULL
2598               ? (bfd_get_flavour (h->root.u.def.section->owner)
2599                  != bfd_target_elf_flavour)
2600               : (bfd_is_abs_section (h->root.u.def.section)
2601                  && !h->def_dynamic)))
2602         h->def_regular = 1;
2603     }
2604
2605   /* Backend specific symbol fixup.  */
2606   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2607   if (bed->elf_backend_fixup_symbol
2608       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2609     return FALSE;
2610
2611   /* If this is a final link, and the symbol was defined as a common
2612      symbol in a regular object file, and there was no definition in
2613      any dynamic object, then the linker will have allocated space for
2614      the symbol in a common section but the DEF_REGULAR
2615      flag will not have been set.  */
2616   if (h->root.type == bfd_link_hash_defined
2617       && !h->def_regular
2618       && h->ref_regular
2619       && !h->def_dynamic
2620       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2621     h->def_regular = 1;
2622
2623   /* If -Bsymbolic was used (which means to bind references to global
2624      symbols to the definition within the shared object), and this
2625      symbol was defined in a regular object, then it actually doesn't
2626      need a PLT entry.  Likewise, if the symbol has non-default
2627      visibility.  If the symbol has hidden or internal visibility, we
2628      will force it local.  */
2629   if (h->needs_plt
2630       && bfd_link_pic (eif->info)
2631       && is_elf_hash_table (eif->info->hash)
2632       && (SYMBOLIC_BIND (eif->info, h)
2633           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2634       && h->def_regular)
2635     {
2636       bfd_boolean force_local;
2637
2638       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2639                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2640       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2641     }
2642
2643   /* If a weak undefined symbol has non-default visibility, we also
2644      hide it from the dynamic linker.  */
2645   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2646       && h->root.type == bfd_link_hash_undefweak)
2647     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2648
2649   /* If this is a weak defined symbol in a dynamic object, and we know
2650      the real definition in the dynamic object, copy interesting flags
2651      over to the real definition.  */
2652   if (h->u.weakdef != NULL)
2653     {
2654       /* If the real definition is defined by a regular object file,
2655          don't do anything special.  See the longer description in
2656          _bfd_elf_adjust_dynamic_symbol, below.  */
2657       if (h->u.weakdef->def_regular)
2658         h->u.weakdef = NULL;
2659       else
2660         {
2661           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2662
2663           while (h->root.type == bfd_link_hash_indirect)
2664             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2665
2666           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2667                       || h->root.type == bfd_link_hash_defweak);
2668           BFD_ASSERT (weakdef->def_dynamic);
2669           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2670                       || weakdef->root.type == bfd_link_hash_defweak);
2671           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2672         }
2673     }
2674
2675   return TRUE;
2676 }
2677
2678 /* Make the backend pick a good value for a dynamic symbol.  This is
2679    called via elf_link_hash_traverse, and also calls itself
2680    recursively.  */
2681
2682 static bfd_boolean
2683 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2684 {
2685   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2686   bfd *dynobj;
2687   const struct elf_backend_data *bed;
2688
2689   if (! is_elf_hash_table (eif->info->hash))
2690     return FALSE;
2691
2692   /* Ignore indirect symbols.  These are added by the versioning code.  */
2693   if (h->root.type == bfd_link_hash_indirect)
2694     return TRUE;
2695
2696   /* Fix the symbol flags.  */
2697   if (! _bfd_elf_fix_symbol_flags (h, eif))
2698     return FALSE;
2699
2700   /* If this symbol does not require a PLT entry, and it is not
2701      defined by a dynamic object, or is not referenced by a regular
2702      object, ignore it.  We do have to handle a weak defined symbol,
2703      even if no regular object refers to it, if we decided to add it
2704      to the dynamic symbol table.  FIXME: Do we normally need to worry
2705      about symbols which are defined by one dynamic object and
2706      referenced by another one?  */
2707   if (!h->needs_plt
2708       && h->type != STT_GNU_IFUNC
2709       && (h->def_regular
2710           || !h->def_dynamic
2711           || (!h->ref_regular
2712               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2713     {
2714       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2715       return TRUE;
2716     }
2717
2718   /* If we've already adjusted this symbol, don't do it again.  This
2719      can happen via a recursive call.  */
2720   if (h->dynamic_adjusted)
2721     return TRUE;
2722
2723   /* Don't look at this symbol again.  Note that we must set this
2724      after checking the above conditions, because we may look at a
2725      symbol once, decide not to do anything, and then get called
2726      recursively later after REF_REGULAR is set below.  */
2727   h->dynamic_adjusted = 1;
2728
2729   /* If this is a weak definition, and we know a real definition, and
2730      the real symbol is not itself defined by a regular object file,
2731      then get a good value for the real definition.  We handle the
2732      real symbol first, for the convenience of the backend routine.
2733
2734      Note that there is a confusing case here.  If the real definition
2735      is defined by a regular object file, we don't get the real symbol
2736      from the dynamic object, but we do get the weak symbol.  If the
2737      processor backend uses a COPY reloc, then if some routine in the
2738      dynamic object changes the real symbol, we will not see that
2739      change in the corresponding weak symbol.  This is the way other
2740      ELF linkers work as well, and seems to be a result of the shared
2741      library model.
2742
2743      I will clarify this issue.  Most SVR4 shared libraries define the
2744      variable _timezone and define timezone as a weak synonym.  The
2745      tzset call changes _timezone.  If you write
2746        extern int timezone;
2747        int _timezone = 5;
2748        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2749      you might expect that, since timezone is a synonym for _timezone,
2750      the same number will print both times.  However, if the processor
2751      backend uses a COPY reloc, then actually timezone will be copied
2752      into your process image, and, since you define _timezone
2753      yourself, _timezone will not.  Thus timezone and _timezone will
2754      wind up at different memory locations.  The tzset call will set
2755      _timezone, leaving timezone unchanged.  */
2756
2757   if (h->u.weakdef != NULL)
2758     {
2759       /* If we get to this point, there is an implicit reference to
2760          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2761       h->u.weakdef->ref_regular = 1;
2762
2763       /* Ensure that the backend adjust_dynamic_symbol function sees
2764          H->U.WEAKDEF before H by recursively calling ourselves.  */
2765       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2766         return FALSE;
2767     }
2768
2769   /* If a symbol has no type and no size and does not require a PLT
2770      entry, then we are probably about to do the wrong thing here: we
2771      are probably going to create a COPY reloc for an empty object.
2772      This case can arise when a shared object is built with assembly
2773      code, and the assembly code fails to set the symbol type.  */
2774   if (h->size == 0
2775       && h->type == STT_NOTYPE
2776       && !h->needs_plt)
2777     (*_bfd_error_handler)
2778       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2779        h->root.root.string);
2780
2781   dynobj = elf_hash_table (eif->info)->dynobj;
2782   bed = get_elf_backend_data (dynobj);
2783
2784   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2785     {
2786       eif->failed = TRUE;
2787       return FALSE;
2788     }
2789
2790   return TRUE;
2791 }
2792
2793 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2794    DYNBSS.  */
2795
2796 bfd_boolean
2797 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2798                               struct elf_link_hash_entry *h,
2799                               asection *dynbss)
2800 {
2801   unsigned int power_of_two;
2802   bfd_vma mask;
2803   asection *sec = h->root.u.def.section;
2804
2805   /* The section aligment of definition is the maximum alignment
2806      requirement of symbols defined in the section.  Since we don't
2807      know the symbol alignment requirement, we start with the
2808      maximum alignment and check low bits of the symbol address
2809      for the minimum alignment.  */
2810   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2811   mask = ((bfd_vma) 1 << power_of_two) - 1;
2812   while ((h->root.u.def.value & mask) != 0)
2813     {
2814        mask >>= 1;
2815        --power_of_two;
2816     }
2817
2818   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2819                                                 dynbss))
2820     {
2821       /* Adjust the section alignment if needed.  */
2822       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2823                                        power_of_two))
2824         return FALSE;
2825     }
2826
2827   /* We make sure that the symbol will be aligned properly.  */
2828   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2829
2830   /* Define the symbol as being at this point in DYNBSS.  */
2831   h->root.u.def.section = dynbss;
2832   h->root.u.def.value = dynbss->size;
2833
2834   /* Increment the size of DYNBSS to make room for the symbol.  */
2835   dynbss->size += h->size;
2836
2837   /* No error if extern_protected_data is true.  */
2838   if (h->protected_def
2839       && (!info->extern_protected_data
2840           || (info->extern_protected_data < 0
2841               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2842     info->callbacks->einfo
2843       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2844        h->root.root.string);
2845
2846   return TRUE;
2847 }
2848
2849 /* Adjust all external symbols pointing into SEC_MERGE sections
2850    to reflect the object merging within the sections.  */
2851
2852 static bfd_boolean
2853 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2854 {
2855   asection *sec;
2856
2857   if ((h->root.type == bfd_link_hash_defined
2858        || h->root.type == bfd_link_hash_defweak)
2859       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2860       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2861     {
2862       bfd *output_bfd = (bfd *) data;
2863
2864       h->root.u.def.value =
2865         _bfd_merged_section_offset (output_bfd,
2866                                     &h->root.u.def.section,
2867                                     elf_section_data (sec)->sec_info,
2868                                     h->root.u.def.value);
2869     }
2870
2871   return TRUE;
2872 }
2873
2874 /* Returns false if the symbol referred to by H should be considered
2875    to resolve local to the current module, and true if it should be
2876    considered to bind dynamically.  */
2877
2878 bfd_boolean
2879 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2880                            struct bfd_link_info *info,
2881                            bfd_boolean not_local_protected)
2882 {
2883   bfd_boolean binding_stays_local_p;
2884   const struct elf_backend_data *bed;
2885   struct elf_link_hash_table *hash_table;
2886
2887   if (h == NULL)
2888     return FALSE;
2889
2890   while (h->root.type == bfd_link_hash_indirect
2891          || h->root.type == bfd_link_hash_warning)
2892     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2893
2894   /* If it was forced local, then clearly it's not dynamic.  */
2895   if (h->dynindx == -1)
2896     return FALSE;
2897   if (h->forced_local)
2898     return FALSE;
2899
2900   /* Identify the cases where name binding rules say that a
2901      visible symbol resolves locally.  */
2902   binding_stays_local_p = (bfd_link_executable (info)
2903                            || SYMBOLIC_BIND (info, h));
2904
2905   switch (ELF_ST_VISIBILITY (h->other))
2906     {
2907     case STV_INTERNAL:
2908     case STV_HIDDEN:
2909       return FALSE;
2910
2911     case STV_PROTECTED:
2912       hash_table = elf_hash_table (info);
2913       if (!is_elf_hash_table (hash_table))
2914         return FALSE;
2915
2916       bed = get_elf_backend_data (hash_table->dynobj);
2917
2918       /* Proper resolution for function pointer equality may require
2919          that these symbols perhaps be resolved dynamically, even though
2920          we should be resolving them to the current module.  */
2921       if (!not_local_protected || !bed->is_function_type (h->type))
2922         binding_stays_local_p = TRUE;
2923       break;
2924
2925     default:
2926       break;
2927     }
2928
2929   /* If it isn't defined locally, then clearly it's dynamic.  */
2930   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2931     return TRUE;
2932
2933   /* Otherwise, the symbol is dynamic if binding rules don't tell
2934      us that it remains local.  */
2935   return !binding_stays_local_p;
2936 }
2937
2938 /* Return true if the symbol referred to by H should be considered
2939    to resolve local to the current module, and false otherwise.  Differs
2940    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2941    undefined symbols.  The two functions are virtually identical except
2942    for the place where forced_local and dynindx == -1 are tested.  If
2943    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2944    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2945    the symbol is local only for defined symbols.
2946    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2947    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2948    treatment of undefined weak symbols.  For those that do not make
2949    undefined weak symbols dynamic, both functions may return false.  */
2950
2951 bfd_boolean
2952 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2953                               struct bfd_link_info *info,
2954                               bfd_boolean local_protected)
2955 {
2956   const struct elf_backend_data *bed;
2957   struct elf_link_hash_table *hash_table;
2958
2959   /* If it's a local sym, of course we resolve locally.  */
2960   if (h == NULL)
2961     return TRUE;
2962
2963   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2964   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2965       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2966     return TRUE;
2967
2968   /* Common symbols that become definitions don't get the DEF_REGULAR
2969      flag set, so test it first, and don't bail out.  */
2970   if (ELF_COMMON_DEF_P (h))
2971     /* Do nothing.  */;
2972   /* If we don't have a definition in a regular file, then we can't
2973      resolve locally.  The sym is either undefined or dynamic.  */
2974   else if (!h->def_regular)
2975     return FALSE;
2976
2977   /* Forced local symbols resolve locally.  */
2978   if (h->forced_local)
2979     return TRUE;
2980
2981   /* As do non-dynamic symbols.  */
2982   if (h->dynindx == -1)
2983     return TRUE;
2984
2985   /* At this point, we know the symbol is defined and dynamic.  In an
2986      executable it must resolve locally, likewise when building symbolic
2987      shared libraries.  */
2988   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
2989     return TRUE;
2990
2991   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2992      with default visibility might not resolve locally.  */
2993   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2994     return FALSE;
2995
2996   hash_table = elf_hash_table (info);
2997   if (!is_elf_hash_table (hash_table))
2998     return TRUE;
2999
3000   bed = get_elf_backend_data (hash_table->dynobj);
3001
3002   /* If extern_protected_data is false, STV_PROTECTED non-function
3003      symbols are local.  */
3004   if ((!info->extern_protected_data
3005        || (info->extern_protected_data < 0
3006            && !bed->extern_protected_data))
3007       && !bed->is_function_type (h->type))
3008     return TRUE;
3009
3010   /* Function pointer equality tests may require that STV_PROTECTED
3011      symbols be treated as dynamic symbols.  If the address of a
3012      function not defined in an executable is set to that function's
3013      plt entry in the executable, then the address of the function in
3014      a shared library must also be the plt entry in the executable.  */
3015   return local_protected;
3016 }
3017
3018 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3019    aligned.  Returns the first TLS output section.  */
3020
3021 struct bfd_section *
3022 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3023 {
3024   struct bfd_section *sec, *tls;
3025   unsigned int align = 0;
3026
3027   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3028     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3029       break;
3030   tls = sec;
3031
3032   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3033     if (sec->alignment_power > align)
3034       align = sec->alignment_power;
3035
3036   elf_hash_table (info)->tls_sec = tls;
3037
3038   /* Ensure the alignment of the first section is the largest alignment,
3039      so that the tls segment starts aligned.  */
3040   if (tls != NULL)
3041     tls->alignment_power = align;
3042
3043   return tls;
3044 }
3045
3046 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3047 static bfd_boolean
3048 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3049                                   Elf_Internal_Sym *sym)
3050 {
3051   const struct elf_backend_data *bed;
3052
3053   /* Local symbols do not count, but target specific ones might.  */
3054   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3055       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3056     return FALSE;
3057
3058   bed = get_elf_backend_data (abfd);
3059   /* Function symbols do not count.  */
3060   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3061     return FALSE;
3062
3063   /* If the section is undefined, then so is the symbol.  */
3064   if (sym->st_shndx == SHN_UNDEF)
3065     return FALSE;
3066
3067   /* If the symbol is defined in the common section, then
3068      it is a common definition and so does not count.  */
3069   if (bed->common_definition (sym))
3070     return FALSE;
3071
3072   /* If the symbol is in a target specific section then we
3073      must rely upon the backend to tell us what it is.  */
3074   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3075     /* FIXME - this function is not coded yet:
3076
3077        return _bfd_is_global_symbol_definition (abfd, sym);
3078
3079        Instead for now assume that the definition is not global,
3080        Even if this is wrong, at least the linker will behave
3081        in the same way that it used to do.  */
3082     return FALSE;
3083
3084   return TRUE;
3085 }
3086
3087 /* Search the symbol table of the archive element of the archive ABFD
3088    whose archive map contains a mention of SYMDEF, and determine if
3089    the symbol is defined in this element.  */
3090 static bfd_boolean
3091 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3092 {
3093   Elf_Internal_Shdr * hdr;
3094   bfd_size_type symcount;
3095   bfd_size_type extsymcount;
3096   bfd_size_type extsymoff;
3097   Elf_Internal_Sym *isymbuf;
3098   Elf_Internal_Sym *isym;
3099   Elf_Internal_Sym *isymend;
3100   bfd_boolean result;
3101
3102   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3103   if (abfd == NULL)
3104     return FALSE;
3105
3106   /* Return FALSE if the object has been claimed by plugin.  */
3107   if (abfd->plugin_format == bfd_plugin_yes)
3108     return FALSE;
3109
3110   if (! bfd_check_format (abfd, bfd_object))
3111     return FALSE;
3112
3113   /* Select the appropriate symbol table.  */
3114   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3115     hdr = &elf_tdata (abfd)->symtab_hdr;
3116   else
3117     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3118
3119   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3120
3121   /* The sh_info field of the symtab header tells us where the
3122      external symbols start.  We don't care about the local symbols.  */
3123   if (elf_bad_symtab (abfd))
3124     {
3125       extsymcount = symcount;
3126       extsymoff = 0;
3127     }
3128   else
3129     {
3130       extsymcount = symcount - hdr->sh_info;
3131       extsymoff = hdr->sh_info;
3132     }
3133
3134   if (extsymcount == 0)
3135     return FALSE;
3136
3137   /* Read in the symbol table.  */
3138   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3139                                   NULL, NULL, NULL);
3140   if (isymbuf == NULL)
3141     return FALSE;
3142
3143   /* Scan the symbol table looking for SYMDEF.  */
3144   result = FALSE;
3145   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3146     {
3147       const char *name;
3148
3149       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3150                                               isym->st_name);
3151       if (name == NULL)
3152         break;
3153
3154       if (strcmp (name, symdef->name) == 0)
3155         {
3156           result = is_global_data_symbol_definition (abfd, isym);
3157           break;
3158         }
3159     }
3160
3161   free (isymbuf);
3162
3163   return result;
3164 }
3165 \f
3166 /* Add an entry to the .dynamic table.  */
3167
3168 bfd_boolean
3169 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3170                             bfd_vma tag,
3171                             bfd_vma val)
3172 {
3173   struct elf_link_hash_table *hash_table;
3174   const struct elf_backend_data *bed;
3175   asection *s;
3176   bfd_size_type newsize;
3177   bfd_byte *newcontents;
3178   Elf_Internal_Dyn dyn;
3179
3180   hash_table = elf_hash_table (info);
3181   if (! is_elf_hash_table (hash_table))
3182     return FALSE;
3183
3184   bed = get_elf_backend_data (hash_table->dynobj);
3185   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3186   BFD_ASSERT (s != NULL);
3187
3188   newsize = s->size + bed->s->sizeof_dyn;
3189   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3190   if (newcontents == NULL)
3191     return FALSE;
3192
3193   dyn.d_tag = tag;
3194   dyn.d_un.d_val = val;
3195   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3196
3197   s->size = newsize;
3198   s->contents = newcontents;
3199
3200   return TRUE;
3201 }
3202
3203 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3204    otherwise just check whether one already exists.  Returns -1 on error,
3205    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3206
3207 static int
3208 elf_add_dt_needed_tag (bfd *abfd,
3209                        struct bfd_link_info *info,
3210                        const char *soname,
3211                        bfd_boolean do_it)
3212 {
3213   struct elf_link_hash_table *hash_table;
3214   bfd_size_type strindex;
3215
3216   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3217     return -1;
3218
3219   hash_table = elf_hash_table (info);
3220   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3221   if (strindex == (bfd_size_type) -1)
3222     return -1;
3223
3224   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3225     {
3226       asection *sdyn;
3227       const struct elf_backend_data *bed;
3228       bfd_byte *extdyn;
3229
3230       bed = get_elf_backend_data (hash_table->dynobj);
3231       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3232       if (sdyn != NULL)
3233         for (extdyn = sdyn->contents;
3234              extdyn < sdyn->contents + sdyn->size;
3235              extdyn += bed->s->sizeof_dyn)
3236           {
3237             Elf_Internal_Dyn dyn;
3238
3239             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3240             if (dyn.d_tag == DT_NEEDED
3241                 && dyn.d_un.d_val == strindex)
3242               {
3243                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3244                 return 1;
3245               }
3246           }
3247     }
3248
3249   if (do_it)
3250     {
3251       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3252         return -1;
3253
3254       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3255         return -1;
3256     }
3257   else
3258     /* We were just checking for existence of the tag.  */
3259     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3260
3261   return 0;
3262 }
3263
3264 /* Return true if SONAME is on the needed list between NEEDED and STOP
3265    (or the end of list if STOP is NULL), and needed by a library that
3266    will be loaded.  */
3267
3268 static bfd_boolean
3269 on_needed_list (const char *soname,
3270                 struct bfd_link_needed_list *needed,
3271                 struct bfd_link_needed_list *stop)
3272 {
3273   struct bfd_link_needed_list *look;
3274   for (look = needed; look != stop; look = look->next)
3275     if (strcmp (soname, look->name) == 0
3276         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3277             /* If needed by a library that itself is not directly
3278                needed, recursively check whether that library is
3279                indirectly needed.  Since we add DT_NEEDED entries to
3280                the end of the list, library dependencies appear after
3281                the library.  Therefore search prior to the current
3282                LOOK, preventing possible infinite recursion.  */
3283             || on_needed_list (elf_dt_name (look->by), needed, look)))
3284       return TRUE;
3285
3286   return FALSE;
3287 }
3288
3289 /* Sort symbol by value, section, and size.  */
3290 static int
3291 elf_sort_symbol (const void *arg1, const void *arg2)
3292 {
3293   const struct elf_link_hash_entry *h1;
3294   const struct elf_link_hash_entry *h2;
3295   bfd_signed_vma vdiff;
3296
3297   h1 = *(const struct elf_link_hash_entry **) arg1;
3298   h2 = *(const struct elf_link_hash_entry **) arg2;
3299   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3300   if (vdiff != 0)
3301     return vdiff > 0 ? 1 : -1;
3302   else
3303     {
3304       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3305       if (sdiff != 0)
3306         return sdiff > 0 ? 1 : -1;
3307     }
3308   vdiff = h1->size - h2->size;
3309   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3310 }
3311
3312 /* This function is used to adjust offsets into .dynstr for
3313    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3314
3315 static bfd_boolean
3316 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3317 {
3318   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3319
3320   if (h->dynindx != -1)
3321     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3322   return TRUE;
3323 }
3324
3325 /* Assign string offsets in .dynstr, update all structures referencing
3326    them.  */
3327
3328 static bfd_boolean
3329 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3330 {
3331   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3332   struct elf_link_local_dynamic_entry *entry;
3333   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3334   bfd *dynobj = hash_table->dynobj;
3335   asection *sdyn;
3336   bfd_size_type size;
3337   const struct elf_backend_data *bed;
3338   bfd_byte *extdyn;
3339
3340   _bfd_elf_strtab_finalize (dynstr);
3341   size = _bfd_elf_strtab_size (dynstr);
3342
3343   bed = get_elf_backend_data (dynobj);
3344   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3345   BFD_ASSERT (sdyn != NULL);
3346
3347   /* Update all .dynamic entries referencing .dynstr strings.  */
3348   for (extdyn = sdyn->contents;
3349        extdyn < sdyn->contents + sdyn->size;
3350        extdyn += bed->s->sizeof_dyn)
3351     {
3352       Elf_Internal_Dyn dyn;
3353
3354       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3355       switch (dyn.d_tag)
3356         {
3357         case DT_STRSZ:
3358           dyn.d_un.d_val = size;
3359           break;
3360         case DT_NEEDED:
3361         case DT_SONAME:
3362         case DT_RPATH:
3363         case DT_RUNPATH:
3364         case DT_FILTER:
3365         case DT_AUXILIARY:
3366         case DT_AUDIT:
3367         case DT_DEPAUDIT:
3368           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3369           break;
3370         default:
3371           continue;
3372         }
3373       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3374     }
3375
3376   /* Now update local dynamic symbols.  */
3377   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3378     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3379                                                   entry->isym.st_name);
3380
3381   /* And the rest of dynamic symbols.  */
3382   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3383
3384   /* Adjust version definitions.  */
3385   if (elf_tdata (output_bfd)->cverdefs)
3386     {
3387       asection *s;
3388       bfd_byte *p;
3389       bfd_size_type i;
3390       Elf_Internal_Verdef def;
3391       Elf_Internal_Verdaux defaux;
3392
3393       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3394       p = s->contents;
3395       do
3396         {
3397           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3398                                    &def);
3399           p += sizeof (Elf_External_Verdef);
3400           if (def.vd_aux != sizeof (Elf_External_Verdef))
3401             continue;
3402           for (i = 0; i < def.vd_cnt; ++i)
3403             {
3404               _bfd_elf_swap_verdaux_in (output_bfd,
3405                                         (Elf_External_Verdaux *) p, &defaux);
3406               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3407                                                         defaux.vda_name);
3408               _bfd_elf_swap_verdaux_out (output_bfd,
3409                                          &defaux, (Elf_External_Verdaux *) p);
3410               p += sizeof (Elf_External_Verdaux);
3411             }
3412         }
3413       while (def.vd_next);
3414     }
3415
3416   /* Adjust version references.  */
3417   if (elf_tdata (output_bfd)->verref)
3418     {
3419       asection *s;
3420       bfd_byte *p;
3421       bfd_size_type i;
3422       Elf_Internal_Verneed need;
3423       Elf_Internal_Vernaux needaux;
3424
3425       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3426       p = s->contents;
3427       do
3428         {
3429           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3430                                     &need);
3431           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3432           _bfd_elf_swap_verneed_out (output_bfd, &need,
3433                                      (Elf_External_Verneed *) p);
3434           p += sizeof (Elf_External_Verneed);
3435           for (i = 0; i < need.vn_cnt; ++i)
3436             {
3437               _bfd_elf_swap_vernaux_in (output_bfd,
3438                                         (Elf_External_Vernaux *) p, &needaux);
3439               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3440                                                          needaux.vna_name);
3441               _bfd_elf_swap_vernaux_out (output_bfd,
3442                                          &needaux,
3443                                          (Elf_External_Vernaux *) p);
3444               p += sizeof (Elf_External_Vernaux);
3445             }
3446         }
3447       while (need.vn_next);
3448     }
3449
3450   return TRUE;
3451 }
3452 \f
3453 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3454    The default is to only match when the INPUT and OUTPUT are exactly
3455    the same target.  */
3456
3457 bfd_boolean
3458 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3459                                     const bfd_target *output)
3460 {
3461   return input == output;
3462 }
3463
3464 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3465    This version is used when different targets for the same architecture
3466    are virtually identical.  */
3467
3468 bfd_boolean
3469 _bfd_elf_relocs_compatible (const bfd_target *input,
3470                             const bfd_target *output)
3471 {
3472   const struct elf_backend_data *obed, *ibed;
3473
3474   if (input == output)
3475     return TRUE;
3476
3477   ibed = xvec_get_elf_backend_data (input);
3478   obed = xvec_get_elf_backend_data (output);
3479
3480   if (ibed->arch != obed->arch)
3481     return FALSE;
3482
3483   /* If both backends are using this function, deem them compatible.  */
3484   return ibed->relocs_compatible == obed->relocs_compatible;
3485 }
3486
3487 /* Make a special call to the linker "notice" function to tell it that
3488    we are about to handle an as-needed lib, or have finished
3489    processing the lib.  */
3490
3491 bfd_boolean
3492 _bfd_elf_notice_as_needed (bfd *ibfd,
3493                            struct bfd_link_info *info,
3494                            enum notice_asneeded_action act)
3495 {
3496   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3497 }
3498
3499 /* Check relocations an ELF object file.  */
3500
3501 bfd_boolean
3502 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3503 {
3504   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3505   struct elf_link_hash_table *htab = elf_hash_table (info);
3506
3507   /* If this object is the same format as the output object, and it is
3508      not a shared library, then let the backend look through the
3509      relocs.
3510
3511      This is required to build global offset table entries and to
3512      arrange for dynamic relocs.  It is not required for the
3513      particular common case of linking non PIC code, even when linking
3514      against shared libraries, but unfortunately there is no way of
3515      knowing whether an object file has been compiled PIC or not.
3516      Looking through the relocs is not particularly time consuming.
3517      The problem is that we must either (1) keep the relocs in memory,
3518      which causes the linker to require additional runtime memory or
3519      (2) read the relocs twice from the input file, which wastes time.
3520      This would be a good case for using mmap.
3521
3522      I have no idea how to handle linking PIC code into a file of a
3523      different format.  It probably can't be done.  */
3524   if ((abfd->flags & DYNAMIC) == 0
3525       && is_elf_hash_table (htab)
3526       && bed->check_relocs != NULL
3527       && elf_object_id (abfd) == elf_hash_table_id (htab)
3528       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3529     {
3530       asection *o;
3531
3532       for (o = abfd->sections; o != NULL; o = o->next)
3533         {
3534           Elf_Internal_Rela *internal_relocs;
3535           bfd_boolean ok;
3536
3537           /* Don't check relocations in excluded sections.  */
3538           if ((o->flags & SEC_RELOC) == 0
3539               || (o->flags & SEC_EXCLUDE) != 0
3540               || o->reloc_count == 0
3541               || ((info->strip == strip_all || info->strip == strip_debugger)
3542                   && (o->flags & SEC_DEBUGGING) != 0)
3543               || bfd_is_abs_section (o->output_section))
3544             continue;
3545
3546           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3547                                                        info->keep_memory);
3548           if (internal_relocs == NULL)
3549             return FALSE;
3550
3551           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3552
3553           if (elf_section_data (o)->relocs != internal_relocs)
3554             free (internal_relocs);
3555
3556           if (! ok)
3557             return FALSE;
3558         }
3559     }
3560
3561   return TRUE;
3562 }
3563
3564 /* Add symbols from an ELF object file to the linker hash table.  */
3565
3566 static bfd_boolean
3567 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3568 {
3569   Elf_Internal_Ehdr *ehdr;
3570   Elf_Internal_Shdr *hdr;
3571   bfd_size_type symcount;
3572   bfd_size_type extsymcount;
3573   bfd_size_type extsymoff;
3574   struct elf_link_hash_entry **sym_hash;
3575   bfd_boolean dynamic;
3576   Elf_External_Versym *extversym = NULL;
3577   Elf_External_Versym *ever;
3578   struct elf_link_hash_entry *weaks;
3579   struct elf_link_hash_entry **nondeflt_vers = NULL;
3580   bfd_size_type nondeflt_vers_cnt = 0;
3581   Elf_Internal_Sym *isymbuf = NULL;
3582   Elf_Internal_Sym *isym;
3583   Elf_Internal_Sym *isymend;
3584   const struct elf_backend_data *bed;
3585   bfd_boolean add_needed;
3586   struct elf_link_hash_table *htab;
3587   bfd_size_type amt;
3588   void *alloc_mark = NULL;
3589   struct bfd_hash_entry **old_table = NULL;
3590   unsigned int old_size = 0;
3591   unsigned int old_count = 0;
3592   void *old_tab = NULL;
3593   void *old_ent;
3594   struct bfd_link_hash_entry *old_undefs = NULL;
3595   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3596   long old_dynsymcount = 0;
3597   bfd_size_type old_dynstr_size = 0;
3598   size_t tabsize = 0;
3599   asection *s;
3600   bfd_boolean just_syms;
3601
3602   htab = elf_hash_table (info);
3603   bed = get_elf_backend_data (abfd);
3604
3605   if ((abfd->flags & DYNAMIC) == 0)
3606     dynamic = FALSE;
3607   else
3608     {
3609       dynamic = TRUE;
3610
3611       /* You can't use -r against a dynamic object.  Also, there's no
3612          hope of using a dynamic object which does not exactly match
3613          the format of the output file.  */
3614       if (bfd_link_relocatable (info)
3615           || !is_elf_hash_table (htab)
3616           || info->output_bfd->xvec != abfd->xvec)
3617         {
3618           if (bfd_link_relocatable (info))
3619             bfd_set_error (bfd_error_invalid_operation);
3620           else
3621             bfd_set_error (bfd_error_wrong_format);
3622           goto error_return;
3623         }
3624     }
3625
3626   ehdr = elf_elfheader (abfd);
3627   if (info->warn_alternate_em
3628       && bed->elf_machine_code != ehdr->e_machine
3629       && ((bed->elf_machine_alt1 != 0
3630            && ehdr->e_machine == bed->elf_machine_alt1)
3631           || (bed->elf_machine_alt2 != 0
3632               && ehdr->e_machine == bed->elf_machine_alt2)))
3633     info->callbacks->einfo
3634       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3635        ehdr->e_machine, abfd, bed->elf_machine_code);
3636
3637   /* As a GNU extension, any input sections which are named
3638      .gnu.warning.SYMBOL are treated as warning symbols for the given
3639      symbol.  This differs from .gnu.warning sections, which generate
3640      warnings when they are included in an output file.  */
3641   /* PR 12761: Also generate this warning when building shared libraries.  */
3642   for (s = abfd->sections; s != NULL; s = s->next)
3643     {
3644       const char *name;
3645
3646       name = bfd_get_section_name (abfd, s);
3647       if (CONST_STRNEQ (name, ".gnu.warning."))
3648         {
3649           char *msg;
3650           bfd_size_type sz;
3651
3652           name += sizeof ".gnu.warning." - 1;
3653
3654           /* If this is a shared object, then look up the symbol
3655              in the hash table.  If it is there, and it is already
3656              been defined, then we will not be using the entry
3657              from this shared object, so we don't need to warn.
3658              FIXME: If we see the definition in a regular object
3659              later on, we will warn, but we shouldn't.  The only
3660              fix is to keep track of what warnings we are supposed
3661              to emit, and then handle them all at the end of the
3662              link.  */
3663           if (dynamic)
3664             {
3665               struct elf_link_hash_entry *h;
3666
3667               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3668
3669               /* FIXME: What about bfd_link_hash_common?  */
3670               if (h != NULL
3671                   && (h->root.type == bfd_link_hash_defined
3672                       || h->root.type == bfd_link_hash_defweak))
3673                 continue;
3674             }
3675
3676           sz = s->size;
3677           msg = (char *) bfd_alloc (abfd, sz + 1);
3678           if (msg == NULL)
3679             goto error_return;
3680
3681           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3682             goto error_return;
3683
3684           msg[sz] = '\0';
3685
3686           if (! (_bfd_generic_link_add_one_symbol
3687                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3688                   FALSE, bed->collect, NULL)))
3689             goto error_return;
3690
3691           if (bfd_link_executable (info))
3692             {
3693               /* Clobber the section size so that the warning does
3694                  not get copied into the output file.  */
3695               s->size = 0;
3696
3697               /* Also set SEC_EXCLUDE, so that symbols defined in
3698                  the warning section don't get copied to the output.  */
3699               s->flags |= SEC_EXCLUDE;
3700             }
3701         }
3702     }
3703
3704   just_syms = ((s = abfd->sections) != NULL
3705                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3706
3707   add_needed = TRUE;
3708   if (! dynamic)
3709     {
3710       /* If we are creating a shared library, create all the dynamic
3711          sections immediately.  We need to attach them to something,
3712          so we attach them to this BFD, provided it is the right
3713          format and is not from ld --just-symbols.  Always create the
3714          dynamic sections for -E/--dynamic-list.  FIXME: If there
3715          are no input BFD's of the same format as the output, we can't
3716          make a shared library.  */
3717       if (!just_syms
3718           && (bfd_link_pic (info)
3719               || (!bfd_link_relocatable (info)
3720                   && (info->export_dynamic || info->dynamic)))
3721           && is_elf_hash_table (htab)
3722           && info->output_bfd->xvec == abfd->xvec
3723           && !htab->dynamic_sections_created)
3724         {
3725           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3726             goto error_return;
3727         }
3728     }
3729   else if (!is_elf_hash_table (htab))
3730     goto error_return;
3731   else
3732     {
3733       const char *soname = NULL;
3734       char *audit = NULL;
3735       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3736       int ret;
3737
3738       /* ld --just-symbols and dynamic objects don't mix very well.
3739          ld shouldn't allow it.  */
3740       if (just_syms)
3741         abort ();
3742
3743       /* If this dynamic lib was specified on the command line with
3744          --as-needed in effect, then we don't want to add a DT_NEEDED
3745          tag unless the lib is actually used.  Similary for libs brought
3746          in by another lib's DT_NEEDED.  When --no-add-needed is used
3747          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3748          any dynamic library in DT_NEEDED tags in the dynamic lib at
3749          all.  */
3750       add_needed = (elf_dyn_lib_class (abfd)
3751                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3752                        | DYN_NO_NEEDED)) == 0;
3753
3754       s = bfd_get_section_by_name (abfd, ".dynamic");
3755       if (s != NULL)
3756         {
3757           bfd_byte *dynbuf;
3758           bfd_byte *extdyn;
3759           unsigned int elfsec;
3760           unsigned long shlink;
3761
3762           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3763             {
3764 error_free_dyn:
3765               free (dynbuf);
3766               goto error_return;
3767             }
3768
3769           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3770           if (elfsec == SHN_BAD)
3771             goto error_free_dyn;
3772           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3773
3774           for (extdyn = dynbuf;
3775                extdyn < dynbuf + s->size;
3776                extdyn += bed->s->sizeof_dyn)
3777             {
3778               Elf_Internal_Dyn dyn;
3779
3780               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3781               if (dyn.d_tag == DT_SONAME)
3782                 {
3783                   unsigned int tagv = dyn.d_un.d_val;
3784                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3785                   if (soname == NULL)
3786                     goto error_free_dyn;
3787                 }
3788               if (dyn.d_tag == DT_NEEDED)
3789                 {
3790                   struct bfd_link_needed_list *n, **pn;
3791                   char *fnm, *anm;
3792                   unsigned int tagv = dyn.d_un.d_val;
3793
3794                   amt = sizeof (struct bfd_link_needed_list);
3795                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3796                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3797                   if (n == NULL || fnm == NULL)
3798                     goto error_free_dyn;
3799                   amt = strlen (fnm) + 1;
3800                   anm = (char *) bfd_alloc (abfd, amt);
3801                   if (anm == NULL)
3802                     goto error_free_dyn;
3803                   memcpy (anm, fnm, amt);
3804                   n->name = anm;
3805                   n->by = abfd;
3806                   n->next = NULL;
3807                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3808                     ;
3809                   *pn = n;
3810                 }
3811               if (dyn.d_tag == DT_RUNPATH)
3812                 {
3813                   struct bfd_link_needed_list *n, **pn;
3814                   char *fnm, *anm;
3815                   unsigned int tagv = dyn.d_un.d_val;
3816
3817                   amt = sizeof (struct bfd_link_needed_list);
3818                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3819                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3820                   if (n == NULL || fnm == NULL)
3821                     goto error_free_dyn;
3822                   amt = strlen (fnm) + 1;
3823                   anm = (char *) bfd_alloc (abfd, amt);
3824                   if (anm == NULL)
3825                     goto error_free_dyn;
3826                   memcpy (anm, fnm, amt);
3827                   n->name = anm;
3828                   n->by = abfd;
3829                   n->next = NULL;
3830                   for (pn = & runpath;
3831                        *pn != NULL;
3832                        pn = &(*pn)->next)
3833                     ;
3834                   *pn = n;
3835                 }
3836               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3837               if (!runpath && dyn.d_tag == DT_RPATH)
3838                 {
3839                   struct bfd_link_needed_list *n, **pn;
3840                   char *fnm, *anm;
3841                   unsigned int tagv = dyn.d_un.d_val;
3842
3843                   amt = sizeof (struct bfd_link_needed_list);
3844                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3845                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3846                   if (n == NULL || fnm == NULL)
3847                     goto error_free_dyn;
3848                   amt = strlen (fnm) + 1;
3849                   anm = (char *) bfd_alloc (abfd, amt);
3850                   if (anm == NULL)
3851                     goto error_free_dyn;
3852                   memcpy (anm, fnm, amt);
3853                   n->name = anm;
3854                   n->by = abfd;
3855                   n->next = NULL;
3856                   for (pn = & rpath;
3857                        *pn != NULL;
3858                        pn = &(*pn)->next)
3859                     ;
3860                   *pn = n;
3861                 }
3862               if (dyn.d_tag == DT_AUDIT)
3863                 {
3864                   unsigned int tagv = dyn.d_un.d_val;
3865                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3866                 }
3867             }
3868
3869           free (dynbuf);
3870         }
3871
3872       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3873          frees all more recently bfd_alloc'd blocks as well.  */
3874       if (runpath)
3875         rpath = runpath;
3876
3877       if (rpath)
3878         {
3879           struct bfd_link_needed_list **pn;
3880           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3881             ;
3882           *pn = rpath;
3883         }
3884
3885       /* We do not want to include any of the sections in a dynamic
3886          object in the output file.  We hack by simply clobbering the
3887          list of sections in the BFD.  This could be handled more
3888          cleanly by, say, a new section flag; the existing
3889          SEC_NEVER_LOAD flag is not the one we want, because that one
3890          still implies that the section takes up space in the output
3891          file.  */
3892       bfd_section_list_clear (abfd);
3893
3894       /* Find the name to use in a DT_NEEDED entry that refers to this
3895          object.  If the object has a DT_SONAME entry, we use it.
3896          Otherwise, if the generic linker stuck something in
3897          elf_dt_name, we use that.  Otherwise, we just use the file
3898          name.  */
3899       if (soname == NULL || *soname == '\0')
3900         {
3901           soname = elf_dt_name (abfd);
3902           if (soname == NULL || *soname == '\0')
3903             soname = bfd_get_filename (abfd);
3904         }
3905
3906       /* Save the SONAME because sometimes the linker emulation code
3907          will need to know it.  */
3908       elf_dt_name (abfd) = soname;
3909
3910       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3911       if (ret < 0)
3912         goto error_return;
3913
3914       /* If we have already included this dynamic object in the
3915          link, just ignore it.  There is no reason to include a
3916          particular dynamic object more than once.  */
3917       if (ret > 0)
3918         return TRUE;
3919
3920       /* Save the DT_AUDIT entry for the linker emulation code. */
3921       elf_dt_audit (abfd) = audit;
3922     }
3923
3924   /* If this is a dynamic object, we always link against the .dynsym
3925      symbol table, not the .symtab symbol table.  The dynamic linker
3926      will only see the .dynsym symbol table, so there is no reason to
3927      look at .symtab for a dynamic object.  */
3928
3929   if (! dynamic || elf_dynsymtab (abfd) == 0)
3930     hdr = &elf_tdata (abfd)->symtab_hdr;
3931   else
3932     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3933
3934   symcount = hdr->sh_size / bed->s->sizeof_sym;
3935
3936   /* The sh_info field of the symtab header tells us where the
3937      external symbols start.  We don't care about the local symbols at
3938      this point.  */
3939   if (elf_bad_symtab (abfd))
3940     {
3941       extsymcount = symcount;
3942       extsymoff = 0;
3943     }
3944   else
3945     {
3946       extsymcount = symcount - hdr->sh_info;
3947       extsymoff = hdr->sh_info;
3948     }
3949
3950   sym_hash = elf_sym_hashes (abfd);
3951   if (extsymcount != 0)
3952     {
3953       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3954                                       NULL, NULL, NULL);
3955       if (isymbuf == NULL)
3956         goto error_return;
3957
3958       if (sym_hash == NULL)
3959         {
3960           /* We store a pointer to the hash table entry for each
3961              external symbol.  */
3962           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3963           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3964           if (sym_hash == NULL)
3965             goto error_free_sym;
3966           elf_sym_hashes (abfd) = sym_hash;
3967         }
3968     }
3969
3970   if (dynamic)
3971     {
3972       /* Read in any version definitions.  */
3973       if (!_bfd_elf_slurp_version_tables (abfd,
3974                                           info->default_imported_symver))
3975         goto error_free_sym;
3976
3977       /* Read in the symbol versions, but don't bother to convert them
3978          to internal format.  */
3979       if (elf_dynversym (abfd) != 0)
3980         {
3981           Elf_Internal_Shdr *versymhdr;
3982
3983           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3984           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3985           if (extversym == NULL)
3986             goto error_free_sym;
3987           amt = versymhdr->sh_size;
3988           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3989               || bfd_bread (extversym, amt, abfd) != amt)
3990             goto error_free_vers;
3991         }
3992     }
3993
3994   /* If we are loading an as-needed shared lib, save the symbol table
3995      state before we start adding symbols.  If the lib turns out
3996      to be unneeded, restore the state.  */
3997   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3998     {
3999       unsigned int i;
4000       size_t entsize;
4001
4002       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4003         {
4004           struct bfd_hash_entry *p;
4005           struct elf_link_hash_entry *h;
4006
4007           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4008             {
4009               h = (struct elf_link_hash_entry *) p;
4010               entsize += htab->root.table.entsize;
4011               if (h->root.type == bfd_link_hash_warning)
4012                 entsize += htab->root.table.entsize;
4013             }
4014         }
4015
4016       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4017       old_tab = bfd_malloc (tabsize + entsize);
4018       if (old_tab == NULL)
4019         goto error_free_vers;
4020
4021       /* Remember the current objalloc pointer, so that all mem for
4022          symbols added can later be reclaimed.  */
4023       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4024       if (alloc_mark == NULL)
4025         goto error_free_vers;
4026
4027       /* Make a special call to the linker "notice" function to
4028          tell it that we are about to handle an as-needed lib.  */
4029       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4030         goto error_free_vers;
4031
4032       /* Clone the symbol table.  Remember some pointers into the
4033          symbol table, and dynamic symbol count.  */
4034       old_ent = (char *) old_tab + tabsize;
4035       memcpy (old_tab, htab->root.table.table, tabsize);
4036       old_undefs = htab->root.undefs;
4037       old_undefs_tail = htab->root.undefs_tail;
4038       old_table = htab->root.table.table;
4039       old_size = htab->root.table.size;
4040       old_count = htab->root.table.count;
4041       old_dynsymcount = htab->dynsymcount;
4042       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
4043
4044       for (i = 0; i < htab->root.table.size; i++)
4045         {
4046           struct bfd_hash_entry *p;
4047           struct elf_link_hash_entry *h;
4048
4049           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4050             {
4051               memcpy (old_ent, p, htab->root.table.entsize);
4052               old_ent = (char *) old_ent + htab->root.table.entsize;
4053               h = (struct elf_link_hash_entry *) p;
4054               if (h->root.type == bfd_link_hash_warning)
4055                 {
4056                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4057                   old_ent = (char *) old_ent + htab->root.table.entsize;
4058                 }
4059             }
4060         }
4061     }
4062
4063   weaks = NULL;
4064   ever = extversym != NULL ? extversym + extsymoff : NULL;
4065   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4066        isym < isymend;
4067        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4068     {
4069       int bind;
4070       bfd_vma value;
4071       asection *sec, *new_sec;
4072       flagword flags;
4073       const char *name;
4074       struct elf_link_hash_entry *h;
4075       struct elf_link_hash_entry *hi;
4076       bfd_boolean definition;
4077       bfd_boolean size_change_ok;
4078       bfd_boolean type_change_ok;
4079       bfd_boolean new_weakdef;
4080       bfd_boolean new_weak;
4081       bfd_boolean old_weak;
4082       bfd_boolean override;
4083       bfd_boolean common;
4084       unsigned int old_alignment;
4085       bfd *old_bfd;
4086       bfd_boolean matched;
4087
4088       override = FALSE;
4089
4090       flags = BSF_NO_FLAGS;
4091       sec = NULL;
4092       value = isym->st_value;
4093       common = bed->common_definition (isym);
4094
4095       bind = ELF_ST_BIND (isym->st_info);
4096       switch (bind)
4097         {
4098         case STB_LOCAL:
4099           /* This should be impossible, since ELF requires that all
4100              global symbols follow all local symbols, and that sh_info
4101              point to the first global symbol.  Unfortunately, Irix 5
4102              screws this up.  */
4103           continue;
4104
4105         case STB_GLOBAL:
4106           if (isym->st_shndx != SHN_UNDEF && !common)
4107             flags = BSF_GLOBAL;
4108           break;
4109
4110         case STB_WEAK:
4111           flags = BSF_WEAK;
4112           break;
4113
4114         case STB_GNU_UNIQUE:
4115           flags = BSF_GNU_UNIQUE;
4116           break;
4117
4118         default:
4119           /* Leave it up to the processor backend.  */
4120           break;
4121         }
4122
4123       if (isym->st_shndx == SHN_UNDEF)
4124         sec = bfd_und_section_ptr;
4125       else if (isym->st_shndx == SHN_ABS)
4126         sec = bfd_abs_section_ptr;
4127       else if (isym->st_shndx == SHN_COMMON)
4128         {
4129           sec = bfd_com_section_ptr;
4130           /* What ELF calls the size we call the value.  What ELF
4131              calls the value we call the alignment.  */
4132           value = isym->st_size;
4133         }
4134       else
4135         {
4136           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4137           if (sec == NULL)
4138             sec = bfd_abs_section_ptr;
4139           else if (discarded_section (sec))
4140             {
4141               /* Symbols from discarded section are undefined.  We keep
4142                  its visibility.  */
4143               sec = bfd_und_section_ptr;
4144               isym->st_shndx = SHN_UNDEF;
4145             }
4146           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4147             value -= sec->vma;
4148         }
4149
4150       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4151                                               isym->st_name);
4152       if (name == NULL)
4153         goto error_free_vers;
4154
4155       if (isym->st_shndx == SHN_COMMON
4156           && (abfd->flags & BFD_PLUGIN) != 0)
4157         {
4158           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4159
4160           if (xc == NULL)
4161             {
4162               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4163                                  | SEC_EXCLUDE);
4164               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4165               if (xc == NULL)
4166                 goto error_free_vers;
4167             }
4168           sec = xc;
4169         }
4170       else if (isym->st_shndx == SHN_COMMON
4171                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4172                && !bfd_link_relocatable (info))
4173         {
4174           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4175
4176           if (tcomm == NULL)
4177             {
4178               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4179                                  | SEC_LINKER_CREATED);
4180               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4181               if (tcomm == NULL)
4182                 goto error_free_vers;
4183             }
4184           sec = tcomm;
4185         }
4186       else if (bed->elf_add_symbol_hook)
4187         {
4188           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4189                                              &sec, &value))
4190             goto error_free_vers;
4191
4192           /* The hook function sets the name to NULL if this symbol
4193              should be skipped for some reason.  */
4194           if (name == NULL)
4195             continue;
4196         }
4197
4198       /* Sanity check that all possibilities were handled.  */
4199       if (sec == NULL)
4200         {
4201           bfd_set_error (bfd_error_bad_value);
4202           goto error_free_vers;
4203         }
4204
4205       /* Silently discard TLS symbols from --just-syms.  There's
4206          no way to combine a static TLS block with a new TLS block
4207          for this executable.  */
4208       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4209           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4210         continue;
4211
4212       if (bfd_is_und_section (sec)
4213           || bfd_is_com_section (sec))
4214         definition = FALSE;
4215       else
4216         definition = TRUE;
4217
4218       size_change_ok = FALSE;
4219       type_change_ok = bed->type_change_ok;
4220       old_weak = FALSE;
4221       matched = FALSE;
4222       old_alignment = 0;
4223       old_bfd = NULL;
4224       new_sec = sec;
4225
4226       if (is_elf_hash_table (htab))
4227         {
4228           Elf_Internal_Versym iver;
4229           unsigned int vernum = 0;
4230           bfd_boolean skip;
4231
4232           if (ever == NULL)
4233             {
4234               if (info->default_imported_symver)
4235                 /* Use the default symbol version created earlier.  */
4236                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4237               else
4238                 iver.vs_vers = 0;
4239             }
4240           else
4241             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4242
4243           vernum = iver.vs_vers & VERSYM_VERSION;
4244
4245           /* If this is a hidden symbol, or if it is not version
4246              1, we append the version name to the symbol name.
4247              However, we do not modify a non-hidden absolute symbol
4248              if it is not a function, because it might be the version
4249              symbol itself.  FIXME: What if it isn't?  */
4250           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4251               || (vernum > 1
4252                   && (!bfd_is_abs_section (sec)
4253                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4254             {
4255               const char *verstr;
4256               size_t namelen, verlen, newlen;
4257               char *newname, *p;
4258
4259               if (isym->st_shndx != SHN_UNDEF)
4260                 {
4261                   if (vernum > elf_tdata (abfd)->cverdefs)
4262                     verstr = NULL;
4263                   else if (vernum > 1)
4264                     verstr =
4265                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4266                   else
4267                     verstr = "";
4268
4269                   if (verstr == NULL)
4270                     {
4271                       (*_bfd_error_handler)
4272                         (_("%B: %s: invalid version %u (max %d)"),
4273                          abfd, name, vernum,
4274                          elf_tdata (abfd)->cverdefs);
4275                       bfd_set_error (bfd_error_bad_value);
4276                       goto error_free_vers;
4277                     }
4278                 }
4279               else
4280                 {
4281                   /* We cannot simply test for the number of
4282                      entries in the VERNEED section since the
4283                      numbers for the needed versions do not start
4284                      at 0.  */
4285                   Elf_Internal_Verneed *t;
4286
4287                   verstr = NULL;
4288                   for (t = elf_tdata (abfd)->verref;
4289                        t != NULL;
4290                        t = t->vn_nextref)
4291                     {
4292                       Elf_Internal_Vernaux *a;
4293
4294                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4295                         {
4296                           if (a->vna_other == vernum)
4297                             {
4298                               verstr = a->vna_nodename;
4299                               break;
4300                             }
4301                         }
4302                       if (a != NULL)
4303                         break;
4304                     }
4305                   if (verstr == NULL)
4306                     {
4307                       (*_bfd_error_handler)
4308                         (_("%B: %s: invalid needed version %d"),
4309                          abfd, name, vernum);
4310                       bfd_set_error (bfd_error_bad_value);
4311                       goto error_free_vers;
4312                     }
4313                 }
4314
4315               namelen = strlen (name);
4316               verlen = strlen (verstr);
4317               newlen = namelen + verlen + 2;
4318               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4319                   && isym->st_shndx != SHN_UNDEF)
4320                 ++newlen;
4321
4322               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4323               if (newname == NULL)
4324                 goto error_free_vers;
4325               memcpy (newname, name, namelen);
4326               p = newname + namelen;
4327               *p++ = ELF_VER_CHR;
4328               /* If this is a defined non-hidden version symbol,
4329                  we add another @ to the name.  This indicates the
4330                  default version of the symbol.  */
4331               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4332                   && isym->st_shndx != SHN_UNDEF)
4333                 *p++ = ELF_VER_CHR;
4334               memcpy (p, verstr, verlen + 1);
4335
4336               name = newname;
4337             }
4338
4339           /* If this symbol has default visibility and the user has
4340              requested we not re-export it, then mark it as hidden.  */
4341           if (!bfd_is_und_section (sec)
4342               && !dynamic
4343               && abfd->no_export
4344               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4345             isym->st_other = (STV_HIDDEN
4346                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4347
4348           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4349                                       sym_hash, &old_bfd, &old_weak,
4350                                       &old_alignment, &skip, &override,
4351                                       &type_change_ok, &size_change_ok,
4352                                       &matched))
4353             goto error_free_vers;
4354
4355           if (skip)
4356             continue;
4357
4358           /* Override a definition only if the new symbol matches the
4359              existing one.  */
4360           if (override && matched)
4361             definition = FALSE;
4362
4363           h = *sym_hash;
4364           while (h->root.type == bfd_link_hash_indirect
4365                  || h->root.type == bfd_link_hash_warning)
4366             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4367
4368           if (elf_tdata (abfd)->verdef != NULL
4369               && vernum > 1
4370               && definition)
4371             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4372         }
4373
4374       if (! (_bfd_generic_link_add_one_symbol
4375              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4376               (struct bfd_link_hash_entry **) sym_hash)))
4377         goto error_free_vers;
4378
4379       h = *sym_hash;
4380       /* We need to make sure that indirect symbol dynamic flags are
4381          updated.  */
4382       hi = h;
4383       while (h->root.type == bfd_link_hash_indirect
4384              || h->root.type == bfd_link_hash_warning)
4385         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4386
4387       *sym_hash = h;
4388
4389       new_weak = (flags & BSF_WEAK) != 0;
4390       new_weakdef = FALSE;
4391       if (dynamic
4392           && definition
4393           && new_weak
4394           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4395           && is_elf_hash_table (htab)
4396           && h->u.weakdef == NULL)
4397         {
4398           /* Keep a list of all weak defined non function symbols from
4399              a dynamic object, using the weakdef field.  Later in this
4400              function we will set the weakdef field to the correct
4401              value.  We only put non-function symbols from dynamic
4402              objects on this list, because that happens to be the only
4403              time we need to know the normal symbol corresponding to a
4404              weak symbol, and the information is time consuming to
4405              figure out.  If the weakdef field is not already NULL,
4406              then this symbol was already defined by some previous
4407              dynamic object, and we will be using that previous
4408              definition anyhow.  */
4409
4410           h->u.weakdef = weaks;
4411           weaks = h;
4412           new_weakdef = TRUE;
4413         }
4414
4415       /* Set the alignment of a common symbol.  */
4416       if ((common || bfd_is_com_section (sec))
4417           && h->root.type == bfd_link_hash_common)
4418         {
4419           unsigned int align;
4420
4421           if (common)
4422             align = bfd_log2 (isym->st_value);
4423           else
4424             {
4425               /* The new symbol is a common symbol in a shared object.
4426                  We need to get the alignment from the section.  */
4427               align = new_sec->alignment_power;
4428             }
4429           if (align > old_alignment)
4430             h->root.u.c.p->alignment_power = align;
4431           else
4432             h->root.u.c.p->alignment_power = old_alignment;
4433         }
4434
4435       if (is_elf_hash_table (htab))
4436         {
4437           /* Set a flag in the hash table entry indicating the type of
4438              reference or definition we just found.  A dynamic symbol
4439              is one which is referenced or defined by both a regular
4440              object and a shared object.  */
4441           bfd_boolean dynsym = FALSE;
4442
4443           /* Plugin symbols aren't normal.  Don't set def_regular or
4444              ref_regular for them, or make them dynamic.  */
4445           if ((abfd->flags & BFD_PLUGIN) != 0)
4446             ;
4447           else if (! dynamic)
4448             {
4449               if (! definition)
4450                 {
4451                   h->ref_regular = 1;
4452                   if (bind != STB_WEAK)
4453                     h->ref_regular_nonweak = 1;
4454                 }
4455               else
4456                 {
4457                   h->def_regular = 1;
4458                   if (h->def_dynamic)
4459                     {
4460                       h->def_dynamic = 0;
4461                       h->ref_dynamic = 1;
4462                     }
4463                 }
4464
4465               /* If the indirect symbol has been forced local, don't
4466                  make the real symbol dynamic.  */
4467               if ((h == hi || !hi->forced_local)
4468                   && (bfd_link_dll (info)
4469                       || h->def_dynamic
4470                       || h->ref_dynamic))
4471                 dynsym = TRUE;
4472             }
4473           else
4474             {
4475               if (! definition)
4476                 {
4477                   h->ref_dynamic = 1;
4478                   hi->ref_dynamic = 1;
4479                 }
4480               else
4481                 {
4482                   h->def_dynamic = 1;
4483                   hi->def_dynamic = 1;
4484                 }
4485
4486               /* If the indirect symbol has been forced local, don't
4487                  make the real symbol dynamic.  */
4488               if ((h == hi || !hi->forced_local)
4489                   && (h->def_regular
4490                       || h->ref_regular
4491                       || (h->u.weakdef != NULL
4492                           && ! new_weakdef
4493                           && h->u.weakdef->dynindx != -1)))
4494                 dynsym = TRUE;
4495             }
4496
4497           /* Check to see if we need to add an indirect symbol for
4498              the default name.  */
4499           if (definition
4500               || (!override && h->root.type == bfd_link_hash_common))
4501             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4502                                               sec, value, &old_bfd, &dynsym))
4503               goto error_free_vers;
4504
4505           /* Check the alignment when a common symbol is involved. This
4506              can change when a common symbol is overridden by a normal
4507              definition or a common symbol is ignored due to the old
4508              normal definition. We need to make sure the maximum
4509              alignment is maintained.  */
4510           if ((old_alignment || common)
4511               && h->root.type != bfd_link_hash_common)
4512             {
4513               unsigned int common_align;
4514               unsigned int normal_align;
4515               unsigned int symbol_align;
4516               bfd *normal_bfd;
4517               bfd *common_bfd;
4518
4519               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4520                           || h->root.type == bfd_link_hash_defweak);
4521
4522               symbol_align = ffs (h->root.u.def.value) - 1;
4523               if (h->root.u.def.section->owner != NULL
4524                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4525                 {
4526                   normal_align = h->root.u.def.section->alignment_power;
4527                   if (normal_align > symbol_align)
4528                     normal_align = symbol_align;
4529                 }
4530               else
4531                 normal_align = symbol_align;
4532
4533               if (old_alignment)
4534                 {
4535                   common_align = old_alignment;
4536                   common_bfd = old_bfd;
4537                   normal_bfd = abfd;
4538                 }
4539               else
4540                 {
4541                   common_align = bfd_log2 (isym->st_value);
4542                   common_bfd = abfd;
4543                   normal_bfd = old_bfd;
4544                 }
4545
4546               if (normal_align < common_align)
4547                 {
4548                   /* PR binutils/2735 */
4549                   if (normal_bfd == NULL)
4550                     (*_bfd_error_handler)
4551                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4552                          " greater than the alignment (%u) of its section %A"),
4553                        common_bfd, h->root.u.def.section,
4554                        1 << common_align, name, 1 << normal_align);
4555                   else
4556                     (*_bfd_error_handler)
4557                       (_("Warning: alignment %u of symbol `%s' in %B"
4558                          " is smaller than %u in %B"),
4559                        normal_bfd, common_bfd,
4560                        1 << normal_align, name, 1 << common_align);
4561                 }
4562             }
4563
4564           /* Remember the symbol size if it isn't undefined.  */
4565           if (isym->st_size != 0
4566               && isym->st_shndx != SHN_UNDEF
4567               && (definition || h->size == 0))
4568             {
4569               if (h->size != 0
4570                   && h->size != isym->st_size
4571                   && ! size_change_ok)
4572                 (*_bfd_error_handler)
4573                   (_("Warning: size of symbol `%s' changed"
4574                      " from %lu in %B to %lu in %B"),
4575                    old_bfd, abfd,
4576                    name, (unsigned long) h->size,
4577                    (unsigned long) isym->st_size);
4578
4579               h->size = isym->st_size;
4580             }
4581
4582           /* If this is a common symbol, then we always want H->SIZE
4583              to be the size of the common symbol.  The code just above
4584              won't fix the size if a common symbol becomes larger.  We
4585              don't warn about a size change here, because that is
4586              covered by --warn-common.  Allow changes between different
4587              function types.  */
4588           if (h->root.type == bfd_link_hash_common)
4589             h->size = h->root.u.c.size;
4590
4591           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4592               && ((definition && !new_weak)
4593                   || (old_weak && h->root.type == bfd_link_hash_common)
4594                   || h->type == STT_NOTYPE))
4595             {
4596               unsigned int type = ELF_ST_TYPE (isym->st_info);
4597
4598               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4599                  symbol.  */
4600               if (type == STT_GNU_IFUNC
4601                   && (abfd->flags & DYNAMIC) != 0)
4602                 type = STT_FUNC;
4603
4604               if (h->type != type)
4605                 {
4606                   if (h->type != STT_NOTYPE && ! type_change_ok)
4607                     (*_bfd_error_handler)
4608                       (_("Warning: type of symbol `%s' changed"
4609                          " from %d to %d in %B"),
4610                        abfd, name, h->type, type);
4611
4612                   h->type = type;
4613                 }
4614             }
4615
4616           /* Merge st_other field.  */
4617           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4618
4619           /* We don't want to make debug symbol dynamic.  */
4620           if (definition
4621               && (sec->flags & SEC_DEBUGGING)
4622               && !bfd_link_relocatable (info))
4623             dynsym = FALSE;
4624
4625           /* Nor should we make plugin symbols dynamic.  */
4626           if ((abfd->flags & BFD_PLUGIN) != 0)
4627             dynsym = FALSE;
4628
4629           if (definition)
4630             {
4631               h->target_internal = isym->st_target_internal;
4632               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4633             }
4634
4635           if (definition && !dynamic)
4636             {
4637               char *p = strchr (name, ELF_VER_CHR);
4638               if (p != NULL && p[1] != ELF_VER_CHR)
4639                 {
4640                   /* Queue non-default versions so that .symver x, x@FOO
4641                      aliases can be checked.  */
4642                   if (!nondeflt_vers)
4643                     {
4644                       amt = ((isymend - isym + 1)
4645                              * sizeof (struct elf_link_hash_entry *));
4646                       nondeflt_vers
4647                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4648                       if (!nondeflt_vers)
4649                         goto error_free_vers;
4650                     }
4651                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4652                 }
4653             }
4654
4655           if (dynsym && h->dynindx == -1)
4656             {
4657               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4658                 goto error_free_vers;
4659               if (h->u.weakdef != NULL
4660                   && ! new_weakdef
4661                   && h->u.weakdef->dynindx == -1)
4662                 {
4663                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4664                     goto error_free_vers;
4665                 }
4666             }
4667           else if (h->dynindx != -1)
4668             /* If the symbol already has a dynamic index, but
4669                visibility says it should not be visible, turn it into
4670                a local symbol.  */
4671             switch (ELF_ST_VISIBILITY (h->other))
4672               {
4673               case STV_INTERNAL:
4674               case STV_HIDDEN:
4675                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4676                 dynsym = FALSE;
4677                 break;
4678               }
4679
4680           /* Don't add DT_NEEDED for references from the dummy bfd nor
4681              for unmatched symbol.  */
4682           if (!add_needed
4683               && matched
4684               && definition
4685               && ((dynsym
4686                    && h->ref_regular_nonweak
4687                    && (old_bfd == NULL
4688                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4689                   || (h->ref_dynamic_nonweak
4690                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4691                       && !on_needed_list (elf_dt_name (abfd),
4692                                           htab->needed, NULL))))
4693             {
4694               int ret;
4695               const char *soname = elf_dt_name (abfd);
4696
4697               info->callbacks->minfo ("%!", soname, old_bfd,
4698                                       h->root.root.string);
4699
4700               /* A symbol from a library loaded via DT_NEEDED of some
4701                  other library is referenced by a regular object.
4702                  Add a DT_NEEDED entry for it.  Issue an error if
4703                  --no-add-needed is used and the reference was not
4704                  a weak one.  */
4705               if (old_bfd != NULL
4706                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4707                 {
4708                   (*_bfd_error_handler)
4709                     (_("%B: undefined reference to symbol '%s'"),
4710                      old_bfd, name);
4711                   bfd_set_error (bfd_error_missing_dso);
4712                   goto error_free_vers;
4713                 }
4714
4715               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4716                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4717
4718               add_needed = TRUE;
4719               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4720               if (ret < 0)
4721                 goto error_free_vers;
4722
4723               BFD_ASSERT (ret == 0);
4724             }
4725         }
4726     }
4727
4728   if (extversym != NULL)
4729     {
4730       free (extversym);
4731       extversym = NULL;
4732     }
4733
4734   if (isymbuf != NULL)
4735     {
4736       free (isymbuf);
4737       isymbuf = NULL;
4738     }
4739
4740   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4741     {
4742       unsigned int i;
4743
4744       /* Restore the symbol table.  */
4745       old_ent = (char *) old_tab + tabsize;
4746       memset (elf_sym_hashes (abfd), 0,
4747               extsymcount * sizeof (struct elf_link_hash_entry *));
4748       htab->root.table.table = old_table;
4749       htab->root.table.size = old_size;
4750       htab->root.table.count = old_count;
4751       memcpy (htab->root.table.table, old_tab, tabsize);
4752       htab->root.undefs = old_undefs;
4753       htab->root.undefs_tail = old_undefs_tail;
4754       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4755       for (i = 0; i < htab->root.table.size; i++)
4756         {
4757           struct bfd_hash_entry *p;
4758           struct elf_link_hash_entry *h;
4759           bfd_size_type size;
4760           unsigned int alignment_power;
4761
4762           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4763             {
4764               h = (struct elf_link_hash_entry *) p;
4765               if (h->root.type == bfd_link_hash_warning)
4766                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4767               if (h->dynindx >= old_dynsymcount
4768                   && h->dynstr_index < old_dynstr_size)
4769                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4770
4771               /* Preserve the maximum alignment and size for common
4772                  symbols even if this dynamic lib isn't on DT_NEEDED
4773                  since it can still be loaded at run time by another
4774                  dynamic lib.  */
4775               if (h->root.type == bfd_link_hash_common)
4776                 {
4777                   size = h->root.u.c.size;
4778                   alignment_power = h->root.u.c.p->alignment_power;
4779                 }
4780               else
4781                 {
4782                   size = 0;
4783                   alignment_power = 0;
4784                 }
4785               memcpy (p, old_ent, htab->root.table.entsize);
4786               old_ent = (char *) old_ent + htab->root.table.entsize;
4787               h = (struct elf_link_hash_entry *) p;
4788               if (h->root.type == bfd_link_hash_warning)
4789                 {
4790                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4791                   old_ent = (char *) old_ent + htab->root.table.entsize;
4792                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4793                 }
4794               if (h->root.type == bfd_link_hash_common)
4795                 {
4796                   if (size > h->root.u.c.size)
4797                     h->root.u.c.size = size;
4798                   if (alignment_power > h->root.u.c.p->alignment_power)
4799                     h->root.u.c.p->alignment_power = alignment_power;
4800                 }
4801             }
4802         }
4803
4804       /* Make a special call to the linker "notice" function to
4805          tell it that symbols added for crefs may need to be removed.  */
4806       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4807         goto error_free_vers;
4808
4809       free (old_tab);
4810       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4811                            alloc_mark);
4812       if (nondeflt_vers != NULL)
4813         free (nondeflt_vers);
4814       return TRUE;
4815     }
4816
4817   if (old_tab != NULL)
4818     {
4819       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4820         goto error_free_vers;
4821       free (old_tab);
4822       old_tab = NULL;
4823     }
4824
4825   /* Now that all the symbols from this input file are created, if
4826      not performing a relocatable link, handle .symver foo, foo@BAR
4827      such that any relocs against foo become foo@BAR.  */
4828   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4829     {
4830       bfd_size_type cnt, symidx;
4831
4832       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4833         {
4834           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4835           char *shortname, *p;
4836
4837           p = strchr (h->root.root.string, ELF_VER_CHR);
4838           if (p == NULL
4839               || (h->root.type != bfd_link_hash_defined
4840                   && h->root.type != bfd_link_hash_defweak))
4841             continue;
4842
4843           amt = p - h->root.root.string;
4844           shortname = (char *) bfd_malloc (amt + 1);
4845           if (!shortname)
4846             goto error_free_vers;
4847           memcpy (shortname, h->root.root.string, amt);
4848           shortname[amt] = '\0';
4849
4850           hi = (struct elf_link_hash_entry *)
4851                bfd_link_hash_lookup (&htab->root, shortname,
4852                                      FALSE, FALSE, FALSE);
4853           if (hi != NULL
4854               && hi->root.type == h->root.type
4855               && hi->root.u.def.value == h->root.u.def.value
4856               && hi->root.u.def.section == h->root.u.def.section)
4857             {
4858               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4859               hi->root.type = bfd_link_hash_indirect;
4860               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4861               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4862               sym_hash = elf_sym_hashes (abfd);
4863               if (sym_hash)
4864                 for (symidx = 0; symidx < extsymcount; ++symidx)
4865                   if (sym_hash[symidx] == hi)
4866                     {
4867                       sym_hash[symidx] = h;
4868                       break;
4869                     }
4870             }
4871           free (shortname);
4872         }
4873       free (nondeflt_vers);
4874       nondeflt_vers = NULL;
4875     }
4876
4877   /* Now set the weakdefs field correctly for all the weak defined
4878      symbols we found.  The only way to do this is to search all the
4879      symbols.  Since we only need the information for non functions in
4880      dynamic objects, that's the only time we actually put anything on
4881      the list WEAKS.  We need this information so that if a regular
4882      object refers to a symbol defined weakly in a dynamic object, the
4883      real symbol in the dynamic object is also put in the dynamic
4884      symbols; we also must arrange for both symbols to point to the
4885      same memory location.  We could handle the general case of symbol
4886      aliasing, but a general symbol alias can only be generated in
4887      assembler code, handling it correctly would be very time
4888      consuming, and other ELF linkers don't handle general aliasing
4889      either.  */
4890   if (weaks != NULL)
4891     {
4892       struct elf_link_hash_entry **hpp;
4893       struct elf_link_hash_entry **hppend;
4894       struct elf_link_hash_entry **sorted_sym_hash;
4895       struct elf_link_hash_entry *h;
4896       size_t sym_count;
4897
4898       /* Since we have to search the whole symbol list for each weak
4899          defined symbol, search time for N weak defined symbols will be
4900          O(N^2). Binary search will cut it down to O(NlogN).  */
4901       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4902       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4903       if (sorted_sym_hash == NULL)
4904         goto error_return;
4905       sym_hash = sorted_sym_hash;
4906       hpp = elf_sym_hashes (abfd);
4907       hppend = hpp + extsymcount;
4908       sym_count = 0;
4909       for (; hpp < hppend; hpp++)
4910         {
4911           h = *hpp;
4912           if (h != NULL
4913               && h->root.type == bfd_link_hash_defined
4914               && !bed->is_function_type (h->type))
4915             {
4916               *sym_hash = h;
4917               sym_hash++;
4918               sym_count++;
4919             }
4920         }
4921
4922       qsort (sorted_sym_hash, sym_count,
4923              sizeof (struct elf_link_hash_entry *),
4924              elf_sort_symbol);
4925
4926       while (weaks != NULL)
4927         {
4928           struct elf_link_hash_entry *hlook;
4929           asection *slook;
4930           bfd_vma vlook;
4931           size_t i, j, idx = 0;
4932
4933           hlook = weaks;
4934           weaks = hlook->u.weakdef;
4935           hlook->u.weakdef = NULL;
4936
4937           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4938                       || hlook->root.type == bfd_link_hash_defweak
4939                       || hlook->root.type == bfd_link_hash_common
4940                       || hlook->root.type == bfd_link_hash_indirect);
4941           slook = hlook->root.u.def.section;
4942           vlook = hlook->root.u.def.value;
4943
4944           i = 0;
4945           j = sym_count;
4946           while (i != j)
4947             {
4948               bfd_signed_vma vdiff;
4949               idx = (i + j) / 2;
4950               h = sorted_sym_hash[idx];
4951               vdiff = vlook - h->root.u.def.value;
4952               if (vdiff < 0)
4953                 j = idx;
4954               else if (vdiff > 0)
4955                 i = idx + 1;
4956               else
4957                 {
4958                   int sdiff = slook->id - h->root.u.def.section->id;
4959                   if (sdiff < 0)
4960                     j = idx;
4961                   else if (sdiff > 0)
4962                     i = idx + 1;
4963                   else
4964                     break;
4965                 }
4966             }
4967
4968           /* We didn't find a value/section match.  */
4969           if (i == j)
4970             continue;
4971
4972           /* With multiple aliases, or when the weak symbol is already
4973              strongly defined, we have multiple matching symbols and
4974              the binary search above may land on any of them.  Step
4975              one past the matching symbol(s).  */
4976           while (++idx != j)
4977             {
4978               h = sorted_sym_hash[idx];
4979               if (h->root.u.def.section != slook
4980                   || h->root.u.def.value != vlook)
4981                 break;
4982             }
4983
4984           /* Now look back over the aliases.  Since we sorted by size
4985              as well as value and section, we'll choose the one with
4986              the largest size.  */
4987           while (idx-- != i)
4988             {
4989               h = sorted_sym_hash[idx];
4990
4991               /* Stop if value or section doesn't match.  */
4992               if (h->root.u.def.section != slook
4993                   || h->root.u.def.value != vlook)
4994                 break;
4995               else if (h != hlook)
4996                 {
4997                   hlook->u.weakdef = h;
4998
4999                   /* If the weak definition is in the list of dynamic
5000                      symbols, make sure the real definition is put
5001                      there as well.  */
5002                   if (hlook->dynindx != -1 && h->dynindx == -1)
5003                     {
5004                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5005                         {
5006                         err_free_sym_hash:
5007                           free (sorted_sym_hash);
5008                           goto error_return;
5009                         }
5010                     }
5011
5012                   /* If the real definition is in the list of dynamic
5013                      symbols, make sure the weak definition is put
5014                      there as well.  If we don't do this, then the
5015                      dynamic loader might not merge the entries for the
5016                      real definition and the weak definition.  */
5017                   if (h->dynindx != -1 && hlook->dynindx == -1)
5018                     {
5019                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5020                         goto err_free_sym_hash;
5021                     }
5022                   break;
5023                 }
5024             }
5025         }
5026
5027       free (sorted_sym_hash);
5028     }
5029
5030   if (bed->check_directives
5031       && !(*bed->check_directives) (abfd, info))
5032     return FALSE;
5033
5034   if (!info->check_relocs_after_open_input
5035       && !_bfd_elf_link_check_relocs (abfd, info))
5036     return FALSE;
5037
5038   /* If this is a non-traditional link, try to optimize the handling
5039      of the .stab/.stabstr sections.  */
5040   if (! dynamic
5041       && ! info->traditional_format
5042       && is_elf_hash_table (htab)
5043       && (info->strip != strip_all && info->strip != strip_debugger))
5044     {
5045       asection *stabstr;
5046
5047       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5048       if (stabstr != NULL)
5049         {
5050           bfd_size_type string_offset = 0;
5051           asection *stab;
5052
5053           for (stab = abfd->sections; stab; stab = stab->next)
5054             if (CONST_STRNEQ (stab->name, ".stab")
5055                 && (!stab->name[5] ||
5056                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5057                 && (stab->flags & SEC_MERGE) == 0
5058                 && !bfd_is_abs_section (stab->output_section))
5059               {
5060                 struct bfd_elf_section_data *secdata;
5061
5062                 secdata = elf_section_data (stab);
5063                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5064                                                stabstr, &secdata->sec_info,
5065                                                &string_offset))
5066                   goto error_return;
5067                 if (secdata->sec_info)
5068                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5069             }
5070         }
5071     }
5072
5073   if (is_elf_hash_table (htab) && add_needed)
5074     {
5075       /* Add this bfd to the loaded list.  */
5076       struct elf_link_loaded_list *n;
5077
5078       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5079       if (n == NULL)
5080         goto error_return;
5081       n->abfd = abfd;
5082       n->next = htab->loaded;
5083       htab->loaded = n;
5084     }
5085
5086   return TRUE;
5087
5088  error_free_vers:
5089   if (old_tab != NULL)
5090     free (old_tab);
5091   if (nondeflt_vers != NULL)
5092     free (nondeflt_vers);
5093   if (extversym != NULL)
5094     free (extversym);
5095  error_free_sym:
5096   if (isymbuf != NULL)
5097     free (isymbuf);
5098  error_return:
5099   return FALSE;
5100 }
5101
5102 /* Return the linker hash table entry of a symbol that might be
5103    satisfied by an archive symbol.  Return -1 on error.  */
5104
5105 struct elf_link_hash_entry *
5106 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5107                                 struct bfd_link_info *info,
5108                                 const char *name)
5109 {
5110   struct elf_link_hash_entry *h;
5111   char *p, *copy;
5112   size_t len, first;
5113
5114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5115   if (h != NULL)
5116     return h;
5117
5118   /* If this is a default version (the name contains @@), look up the
5119      symbol again with only one `@' as well as without the version.
5120      The effect is that references to the symbol with and without the
5121      version will be matched by the default symbol in the archive.  */
5122
5123   p = strchr (name, ELF_VER_CHR);
5124   if (p == NULL || p[1] != ELF_VER_CHR)
5125     return h;
5126
5127   /* First check with only one `@'.  */
5128   len = strlen (name);
5129   copy = (char *) bfd_alloc (abfd, len);
5130   if (copy == NULL)
5131     return (struct elf_link_hash_entry *) 0 - 1;
5132
5133   first = p - name + 1;
5134   memcpy (copy, name, first);
5135   memcpy (copy + first, name + first + 1, len - first);
5136
5137   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5138   if (h == NULL)
5139     {
5140       /* We also need to check references to the symbol without the
5141          version.  */
5142       copy[first - 1] = '\0';
5143       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5144                                 FALSE, FALSE, TRUE);
5145     }
5146
5147   bfd_release (abfd, copy);
5148   return h;
5149 }
5150
5151 /* Add symbols from an ELF archive file to the linker hash table.  We
5152    don't use _bfd_generic_link_add_archive_symbols because we need to
5153    handle versioned symbols.
5154
5155    Fortunately, ELF archive handling is simpler than that done by
5156    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5157    oddities.  In ELF, if we find a symbol in the archive map, and the
5158    symbol is currently undefined, we know that we must pull in that
5159    object file.
5160
5161    Unfortunately, we do have to make multiple passes over the symbol
5162    table until nothing further is resolved.  */
5163
5164 static bfd_boolean
5165 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5166 {
5167   symindex c;
5168   unsigned char *included = NULL;
5169   carsym *symdefs;
5170   bfd_boolean loop;
5171   bfd_size_type amt;
5172   const struct elf_backend_data *bed;
5173   struct elf_link_hash_entry * (*archive_symbol_lookup)
5174     (bfd *, struct bfd_link_info *, const char *);
5175
5176   if (! bfd_has_map (abfd))
5177     {
5178       /* An empty archive is a special case.  */
5179       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5180         return TRUE;
5181       bfd_set_error (bfd_error_no_armap);
5182       return FALSE;
5183     }
5184
5185   /* Keep track of all symbols we know to be already defined, and all
5186      files we know to be already included.  This is to speed up the
5187      second and subsequent passes.  */
5188   c = bfd_ardata (abfd)->symdef_count;
5189   if (c == 0)
5190     return TRUE;
5191   amt = c;
5192   amt *= sizeof (*included);
5193   included = (unsigned char *) bfd_zmalloc (amt);
5194   if (included == NULL)
5195     return FALSE;
5196
5197   symdefs = bfd_ardata (abfd)->symdefs;
5198   bed = get_elf_backend_data (abfd);
5199   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5200
5201   do
5202     {
5203       file_ptr last;
5204       symindex i;
5205       carsym *symdef;
5206       carsym *symdefend;
5207
5208       loop = FALSE;
5209       last = -1;
5210
5211       symdef = symdefs;
5212       symdefend = symdef + c;
5213       for (i = 0; symdef < symdefend; symdef++, i++)
5214         {
5215           struct elf_link_hash_entry *h;
5216           bfd *element;
5217           struct bfd_link_hash_entry *undefs_tail;
5218           symindex mark;
5219
5220           if (included[i])
5221             continue;
5222           if (symdef->file_offset == last)
5223             {
5224               included[i] = TRUE;
5225               continue;
5226             }
5227
5228           h = archive_symbol_lookup (abfd, info, symdef->name);
5229           if (h == (struct elf_link_hash_entry *) 0 - 1)
5230             goto error_return;
5231
5232           if (h == NULL)
5233             continue;
5234
5235           if (h->root.type == bfd_link_hash_common)
5236             {
5237               /* We currently have a common symbol.  The archive map contains
5238                  a reference to this symbol, so we may want to include it.  We
5239                  only want to include it however, if this archive element
5240                  contains a definition of the symbol, not just another common
5241                  declaration of it.
5242
5243                  Unfortunately some archivers (including GNU ar) will put
5244                  declarations of common symbols into their archive maps, as
5245                  well as real definitions, so we cannot just go by the archive
5246                  map alone.  Instead we must read in the element's symbol
5247                  table and check that to see what kind of symbol definition
5248                  this is.  */
5249               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5250                 continue;
5251             }
5252           else if (h->root.type != bfd_link_hash_undefined)
5253             {
5254               if (h->root.type != bfd_link_hash_undefweak)
5255                 /* Symbol must be defined.  Don't check it again.  */
5256                 included[i] = TRUE;
5257               continue;
5258             }
5259
5260           /* We need to include this archive member.  */
5261           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5262           if (element == NULL)
5263             goto error_return;
5264
5265           if (! bfd_check_format (element, bfd_object))
5266             goto error_return;
5267
5268           undefs_tail = info->hash->undefs_tail;
5269
5270           if (!(*info->callbacks
5271                 ->add_archive_element) (info, element, symdef->name, &element))
5272             goto error_return;
5273           if (!bfd_link_add_symbols (element, info))
5274             goto error_return;
5275
5276           /* If there are any new undefined symbols, we need to make
5277              another pass through the archive in order to see whether
5278              they can be defined.  FIXME: This isn't perfect, because
5279              common symbols wind up on undefs_tail and because an
5280              undefined symbol which is defined later on in this pass
5281              does not require another pass.  This isn't a bug, but it
5282              does make the code less efficient than it could be.  */
5283           if (undefs_tail != info->hash->undefs_tail)
5284             loop = TRUE;
5285
5286           /* Look backward to mark all symbols from this object file
5287              which we have already seen in this pass.  */
5288           mark = i;
5289           do
5290             {
5291               included[mark] = TRUE;
5292               if (mark == 0)
5293                 break;
5294               --mark;
5295             }
5296           while (symdefs[mark].file_offset == symdef->file_offset);
5297
5298           /* We mark subsequent symbols from this object file as we go
5299              on through the loop.  */
5300           last = symdef->file_offset;
5301         }
5302     }
5303   while (loop);
5304
5305   free (included);
5306
5307   return TRUE;
5308
5309  error_return:
5310   if (included != NULL)
5311     free (included);
5312   return FALSE;
5313 }
5314
5315 /* Given an ELF BFD, add symbols to the global hash table as
5316    appropriate.  */
5317
5318 bfd_boolean
5319 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5320 {
5321   switch (bfd_get_format (abfd))
5322     {
5323     case bfd_object:
5324       return elf_link_add_object_symbols (abfd, info);
5325     case bfd_archive:
5326       return elf_link_add_archive_symbols (abfd, info);
5327     default:
5328       bfd_set_error (bfd_error_wrong_format);
5329       return FALSE;
5330     }
5331 }
5332 \f
5333 struct hash_codes_info
5334 {
5335   unsigned long *hashcodes;
5336   bfd_boolean error;
5337 };
5338
5339 /* This function will be called though elf_link_hash_traverse to store
5340    all hash value of the exported symbols in an array.  */
5341
5342 static bfd_boolean
5343 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5344 {
5345   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5346   const char *name;
5347   unsigned long ha;
5348   char *alc = NULL;
5349
5350   /* Ignore indirect symbols.  These are added by the versioning code.  */
5351   if (h->dynindx == -1)
5352     return TRUE;
5353
5354   name = h->root.root.string;
5355   if (h->versioned >= versioned)
5356     {
5357       char *p = strchr (name, ELF_VER_CHR);
5358       if (p != NULL)
5359         {
5360           alc = (char *) bfd_malloc (p - name + 1);
5361           if (alc == NULL)
5362             {
5363               inf->error = TRUE;
5364               return FALSE;
5365             }
5366           memcpy (alc, name, p - name);
5367           alc[p - name] = '\0';
5368           name = alc;
5369         }
5370     }
5371
5372   /* Compute the hash value.  */
5373   ha = bfd_elf_hash (name);
5374
5375   /* Store the found hash value in the array given as the argument.  */
5376   *(inf->hashcodes)++ = ha;
5377
5378   /* And store it in the struct so that we can put it in the hash table
5379      later.  */
5380   h->u.elf_hash_value = ha;
5381
5382   if (alc != NULL)
5383     free (alc);
5384
5385   return TRUE;
5386 }
5387
5388 struct collect_gnu_hash_codes
5389 {
5390   bfd *output_bfd;
5391   const struct elf_backend_data *bed;
5392   unsigned long int nsyms;
5393   unsigned long int maskbits;
5394   unsigned long int *hashcodes;
5395   unsigned long int *hashval;
5396   unsigned long int *indx;
5397   unsigned long int *counts;
5398   bfd_vma *bitmask;
5399   bfd_byte *contents;
5400   long int min_dynindx;
5401   unsigned long int bucketcount;
5402   unsigned long int symindx;
5403   long int local_indx;
5404   long int shift1, shift2;
5405   unsigned long int mask;
5406   bfd_boolean error;
5407 };
5408
5409 /* This function will be called though elf_link_hash_traverse to store
5410    all hash value of the exported symbols in an array.  */
5411
5412 static bfd_boolean
5413 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5414 {
5415   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5416   const char *name;
5417   unsigned long ha;
5418   char *alc = NULL;
5419
5420   /* Ignore indirect symbols.  These are added by the versioning code.  */
5421   if (h->dynindx == -1)
5422     return TRUE;
5423
5424   /* Ignore also local symbols and undefined symbols.  */
5425   if (! (*s->bed->elf_hash_symbol) (h))
5426     return TRUE;
5427
5428   name = h->root.root.string;
5429   if (h->versioned >= versioned)
5430     {
5431       char *p = strchr (name, ELF_VER_CHR);
5432       if (p != NULL)
5433         {
5434           alc = (char *) bfd_malloc (p - name + 1);
5435           if (alc == NULL)
5436             {
5437               s->error = TRUE;
5438               return FALSE;
5439             }
5440           memcpy (alc, name, p - name);
5441           alc[p - name] = '\0';
5442           name = alc;
5443         }
5444     }
5445
5446   /* Compute the hash value.  */
5447   ha = bfd_elf_gnu_hash (name);
5448
5449   /* Store the found hash value in the array for compute_bucket_count,
5450      and also for .dynsym reordering purposes.  */
5451   s->hashcodes[s->nsyms] = ha;
5452   s->hashval[h->dynindx] = ha;
5453   ++s->nsyms;
5454   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5455     s->min_dynindx = h->dynindx;
5456
5457   if (alc != NULL)
5458     free (alc);
5459
5460   return TRUE;
5461 }
5462
5463 /* This function will be called though elf_link_hash_traverse to do
5464    final dynaminc symbol renumbering.  */
5465
5466 static bfd_boolean
5467 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5468 {
5469   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5470   unsigned long int bucket;
5471   unsigned long int val;
5472
5473   /* Ignore indirect symbols.  */
5474   if (h->dynindx == -1)
5475     return TRUE;
5476
5477   /* Ignore also local symbols and undefined symbols.  */
5478   if (! (*s->bed->elf_hash_symbol) (h))
5479     {
5480       if (h->dynindx >= s->min_dynindx)
5481         h->dynindx = s->local_indx++;
5482       return TRUE;
5483     }
5484
5485   bucket = s->hashval[h->dynindx] % s->bucketcount;
5486   val = (s->hashval[h->dynindx] >> s->shift1)
5487         & ((s->maskbits >> s->shift1) - 1);
5488   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5489   s->bitmask[val]
5490     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5491   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5492   if (s->counts[bucket] == 1)
5493     /* Last element terminates the chain.  */
5494     val |= 1;
5495   bfd_put_32 (s->output_bfd, val,
5496               s->contents + (s->indx[bucket] - s->symindx) * 4);
5497   --s->counts[bucket];
5498   h->dynindx = s->indx[bucket]++;
5499   return TRUE;
5500 }
5501
5502 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5503
5504 bfd_boolean
5505 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5506 {
5507   return !(h->forced_local
5508            || h->root.type == bfd_link_hash_undefined
5509            || h->root.type == bfd_link_hash_undefweak
5510            || ((h->root.type == bfd_link_hash_defined
5511                 || h->root.type == bfd_link_hash_defweak)
5512                && h->root.u.def.section->output_section == NULL));
5513 }
5514
5515 /* Array used to determine the number of hash table buckets to use
5516    based on the number of symbols there are.  If there are fewer than
5517    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5518    fewer than 37 we use 17 buckets, and so forth.  We never use more
5519    than 32771 buckets.  */
5520
5521 static const size_t elf_buckets[] =
5522 {
5523   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5524   16411, 32771, 0
5525 };
5526
5527 /* Compute bucket count for hashing table.  We do not use a static set
5528    of possible tables sizes anymore.  Instead we determine for all
5529    possible reasonable sizes of the table the outcome (i.e., the
5530    number of collisions etc) and choose the best solution.  The
5531    weighting functions are not too simple to allow the table to grow
5532    without bounds.  Instead one of the weighting factors is the size.
5533    Therefore the result is always a good payoff between few collisions
5534    (= short chain lengths) and table size.  */
5535 static size_t
5536 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5537                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5538                       unsigned long int nsyms,
5539                       int gnu_hash)
5540 {
5541   size_t best_size = 0;
5542   unsigned long int i;
5543
5544   /* We have a problem here.  The following code to optimize the table
5545      size requires an integer type with more the 32 bits.  If
5546      BFD_HOST_U_64_BIT is set we know about such a type.  */
5547 #ifdef BFD_HOST_U_64_BIT
5548   if (info->optimize)
5549     {
5550       size_t minsize;
5551       size_t maxsize;
5552       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5553       bfd *dynobj = elf_hash_table (info)->dynobj;
5554       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5555       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5556       unsigned long int *counts;
5557       bfd_size_type amt;
5558       unsigned int no_improvement_count = 0;
5559
5560       /* Possible optimization parameters: if we have NSYMS symbols we say
5561          that the hashing table must at least have NSYMS/4 and at most
5562          2*NSYMS buckets.  */
5563       minsize = nsyms / 4;
5564       if (minsize == 0)
5565         minsize = 1;
5566       best_size = maxsize = nsyms * 2;
5567       if (gnu_hash)
5568         {
5569           if (minsize < 2)
5570             minsize = 2;
5571           if ((best_size & 31) == 0)
5572             ++best_size;
5573         }
5574
5575       /* Create array where we count the collisions in.  We must use bfd_malloc
5576          since the size could be large.  */
5577       amt = maxsize;
5578       amt *= sizeof (unsigned long int);
5579       counts = (unsigned long int *) bfd_malloc (amt);
5580       if (counts == NULL)
5581         return 0;
5582
5583       /* Compute the "optimal" size for the hash table.  The criteria is a
5584          minimal chain length.  The minor criteria is (of course) the size
5585          of the table.  */
5586       for (i = minsize; i < maxsize; ++i)
5587         {
5588           /* Walk through the array of hashcodes and count the collisions.  */
5589           BFD_HOST_U_64_BIT max;
5590           unsigned long int j;
5591           unsigned long int fact;
5592
5593           if (gnu_hash && (i & 31) == 0)
5594             continue;
5595
5596           memset (counts, '\0', i * sizeof (unsigned long int));
5597
5598           /* Determine how often each hash bucket is used.  */
5599           for (j = 0; j < nsyms; ++j)
5600             ++counts[hashcodes[j] % i];
5601
5602           /* For the weight function we need some information about the
5603              pagesize on the target.  This is information need not be 100%
5604              accurate.  Since this information is not available (so far) we
5605              define it here to a reasonable default value.  If it is crucial
5606              to have a better value some day simply define this value.  */
5607 # ifndef BFD_TARGET_PAGESIZE
5608 #  define BFD_TARGET_PAGESIZE   (4096)
5609 # endif
5610
5611           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5612              and the chains.  */
5613           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5614
5615 # if 1
5616           /* Variant 1: optimize for short chains.  We add the squares
5617              of all the chain lengths (which favors many small chain
5618              over a few long chains).  */
5619           for (j = 0; j < i; ++j)
5620             max += counts[j] * counts[j];
5621
5622           /* This adds penalties for the overall size of the table.  */
5623           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5624           max *= fact * fact;
5625 # else
5626           /* Variant 2: Optimize a lot more for small table.  Here we
5627              also add squares of the size but we also add penalties for
5628              empty slots (the +1 term).  */
5629           for (j = 0; j < i; ++j)
5630             max += (1 + counts[j]) * (1 + counts[j]);
5631
5632           /* The overall size of the table is considered, but not as
5633              strong as in variant 1, where it is squared.  */
5634           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5635           max *= fact;
5636 # endif
5637
5638           /* Compare with current best results.  */
5639           if (max < best_chlen)
5640             {
5641               best_chlen = max;
5642               best_size = i;
5643               no_improvement_count = 0;
5644             }
5645           /* PR 11843: Avoid futile long searches for the best bucket size
5646              when there are a large number of symbols.  */
5647           else if (++no_improvement_count == 100)
5648             break;
5649         }
5650
5651       free (counts);
5652     }
5653   else
5654 #endif /* defined (BFD_HOST_U_64_BIT) */
5655     {
5656       /* This is the fallback solution if no 64bit type is available or if we
5657          are not supposed to spend much time on optimizations.  We select the
5658          bucket count using a fixed set of numbers.  */
5659       for (i = 0; elf_buckets[i] != 0; i++)
5660         {
5661           best_size = elf_buckets[i];
5662           if (nsyms < elf_buckets[i + 1])
5663             break;
5664         }
5665       if (gnu_hash && best_size < 2)
5666         best_size = 2;
5667     }
5668
5669   return best_size;
5670 }
5671
5672 /* Size any SHT_GROUP section for ld -r.  */
5673
5674 bfd_boolean
5675 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5676 {
5677   bfd *ibfd;
5678
5679   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5680     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5681         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5682       return FALSE;
5683   return TRUE;
5684 }
5685
5686 /* Set a default stack segment size.  The value in INFO wins.  If it
5687    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5688    undefined it is initialized.  */
5689
5690 bfd_boolean
5691 bfd_elf_stack_segment_size (bfd *output_bfd,
5692                             struct bfd_link_info *info,
5693                             const char *legacy_symbol,
5694                             bfd_vma default_size)
5695 {
5696   struct elf_link_hash_entry *h = NULL;
5697
5698   /* Look for legacy symbol.  */
5699   if (legacy_symbol)
5700     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5701                               FALSE, FALSE, FALSE);
5702   if (h && (h->root.type == bfd_link_hash_defined
5703             || h->root.type == bfd_link_hash_defweak)
5704       && h->def_regular
5705       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5706     {
5707       /* The symbol has no type if specified on the command line.  */
5708       h->type = STT_OBJECT;
5709       if (info->stacksize)
5710         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5711                                output_bfd, legacy_symbol);
5712       else if (h->root.u.def.section != bfd_abs_section_ptr)
5713         (*_bfd_error_handler) (_("%B: %s not absolute"),
5714                                output_bfd, legacy_symbol);
5715       else
5716         info->stacksize = h->root.u.def.value;
5717     }
5718
5719   if (!info->stacksize)
5720     /* If the user didn't set a size, or explicitly inhibit the
5721        size, set it now.  */
5722     info->stacksize = default_size;
5723
5724   /* Provide the legacy symbol, if it is referenced.  */
5725   if (h && (h->root.type == bfd_link_hash_undefined
5726             || h->root.type == bfd_link_hash_undefweak))
5727     {
5728       struct bfd_link_hash_entry *bh = NULL;
5729
5730       if (!(_bfd_generic_link_add_one_symbol
5731             (info, output_bfd, legacy_symbol,
5732              BSF_GLOBAL, bfd_abs_section_ptr,
5733              info->stacksize >= 0 ? info->stacksize : 0,
5734              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5735         return FALSE;
5736
5737       h = (struct elf_link_hash_entry *) bh;
5738       h->def_regular = 1;
5739       h->type = STT_OBJECT;
5740     }
5741
5742   return TRUE;
5743 }
5744
5745 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5746    called by the ELF linker emulation before_allocation routine.  We
5747    must set the sizes of the sections before the linker sets the
5748    addresses of the various sections.  */
5749
5750 bfd_boolean
5751 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5752                                const char *soname,
5753                                const char *rpath,
5754                                const char *filter_shlib,
5755                                const char *audit,
5756                                const char *depaudit,
5757                                const char * const *auxiliary_filters,
5758                                struct bfd_link_info *info,
5759                                asection **sinterpptr)
5760 {
5761   bfd_size_type soname_indx;
5762   bfd *dynobj;
5763   const struct elf_backend_data *bed;
5764   struct elf_info_failed asvinfo;
5765
5766   *sinterpptr = NULL;
5767
5768   soname_indx = (bfd_size_type) -1;
5769
5770   if (!is_elf_hash_table (info->hash))
5771     return TRUE;
5772
5773   bed = get_elf_backend_data (output_bfd);
5774
5775   /* Any syms created from now on start with -1 in
5776      got.refcount/offset and plt.refcount/offset.  */
5777   elf_hash_table (info)->init_got_refcount
5778     = elf_hash_table (info)->init_got_offset;
5779   elf_hash_table (info)->init_plt_refcount
5780     = elf_hash_table (info)->init_plt_offset;
5781
5782   if (bfd_link_relocatable (info)
5783       && !_bfd_elf_size_group_sections (info))
5784     return FALSE;
5785
5786   /* The backend may have to create some sections regardless of whether
5787      we're dynamic or not.  */
5788   if (bed->elf_backend_always_size_sections
5789       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5790     return FALSE;
5791
5792   /* Determine any GNU_STACK segment requirements, after the backend
5793      has had a chance to set a default segment size.  */
5794   if (info->execstack)
5795     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5796   else if (info->noexecstack)
5797     elf_stack_flags (output_bfd) = PF_R | PF_W;
5798   else
5799     {
5800       bfd *inputobj;
5801       asection *notesec = NULL;
5802       int exec = 0;
5803
5804       for (inputobj = info->input_bfds;
5805            inputobj;
5806            inputobj = inputobj->link.next)
5807         {
5808           asection *s;
5809
5810           if (inputobj->flags
5811               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5812             continue;
5813           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5814           if (s)
5815             {
5816               if (s->flags & SEC_CODE)
5817                 exec = PF_X;
5818               notesec = s;
5819             }
5820           else if (bed->default_execstack)
5821             exec = PF_X;
5822         }
5823       if (notesec || info->stacksize > 0)
5824         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5825       if (notesec && exec && bfd_link_relocatable (info)
5826           && notesec->output_section != bfd_abs_section_ptr)
5827         notesec->output_section->flags |= SEC_CODE;
5828     }
5829
5830   dynobj = elf_hash_table (info)->dynobj;
5831
5832   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5833     {
5834       struct elf_info_failed eif;
5835       struct elf_link_hash_entry *h;
5836       asection *dynstr;
5837       struct bfd_elf_version_tree *t;
5838       struct bfd_elf_version_expr *d;
5839       asection *s;
5840       bfd_boolean all_defined;
5841
5842       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5843       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
5844
5845       if (soname != NULL)
5846         {
5847           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5848                                              soname, TRUE);
5849           if (soname_indx == (bfd_size_type) -1
5850               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5851             return FALSE;
5852         }
5853
5854       if (info->symbolic)
5855         {
5856           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5857             return FALSE;
5858           info->flags |= DF_SYMBOLIC;
5859         }
5860
5861       if (rpath != NULL)
5862         {
5863           bfd_size_type indx;
5864           bfd_vma tag;
5865
5866           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5867                                       TRUE);
5868           if (indx == (bfd_size_type) -1)
5869             return FALSE;
5870
5871           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5872           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5873             return FALSE;
5874         }
5875
5876       if (filter_shlib != NULL)
5877         {
5878           bfd_size_type indx;
5879
5880           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5881                                       filter_shlib, TRUE);
5882           if (indx == (bfd_size_type) -1
5883               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5884             return FALSE;
5885         }
5886
5887       if (auxiliary_filters != NULL)
5888         {
5889           const char * const *p;
5890
5891           for (p = auxiliary_filters; *p != NULL; p++)
5892             {
5893               bfd_size_type indx;
5894
5895               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5896                                           *p, TRUE);
5897               if (indx == (bfd_size_type) -1
5898                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5899                 return FALSE;
5900             }
5901         }
5902
5903       if (audit != NULL)
5904         {
5905           bfd_size_type indx;
5906
5907           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5908                                       TRUE);
5909           if (indx == (bfd_size_type) -1
5910               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5911             return FALSE;
5912         }
5913
5914       if (depaudit != NULL)
5915         {
5916           bfd_size_type indx;
5917
5918           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5919                                       TRUE);
5920           if (indx == (bfd_size_type) -1
5921               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5922             return FALSE;
5923         }
5924
5925       eif.info = info;
5926       eif.failed = FALSE;
5927
5928       /* If we are supposed to export all symbols into the dynamic symbol
5929          table (this is not the normal case), then do so.  */
5930       if (info->export_dynamic
5931           || (bfd_link_executable (info) && info->dynamic))
5932         {
5933           elf_link_hash_traverse (elf_hash_table (info),
5934                                   _bfd_elf_export_symbol,
5935                                   &eif);
5936           if (eif.failed)
5937             return FALSE;
5938         }
5939
5940       /* Make all global versions with definition.  */
5941       for (t = info->version_info; t != NULL; t = t->next)
5942         for (d = t->globals.list; d != NULL; d = d->next)
5943           if (!d->symver && d->literal)
5944             {
5945               const char *verstr, *name;
5946               size_t namelen, verlen, newlen;
5947               char *newname, *p, leading_char;
5948               struct elf_link_hash_entry *newh;
5949
5950               leading_char = bfd_get_symbol_leading_char (output_bfd);
5951               name = d->pattern;
5952               namelen = strlen (name) + (leading_char != '\0');
5953               verstr = t->name;
5954               verlen = strlen (verstr);
5955               newlen = namelen + verlen + 3;
5956
5957               newname = (char *) bfd_malloc (newlen);
5958               if (newname == NULL)
5959                 return FALSE;
5960               newname[0] = leading_char;
5961               memcpy (newname + (leading_char != '\0'), name, namelen);
5962
5963               /* Check the hidden versioned definition.  */
5964               p = newname + namelen;
5965               *p++ = ELF_VER_CHR;
5966               memcpy (p, verstr, verlen + 1);
5967               newh = elf_link_hash_lookup (elf_hash_table (info),
5968                                            newname, FALSE, FALSE,
5969                                            FALSE);
5970               if (newh == NULL
5971                   || (newh->root.type != bfd_link_hash_defined
5972                       && newh->root.type != bfd_link_hash_defweak))
5973                 {
5974                   /* Check the default versioned definition.  */
5975                   *p++ = ELF_VER_CHR;
5976                   memcpy (p, verstr, verlen + 1);
5977                   newh = elf_link_hash_lookup (elf_hash_table (info),
5978                                                newname, FALSE, FALSE,
5979                                                FALSE);
5980                 }
5981               free (newname);
5982
5983               /* Mark this version if there is a definition and it is
5984                  not defined in a shared object.  */
5985               if (newh != NULL
5986                   && !newh->def_dynamic
5987                   && (newh->root.type == bfd_link_hash_defined
5988                       || newh->root.type == bfd_link_hash_defweak))
5989                 d->symver = 1;
5990             }
5991
5992       /* Attach all the symbols to their version information.  */
5993       asvinfo.info = info;
5994       asvinfo.failed = FALSE;
5995
5996       elf_link_hash_traverse (elf_hash_table (info),
5997                               _bfd_elf_link_assign_sym_version,
5998                               &asvinfo);
5999       if (asvinfo.failed)
6000         return FALSE;
6001
6002       if (!info->allow_undefined_version)
6003         {
6004           /* Check if all global versions have a definition.  */
6005           all_defined = TRUE;
6006           for (t = info->version_info; t != NULL; t = t->next)
6007             for (d = t->globals.list; d != NULL; d = d->next)
6008               if (d->literal && !d->symver && !d->script)
6009                 {
6010                   (*_bfd_error_handler)
6011                     (_("%s: undefined version: %s"),
6012                      d->pattern, t->name);
6013                   all_defined = FALSE;
6014                 }
6015
6016           if (!all_defined)
6017             {
6018               bfd_set_error (bfd_error_bad_value);
6019               return FALSE;
6020             }
6021         }
6022
6023       /* Find all symbols which were defined in a dynamic object and make
6024          the backend pick a reasonable value for them.  */
6025       elf_link_hash_traverse (elf_hash_table (info),
6026                               _bfd_elf_adjust_dynamic_symbol,
6027                               &eif);
6028       if (eif.failed)
6029         return FALSE;
6030
6031       /* Add some entries to the .dynamic section.  We fill in some of the
6032          values later, in bfd_elf_final_link, but we must add the entries
6033          now so that we know the final size of the .dynamic section.  */
6034
6035       /* If there are initialization and/or finalization functions to
6036          call then add the corresponding DT_INIT/DT_FINI entries.  */
6037       h = (info->init_function
6038            ? elf_link_hash_lookup (elf_hash_table (info),
6039                                    info->init_function, FALSE,
6040                                    FALSE, FALSE)
6041            : NULL);
6042       if (h != NULL
6043           && (h->ref_regular
6044               || h->def_regular))
6045         {
6046           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6047             return FALSE;
6048         }
6049       h = (info->fini_function
6050            ? elf_link_hash_lookup (elf_hash_table (info),
6051                                    info->fini_function, FALSE,
6052                                    FALSE, FALSE)
6053            : NULL);
6054       if (h != NULL
6055           && (h->ref_regular
6056               || h->def_regular))
6057         {
6058           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6059             return FALSE;
6060         }
6061
6062       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6063       if (s != NULL && s->linker_has_input)
6064         {
6065           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6066           if (! bfd_link_executable (info))
6067             {
6068               bfd *sub;
6069               asection *o;
6070
6071               for (sub = info->input_bfds; sub != NULL;
6072                    sub = sub->link.next)
6073                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6074                   for (o = sub->sections; o != NULL; o = o->next)
6075                     if (elf_section_data (o)->this_hdr.sh_type
6076                         == SHT_PREINIT_ARRAY)
6077                       {
6078                         (*_bfd_error_handler)
6079                           (_("%B: .preinit_array section is not allowed in DSO"),
6080                            sub);
6081                         break;
6082                       }
6083
6084               bfd_set_error (bfd_error_nonrepresentable_section);
6085               return FALSE;
6086             }
6087
6088           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6089               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6090             return FALSE;
6091         }
6092       s = bfd_get_section_by_name (output_bfd, ".init_array");
6093       if (s != NULL && s->linker_has_input)
6094         {
6095           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6096               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6097             return FALSE;
6098         }
6099       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6100       if (s != NULL && s->linker_has_input)
6101         {
6102           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6103               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6104             return FALSE;
6105         }
6106
6107       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6108       /* If .dynstr is excluded from the link, we don't want any of
6109          these tags.  Strictly, we should be checking each section
6110          individually;  This quick check covers for the case where
6111          someone does a /DISCARD/ : { *(*) }.  */
6112       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6113         {
6114           bfd_size_type strsize;
6115
6116           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6117           if ((info->emit_hash
6118                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6119               || (info->emit_gnu_hash
6120                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6121               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6122               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6123               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6124               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6125                                               bed->s->sizeof_sym))
6126             return FALSE;
6127         }
6128     }
6129
6130   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6131     return FALSE;
6132
6133   /* The backend must work out the sizes of all the other dynamic
6134      sections.  */
6135   if (dynobj != NULL
6136       && bed->elf_backend_size_dynamic_sections != NULL
6137       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6138     return FALSE;
6139
6140   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6141     {
6142       unsigned long section_sym_count;
6143       struct bfd_elf_version_tree *verdefs;
6144       asection *s;
6145
6146       /* Set up the version definition section.  */
6147       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6148       BFD_ASSERT (s != NULL);
6149
6150       /* We may have created additional version definitions if we are
6151          just linking a regular application.  */
6152       verdefs = info->version_info;
6153
6154       /* Skip anonymous version tag.  */
6155       if (verdefs != NULL && verdefs->vernum == 0)
6156         verdefs = verdefs->next;
6157
6158       if (verdefs == NULL && !info->create_default_symver)
6159         s->flags |= SEC_EXCLUDE;
6160       else
6161         {
6162           unsigned int cdefs;
6163           bfd_size_type size;
6164           struct bfd_elf_version_tree *t;
6165           bfd_byte *p;
6166           Elf_Internal_Verdef def;
6167           Elf_Internal_Verdaux defaux;
6168           struct bfd_link_hash_entry *bh;
6169           struct elf_link_hash_entry *h;
6170           const char *name;
6171
6172           cdefs = 0;
6173           size = 0;
6174
6175           /* Make space for the base version.  */
6176           size += sizeof (Elf_External_Verdef);
6177           size += sizeof (Elf_External_Verdaux);
6178           ++cdefs;
6179
6180           /* Make space for the default version.  */
6181           if (info->create_default_symver)
6182             {
6183               size += sizeof (Elf_External_Verdef);
6184               ++cdefs;
6185             }
6186
6187           for (t = verdefs; t != NULL; t = t->next)
6188             {
6189               struct bfd_elf_version_deps *n;
6190
6191               /* Don't emit base version twice.  */
6192               if (t->vernum == 0)
6193                 continue;
6194
6195               size += sizeof (Elf_External_Verdef);
6196               size += sizeof (Elf_External_Verdaux);
6197               ++cdefs;
6198
6199               for (n = t->deps; n != NULL; n = n->next)
6200                 size += sizeof (Elf_External_Verdaux);
6201             }
6202
6203           s->size = size;
6204           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6205           if (s->contents == NULL && s->size != 0)
6206             return FALSE;
6207
6208           /* Fill in the version definition section.  */
6209
6210           p = s->contents;
6211
6212           def.vd_version = VER_DEF_CURRENT;
6213           def.vd_flags = VER_FLG_BASE;
6214           def.vd_ndx = 1;
6215           def.vd_cnt = 1;
6216           if (info->create_default_symver)
6217             {
6218               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6219               def.vd_next = sizeof (Elf_External_Verdef);
6220             }
6221           else
6222             {
6223               def.vd_aux = sizeof (Elf_External_Verdef);
6224               def.vd_next = (sizeof (Elf_External_Verdef)
6225                              + sizeof (Elf_External_Verdaux));
6226             }
6227
6228           if (soname_indx != (bfd_size_type) -1)
6229             {
6230               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6231                                       soname_indx);
6232               def.vd_hash = bfd_elf_hash (soname);
6233               defaux.vda_name = soname_indx;
6234               name = soname;
6235             }
6236           else
6237             {
6238               bfd_size_type indx;
6239
6240               name = lbasename (output_bfd->filename);
6241               def.vd_hash = bfd_elf_hash (name);
6242               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6243                                           name, FALSE);
6244               if (indx == (bfd_size_type) -1)
6245                 return FALSE;
6246               defaux.vda_name = indx;
6247             }
6248           defaux.vda_next = 0;
6249
6250           _bfd_elf_swap_verdef_out (output_bfd, &def,
6251                                     (Elf_External_Verdef *) p);
6252           p += sizeof (Elf_External_Verdef);
6253           if (info->create_default_symver)
6254             {
6255               /* Add a symbol representing this version.  */
6256               bh = NULL;
6257               if (! (_bfd_generic_link_add_one_symbol
6258                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6259                       0, NULL, FALSE,
6260                       get_elf_backend_data (dynobj)->collect, &bh)))
6261                 return FALSE;
6262               h = (struct elf_link_hash_entry *) bh;
6263               h->non_elf = 0;
6264               h->def_regular = 1;
6265               h->type = STT_OBJECT;
6266               h->verinfo.vertree = NULL;
6267
6268               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6269                 return FALSE;
6270
6271               /* Create a duplicate of the base version with the same
6272                  aux block, but different flags.  */
6273               def.vd_flags = 0;
6274               def.vd_ndx = 2;
6275               def.vd_aux = sizeof (Elf_External_Verdef);
6276               if (verdefs)
6277                 def.vd_next = (sizeof (Elf_External_Verdef)
6278                                + sizeof (Elf_External_Verdaux));
6279               else
6280                 def.vd_next = 0;
6281               _bfd_elf_swap_verdef_out (output_bfd, &def,
6282                                         (Elf_External_Verdef *) p);
6283               p += sizeof (Elf_External_Verdef);
6284             }
6285           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6286                                      (Elf_External_Verdaux *) p);
6287           p += sizeof (Elf_External_Verdaux);
6288
6289           for (t = verdefs; t != NULL; t = t->next)
6290             {
6291               unsigned int cdeps;
6292               struct bfd_elf_version_deps *n;
6293
6294               /* Don't emit the base version twice.  */
6295               if (t->vernum == 0)
6296                 continue;
6297
6298               cdeps = 0;
6299               for (n = t->deps; n != NULL; n = n->next)
6300                 ++cdeps;
6301
6302               /* Add a symbol representing this version.  */
6303               bh = NULL;
6304               if (! (_bfd_generic_link_add_one_symbol
6305                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6306                       0, NULL, FALSE,
6307                       get_elf_backend_data (dynobj)->collect, &bh)))
6308                 return FALSE;
6309               h = (struct elf_link_hash_entry *) bh;
6310               h->non_elf = 0;
6311               h->def_regular = 1;
6312               h->type = STT_OBJECT;
6313               h->verinfo.vertree = t;
6314
6315               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6316                 return FALSE;
6317
6318               def.vd_version = VER_DEF_CURRENT;
6319               def.vd_flags = 0;
6320               if (t->globals.list == NULL
6321                   && t->locals.list == NULL
6322                   && ! t->used)
6323                 def.vd_flags |= VER_FLG_WEAK;
6324               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6325               def.vd_cnt = cdeps + 1;
6326               def.vd_hash = bfd_elf_hash (t->name);
6327               def.vd_aux = sizeof (Elf_External_Verdef);
6328               def.vd_next = 0;
6329
6330               /* If a basever node is next, it *must* be the last node in
6331                  the chain, otherwise Verdef construction breaks.  */
6332               if (t->next != NULL && t->next->vernum == 0)
6333                 BFD_ASSERT (t->next->next == NULL);
6334
6335               if (t->next != NULL && t->next->vernum != 0)
6336                 def.vd_next = (sizeof (Elf_External_Verdef)
6337                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6338
6339               _bfd_elf_swap_verdef_out (output_bfd, &def,
6340                                         (Elf_External_Verdef *) p);
6341               p += sizeof (Elf_External_Verdef);
6342
6343               defaux.vda_name = h->dynstr_index;
6344               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6345                                       h->dynstr_index);
6346               defaux.vda_next = 0;
6347               if (t->deps != NULL)
6348                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6349               t->name_indx = defaux.vda_name;
6350
6351               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6352                                          (Elf_External_Verdaux *) p);
6353               p += sizeof (Elf_External_Verdaux);
6354
6355               for (n = t->deps; n != NULL; n = n->next)
6356                 {
6357                   if (n->version_needed == NULL)
6358                     {
6359                       /* This can happen if there was an error in the
6360                          version script.  */
6361                       defaux.vda_name = 0;
6362                     }
6363                   else
6364                     {
6365                       defaux.vda_name = n->version_needed->name_indx;
6366                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6367                                               defaux.vda_name);
6368                     }
6369                   if (n->next == NULL)
6370                     defaux.vda_next = 0;
6371                   else
6372                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6373
6374                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6375                                              (Elf_External_Verdaux *) p);
6376                   p += sizeof (Elf_External_Verdaux);
6377                 }
6378             }
6379
6380           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6381               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6382             return FALSE;
6383
6384           elf_tdata (output_bfd)->cverdefs = cdefs;
6385         }
6386
6387       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6388         {
6389           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6390             return FALSE;
6391         }
6392       else if (info->flags & DF_BIND_NOW)
6393         {
6394           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6395             return FALSE;
6396         }
6397
6398       if (info->flags_1)
6399         {
6400           if (bfd_link_executable (info))
6401             info->flags_1 &= ~ (DF_1_INITFIRST
6402                                 | DF_1_NODELETE
6403                                 | DF_1_NOOPEN);
6404           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6405             return FALSE;
6406         }
6407
6408       /* Work out the size of the version reference section.  */
6409
6410       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6411       BFD_ASSERT (s != NULL);
6412       {
6413         struct elf_find_verdep_info sinfo;
6414
6415         sinfo.info = info;
6416         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6417         if (sinfo.vers == 0)
6418           sinfo.vers = 1;
6419         sinfo.failed = FALSE;
6420
6421         elf_link_hash_traverse (elf_hash_table (info),
6422                                 _bfd_elf_link_find_version_dependencies,
6423                                 &sinfo);
6424         if (sinfo.failed)
6425           return FALSE;
6426
6427         if (elf_tdata (output_bfd)->verref == NULL)
6428           s->flags |= SEC_EXCLUDE;
6429         else
6430           {
6431             Elf_Internal_Verneed *t;
6432             unsigned int size;
6433             unsigned int crefs;
6434             bfd_byte *p;
6435
6436             /* Build the version dependency section.  */
6437             size = 0;
6438             crefs = 0;
6439             for (t = elf_tdata (output_bfd)->verref;
6440                  t != NULL;
6441                  t = t->vn_nextref)
6442               {
6443                 Elf_Internal_Vernaux *a;
6444
6445                 size += sizeof (Elf_External_Verneed);
6446                 ++crefs;
6447                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6448                   size += sizeof (Elf_External_Vernaux);
6449               }
6450
6451             s->size = size;
6452             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6453             if (s->contents == NULL)
6454               return FALSE;
6455
6456             p = s->contents;
6457             for (t = elf_tdata (output_bfd)->verref;
6458                  t != NULL;
6459                  t = t->vn_nextref)
6460               {
6461                 unsigned int caux;
6462                 Elf_Internal_Vernaux *a;
6463                 bfd_size_type indx;
6464
6465                 caux = 0;
6466                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6467                   ++caux;
6468
6469                 t->vn_version = VER_NEED_CURRENT;
6470                 t->vn_cnt = caux;
6471                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6472                                             elf_dt_name (t->vn_bfd) != NULL
6473                                             ? elf_dt_name (t->vn_bfd)
6474                                             : lbasename (t->vn_bfd->filename),
6475                                             FALSE);
6476                 if (indx == (bfd_size_type) -1)
6477                   return FALSE;
6478                 t->vn_file = indx;
6479                 t->vn_aux = sizeof (Elf_External_Verneed);
6480                 if (t->vn_nextref == NULL)
6481                   t->vn_next = 0;
6482                 else
6483                   t->vn_next = (sizeof (Elf_External_Verneed)
6484                                 + caux * sizeof (Elf_External_Vernaux));
6485
6486                 _bfd_elf_swap_verneed_out (output_bfd, t,
6487                                            (Elf_External_Verneed *) p);
6488                 p += sizeof (Elf_External_Verneed);
6489
6490                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6491                   {
6492                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6493                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6494                                                 a->vna_nodename, FALSE);
6495                     if (indx == (bfd_size_type) -1)
6496                       return FALSE;
6497                     a->vna_name = indx;
6498                     if (a->vna_nextptr == NULL)
6499                       a->vna_next = 0;
6500                     else
6501                       a->vna_next = sizeof (Elf_External_Vernaux);
6502
6503                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6504                                                (Elf_External_Vernaux *) p);
6505                     p += sizeof (Elf_External_Vernaux);
6506                   }
6507               }
6508
6509             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6510                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6511               return FALSE;
6512
6513             elf_tdata (output_bfd)->cverrefs = crefs;
6514           }
6515       }
6516
6517       if ((elf_tdata (output_bfd)->cverrefs == 0
6518            && elf_tdata (output_bfd)->cverdefs == 0)
6519           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6520                                              &section_sym_count) == 0)
6521         {
6522           s = bfd_get_linker_section (dynobj, ".gnu.version");
6523           s->flags |= SEC_EXCLUDE;
6524         }
6525     }
6526   return TRUE;
6527 }
6528
6529 /* Find the first non-excluded output section.  We'll use its
6530    section symbol for some emitted relocs.  */
6531 void
6532 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6533 {
6534   asection *s;
6535
6536   for (s = output_bfd->sections; s != NULL; s = s->next)
6537     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6538         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6539       {
6540         elf_hash_table (info)->text_index_section = s;
6541         break;
6542       }
6543 }
6544
6545 /* Find two non-excluded output sections, one for code, one for data.
6546    We'll use their section symbols for some emitted relocs.  */
6547 void
6548 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6549 {
6550   asection *s;
6551
6552   /* Data first, since setting text_index_section changes
6553      _bfd_elf_link_omit_section_dynsym.  */
6554   for (s = output_bfd->sections; s != NULL; s = s->next)
6555     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6556         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6557       {
6558         elf_hash_table (info)->data_index_section = s;
6559         break;
6560       }
6561
6562   for (s = output_bfd->sections; s != NULL; s = s->next)
6563     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6564          == (SEC_ALLOC | SEC_READONLY))
6565         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6566       {
6567         elf_hash_table (info)->text_index_section = s;
6568         break;
6569       }
6570
6571   if (elf_hash_table (info)->text_index_section == NULL)
6572     elf_hash_table (info)->text_index_section
6573       = elf_hash_table (info)->data_index_section;
6574 }
6575
6576 bfd_boolean
6577 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6578 {
6579   const struct elf_backend_data *bed;
6580
6581   if (!is_elf_hash_table (info->hash))
6582     return TRUE;
6583
6584   bed = get_elf_backend_data (output_bfd);
6585   (*bed->elf_backend_init_index_section) (output_bfd, info);
6586
6587   if (elf_hash_table (info)->dynamic_sections_created)
6588     {
6589       bfd *dynobj;
6590       asection *s;
6591       bfd_size_type dynsymcount;
6592       unsigned long section_sym_count;
6593       unsigned int dtagcount;
6594
6595       dynobj = elf_hash_table (info)->dynobj;
6596
6597       /* Assign dynsym indicies.  In a shared library we generate a
6598          section symbol for each output section, which come first.
6599          Next come all of the back-end allocated local dynamic syms,
6600          followed by the rest of the global symbols.  */
6601
6602       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6603                                                     &section_sym_count);
6604
6605       /* Work out the size of the symbol version section.  */
6606       s = bfd_get_linker_section (dynobj, ".gnu.version");
6607       BFD_ASSERT (s != NULL);
6608       if (dynsymcount != 0
6609           && (s->flags & SEC_EXCLUDE) == 0)
6610         {
6611           s->size = dynsymcount * sizeof (Elf_External_Versym);
6612           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6613           if (s->contents == NULL)
6614             return FALSE;
6615
6616           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6617             return FALSE;
6618         }
6619
6620       /* Set the size of the .dynsym and .hash sections.  We counted
6621          the number of dynamic symbols in elf_link_add_object_symbols.
6622          We will build the contents of .dynsym and .hash when we build
6623          the final symbol table, because until then we do not know the
6624          correct value to give the symbols.  We built the .dynstr
6625          section as we went along in elf_link_add_object_symbols.  */
6626       s = elf_hash_table (info)->dynsym;
6627       BFD_ASSERT (s != NULL);
6628       s->size = dynsymcount * bed->s->sizeof_sym;
6629
6630       if (dynsymcount != 0)
6631         {
6632           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6633           if (s->contents == NULL)
6634             return FALSE;
6635
6636           /* The first entry in .dynsym is a dummy symbol.
6637              Clear all the section syms, in case we don't output them all.  */
6638           ++section_sym_count;
6639           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6640         }
6641
6642       elf_hash_table (info)->bucketcount = 0;
6643
6644       /* Compute the size of the hashing table.  As a side effect this
6645          computes the hash values for all the names we export.  */
6646       if (info->emit_hash)
6647         {
6648           unsigned long int *hashcodes;
6649           struct hash_codes_info hashinf;
6650           bfd_size_type amt;
6651           unsigned long int nsyms;
6652           size_t bucketcount;
6653           size_t hash_entry_size;
6654
6655           /* Compute the hash values for all exported symbols.  At the same
6656              time store the values in an array so that we could use them for
6657              optimizations.  */
6658           amt = dynsymcount * sizeof (unsigned long int);
6659           hashcodes = (unsigned long int *) bfd_malloc (amt);
6660           if (hashcodes == NULL)
6661             return FALSE;
6662           hashinf.hashcodes = hashcodes;
6663           hashinf.error = FALSE;
6664
6665           /* Put all hash values in HASHCODES.  */
6666           elf_link_hash_traverse (elf_hash_table (info),
6667                                   elf_collect_hash_codes, &hashinf);
6668           if (hashinf.error)
6669             {
6670               free (hashcodes);
6671               return FALSE;
6672             }
6673
6674           nsyms = hashinf.hashcodes - hashcodes;
6675           bucketcount
6676             = compute_bucket_count (info, hashcodes, nsyms, 0);
6677           free (hashcodes);
6678
6679           if (bucketcount == 0)
6680             return FALSE;
6681
6682           elf_hash_table (info)->bucketcount = bucketcount;
6683
6684           s = bfd_get_linker_section (dynobj, ".hash");
6685           BFD_ASSERT (s != NULL);
6686           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6687           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6688           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6689           if (s->contents == NULL)
6690             return FALSE;
6691
6692           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6693           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6694                    s->contents + hash_entry_size);
6695         }
6696
6697       if (info->emit_gnu_hash)
6698         {
6699           size_t i, cnt;
6700           unsigned char *contents;
6701           struct collect_gnu_hash_codes cinfo;
6702           bfd_size_type amt;
6703           size_t bucketcount;
6704
6705           memset (&cinfo, 0, sizeof (cinfo));
6706
6707           /* Compute the hash values for all exported symbols.  At the same
6708              time store the values in an array so that we could use them for
6709              optimizations.  */
6710           amt = dynsymcount * 2 * sizeof (unsigned long int);
6711           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6712           if (cinfo.hashcodes == NULL)
6713             return FALSE;
6714
6715           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6716           cinfo.min_dynindx = -1;
6717           cinfo.output_bfd = output_bfd;
6718           cinfo.bed = bed;
6719
6720           /* Put all hash values in HASHCODES.  */
6721           elf_link_hash_traverse (elf_hash_table (info),
6722                                   elf_collect_gnu_hash_codes, &cinfo);
6723           if (cinfo.error)
6724             {
6725               free (cinfo.hashcodes);
6726               return FALSE;
6727             }
6728
6729           bucketcount
6730             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6731
6732           if (bucketcount == 0)
6733             {
6734               free (cinfo.hashcodes);
6735               return FALSE;
6736             }
6737
6738           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6739           BFD_ASSERT (s != NULL);
6740
6741           if (cinfo.nsyms == 0)
6742             {
6743               /* Empty .gnu.hash section is special.  */
6744               BFD_ASSERT (cinfo.min_dynindx == -1);
6745               free (cinfo.hashcodes);
6746               s->size = 5 * 4 + bed->s->arch_size / 8;
6747               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6748               if (contents == NULL)
6749                 return FALSE;
6750               s->contents = contents;
6751               /* 1 empty bucket.  */
6752               bfd_put_32 (output_bfd, 1, contents);
6753               /* SYMIDX above the special symbol 0.  */
6754               bfd_put_32 (output_bfd, 1, contents + 4);
6755               /* Just one word for bitmask.  */
6756               bfd_put_32 (output_bfd, 1, contents + 8);
6757               /* Only hash fn bloom filter.  */
6758               bfd_put_32 (output_bfd, 0, contents + 12);
6759               /* No hashes are valid - empty bitmask.  */
6760               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6761               /* No hashes in the only bucket.  */
6762               bfd_put_32 (output_bfd, 0,
6763                           contents + 16 + bed->s->arch_size / 8);
6764             }
6765           else
6766             {
6767               unsigned long int maskwords, maskbitslog2, x;
6768               BFD_ASSERT (cinfo.min_dynindx != -1);
6769
6770               x = cinfo.nsyms;
6771               maskbitslog2 = 1;
6772               while ((x >>= 1) != 0)
6773                 ++maskbitslog2;
6774               if (maskbitslog2 < 3)
6775                 maskbitslog2 = 5;
6776               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6777                 maskbitslog2 = maskbitslog2 + 3;
6778               else
6779                 maskbitslog2 = maskbitslog2 + 2;
6780               if (bed->s->arch_size == 64)
6781                 {
6782                   if (maskbitslog2 == 5)
6783                     maskbitslog2 = 6;
6784                   cinfo.shift1 = 6;
6785                 }
6786               else
6787                 cinfo.shift1 = 5;
6788               cinfo.mask = (1 << cinfo.shift1) - 1;
6789               cinfo.shift2 = maskbitslog2;
6790               cinfo.maskbits = 1 << maskbitslog2;
6791               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6792               amt = bucketcount * sizeof (unsigned long int) * 2;
6793               amt += maskwords * sizeof (bfd_vma);
6794               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6795               if (cinfo.bitmask == NULL)
6796                 {
6797                   free (cinfo.hashcodes);
6798                   return FALSE;
6799                 }
6800
6801               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6802               cinfo.indx = cinfo.counts + bucketcount;
6803               cinfo.symindx = dynsymcount - cinfo.nsyms;
6804               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6805
6806               /* Determine how often each hash bucket is used.  */
6807               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6808               for (i = 0; i < cinfo.nsyms; ++i)
6809                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6810
6811               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6812                 if (cinfo.counts[i] != 0)
6813                   {
6814                     cinfo.indx[i] = cnt;
6815                     cnt += cinfo.counts[i];
6816                   }
6817               BFD_ASSERT (cnt == dynsymcount);
6818               cinfo.bucketcount = bucketcount;
6819               cinfo.local_indx = cinfo.min_dynindx;
6820
6821               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6822               s->size += cinfo.maskbits / 8;
6823               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6824               if (contents == NULL)
6825                 {
6826                   free (cinfo.bitmask);
6827                   free (cinfo.hashcodes);
6828                   return FALSE;
6829                 }
6830
6831               s->contents = contents;
6832               bfd_put_32 (output_bfd, bucketcount, contents);
6833               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6834               bfd_put_32 (output_bfd, maskwords, contents + 8);
6835               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6836               contents += 16 + cinfo.maskbits / 8;
6837
6838               for (i = 0; i < bucketcount; ++i)
6839                 {
6840                   if (cinfo.counts[i] == 0)
6841                     bfd_put_32 (output_bfd, 0, contents);
6842                   else
6843                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6844                   contents += 4;
6845                 }
6846
6847               cinfo.contents = contents;
6848
6849               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6850               elf_link_hash_traverse (elf_hash_table (info),
6851                                       elf_renumber_gnu_hash_syms, &cinfo);
6852
6853               contents = s->contents + 16;
6854               for (i = 0; i < maskwords; ++i)
6855                 {
6856                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6857                            contents);
6858                   contents += bed->s->arch_size / 8;
6859                 }
6860
6861               free (cinfo.bitmask);
6862               free (cinfo.hashcodes);
6863             }
6864         }
6865
6866       s = bfd_get_linker_section (dynobj, ".dynstr");
6867       BFD_ASSERT (s != NULL);
6868
6869       elf_finalize_dynstr (output_bfd, info);
6870
6871       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6872
6873       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6874         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6875           return FALSE;
6876     }
6877
6878   return TRUE;
6879 }
6880 \f
6881 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6882
6883 static void
6884 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6885                             asection *sec)
6886 {
6887   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6888   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6889 }
6890
6891 /* Finish SHF_MERGE section merging.  */
6892
6893 bfd_boolean
6894 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
6895 {
6896   bfd *ibfd;
6897   asection *sec;
6898
6899   if (!is_elf_hash_table (info->hash))
6900     return FALSE;
6901
6902   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6903     if ((ibfd->flags & DYNAMIC) == 0
6904         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6905         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
6906             == get_elf_backend_data (obfd)->s->elfclass))
6907       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6908         if ((sec->flags & SEC_MERGE) != 0
6909             && !bfd_is_abs_section (sec->output_section))
6910           {
6911             struct bfd_elf_section_data *secdata;
6912
6913             secdata = elf_section_data (sec);
6914             if (! _bfd_add_merge_section (obfd,
6915                                           &elf_hash_table (info)->merge_info,
6916                                           sec, &secdata->sec_info))
6917               return FALSE;
6918             else if (secdata->sec_info)
6919               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6920           }
6921
6922   if (elf_hash_table (info)->merge_info != NULL)
6923     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
6924                          merge_sections_remove_hook);
6925   return TRUE;
6926 }
6927
6928 /* Create an entry in an ELF linker hash table.  */
6929
6930 struct bfd_hash_entry *
6931 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6932                             struct bfd_hash_table *table,
6933                             const char *string)
6934 {
6935   /* Allocate the structure if it has not already been allocated by a
6936      subclass.  */
6937   if (entry == NULL)
6938     {
6939       entry = (struct bfd_hash_entry *)
6940         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6941       if (entry == NULL)
6942         return entry;
6943     }
6944
6945   /* Call the allocation method of the superclass.  */
6946   entry = _bfd_link_hash_newfunc (entry, table, string);
6947   if (entry != NULL)
6948     {
6949       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6950       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6951
6952       /* Set local fields.  */
6953       ret->indx = -1;
6954       ret->dynindx = -1;
6955       ret->got = htab->init_got_refcount;
6956       ret->plt = htab->init_plt_refcount;
6957       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6958                               - offsetof (struct elf_link_hash_entry, size)));
6959       /* Assume that we have been called by a non-ELF symbol reader.
6960          This flag is then reset by the code which reads an ELF input
6961          file.  This ensures that a symbol created by a non-ELF symbol
6962          reader will have the flag set correctly.  */
6963       ret->non_elf = 1;
6964     }
6965
6966   return entry;
6967 }
6968
6969 /* Copy data from an indirect symbol to its direct symbol, hiding the
6970    old indirect symbol.  Also used for copying flags to a weakdef.  */
6971
6972 void
6973 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6974                                   struct elf_link_hash_entry *dir,
6975                                   struct elf_link_hash_entry *ind)
6976 {
6977   struct elf_link_hash_table *htab;
6978
6979   /* Copy down any references that we may have already seen to the
6980      symbol which just became indirect if DIR isn't a hidden versioned
6981      symbol.  */
6982
6983   if (dir->versioned != versioned_hidden)
6984     {
6985       dir->ref_dynamic |= ind->ref_dynamic;
6986       dir->ref_regular |= ind->ref_regular;
6987       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6988       dir->non_got_ref |= ind->non_got_ref;
6989       dir->needs_plt |= ind->needs_plt;
6990       dir->pointer_equality_needed |= ind->pointer_equality_needed;
6991     }
6992
6993   if (ind->root.type != bfd_link_hash_indirect)
6994     return;
6995
6996   /* Copy over the global and procedure linkage table refcount entries.
6997      These may have been already set up by a check_relocs routine.  */
6998   htab = elf_hash_table (info);
6999   if (ind->got.refcount > htab->init_got_refcount.refcount)
7000     {
7001       if (dir->got.refcount < 0)
7002         dir->got.refcount = 0;
7003       dir->got.refcount += ind->got.refcount;
7004       ind->got.refcount = htab->init_got_refcount.refcount;
7005     }
7006
7007   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7008     {
7009       if (dir->plt.refcount < 0)
7010         dir->plt.refcount = 0;
7011       dir->plt.refcount += ind->plt.refcount;
7012       ind->plt.refcount = htab->init_plt_refcount.refcount;
7013     }
7014
7015   if (ind->dynindx != -1)
7016     {
7017       if (dir->dynindx != -1)
7018         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7019       dir->dynindx = ind->dynindx;
7020       dir->dynstr_index = ind->dynstr_index;
7021       ind->dynindx = -1;
7022       ind->dynstr_index = 0;
7023     }
7024 }
7025
7026 void
7027 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7028                                 struct elf_link_hash_entry *h,
7029                                 bfd_boolean force_local)
7030 {
7031   /* STT_GNU_IFUNC symbol must go through PLT.  */
7032   if (h->type != STT_GNU_IFUNC)
7033     {
7034       h->plt = elf_hash_table (info)->init_plt_offset;
7035       h->needs_plt = 0;
7036     }
7037   if (force_local)
7038     {
7039       h->forced_local = 1;
7040       if (h->dynindx != -1)
7041         {
7042           h->dynindx = -1;
7043           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7044                                   h->dynstr_index);
7045         }
7046     }
7047 }
7048
7049 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7050    caller.  */
7051
7052 bfd_boolean
7053 _bfd_elf_link_hash_table_init
7054   (struct elf_link_hash_table *table,
7055    bfd *abfd,
7056    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7057                                       struct bfd_hash_table *,
7058                                       const char *),
7059    unsigned int entsize,
7060    enum elf_target_id target_id)
7061 {
7062   bfd_boolean ret;
7063   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7064
7065   table->init_got_refcount.refcount = can_refcount - 1;
7066   table->init_plt_refcount.refcount = can_refcount - 1;
7067   table->init_got_offset.offset = -(bfd_vma) 1;
7068   table->init_plt_offset.offset = -(bfd_vma) 1;
7069   /* The first dynamic symbol is a dummy.  */
7070   table->dynsymcount = 1;
7071
7072   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7073
7074   table->root.type = bfd_link_elf_hash_table;
7075   table->hash_table_id = target_id;
7076
7077   return ret;
7078 }
7079
7080 /* Create an ELF linker hash table.  */
7081
7082 struct bfd_link_hash_table *
7083 _bfd_elf_link_hash_table_create (bfd *abfd)
7084 {
7085   struct elf_link_hash_table *ret;
7086   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7087
7088   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7089   if (ret == NULL)
7090     return NULL;
7091
7092   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7093                                        sizeof (struct elf_link_hash_entry),
7094                                        GENERIC_ELF_DATA))
7095     {
7096       free (ret);
7097       return NULL;
7098     }
7099   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7100
7101   return &ret->root;
7102 }
7103
7104 /* Destroy an ELF linker hash table.  */
7105
7106 void
7107 _bfd_elf_link_hash_table_free (bfd *obfd)
7108 {
7109   struct elf_link_hash_table *htab;
7110
7111   htab = (struct elf_link_hash_table *) obfd->link.hash;
7112   if (htab->dynstr != NULL)
7113     _bfd_elf_strtab_free (htab->dynstr);
7114   _bfd_merge_sections_free (htab->merge_info);
7115   _bfd_generic_link_hash_table_free (obfd);
7116 }
7117
7118 /* This is a hook for the ELF emulation code in the generic linker to
7119    tell the backend linker what file name to use for the DT_NEEDED
7120    entry for a dynamic object.  */
7121
7122 void
7123 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7124 {
7125   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7126       && bfd_get_format (abfd) == bfd_object)
7127     elf_dt_name (abfd) = name;
7128 }
7129
7130 int
7131 bfd_elf_get_dyn_lib_class (bfd *abfd)
7132 {
7133   int lib_class;
7134   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7135       && bfd_get_format (abfd) == bfd_object)
7136     lib_class = elf_dyn_lib_class (abfd);
7137   else
7138     lib_class = 0;
7139   return lib_class;
7140 }
7141
7142 void
7143 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7144 {
7145   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7146       && bfd_get_format (abfd) == bfd_object)
7147     elf_dyn_lib_class (abfd) = lib_class;
7148 }
7149
7150 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7151    the linker ELF emulation code.  */
7152
7153 struct bfd_link_needed_list *
7154 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7155                          struct bfd_link_info *info)
7156 {
7157   if (! is_elf_hash_table (info->hash))
7158     return NULL;
7159   return elf_hash_table (info)->needed;
7160 }
7161
7162 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7163    hook for the linker ELF emulation code.  */
7164
7165 struct bfd_link_needed_list *
7166 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7167                           struct bfd_link_info *info)
7168 {
7169   if (! is_elf_hash_table (info->hash))
7170     return NULL;
7171   return elf_hash_table (info)->runpath;
7172 }
7173
7174 /* Get the name actually used for a dynamic object for a link.  This
7175    is the SONAME entry if there is one.  Otherwise, it is the string
7176    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7177
7178 const char *
7179 bfd_elf_get_dt_soname (bfd *abfd)
7180 {
7181   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7182       && bfd_get_format (abfd) == bfd_object)
7183     return elf_dt_name (abfd);
7184   return NULL;
7185 }
7186
7187 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7188    the ELF linker emulation code.  */
7189
7190 bfd_boolean
7191 bfd_elf_get_bfd_needed_list (bfd *abfd,
7192                              struct bfd_link_needed_list **pneeded)
7193 {
7194   asection *s;
7195   bfd_byte *dynbuf = NULL;
7196   unsigned int elfsec;
7197   unsigned long shlink;
7198   bfd_byte *extdyn, *extdynend;
7199   size_t extdynsize;
7200   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7201
7202   *pneeded = NULL;
7203
7204   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7205       || bfd_get_format (abfd) != bfd_object)
7206     return TRUE;
7207
7208   s = bfd_get_section_by_name (abfd, ".dynamic");
7209   if (s == NULL || s->size == 0)
7210     return TRUE;
7211
7212   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7213     goto error_return;
7214
7215   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7216   if (elfsec == SHN_BAD)
7217     goto error_return;
7218
7219   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7220
7221   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7222   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7223
7224   extdyn = dynbuf;
7225   extdynend = extdyn + s->size;
7226   for (; extdyn < extdynend; extdyn += extdynsize)
7227     {
7228       Elf_Internal_Dyn dyn;
7229
7230       (*swap_dyn_in) (abfd, extdyn, &dyn);
7231
7232       if (dyn.d_tag == DT_NULL)
7233         break;
7234
7235       if (dyn.d_tag == DT_NEEDED)
7236         {
7237           const char *string;
7238           struct bfd_link_needed_list *l;
7239           unsigned int tagv = dyn.d_un.d_val;
7240           bfd_size_type amt;
7241
7242           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7243           if (string == NULL)
7244             goto error_return;
7245
7246           amt = sizeof *l;
7247           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7248           if (l == NULL)
7249             goto error_return;
7250
7251           l->by = abfd;
7252           l->name = string;
7253           l->next = *pneeded;
7254           *pneeded = l;
7255         }
7256     }
7257
7258   free (dynbuf);
7259
7260   return TRUE;
7261
7262  error_return:
7263   if (dynbuf != NULL)
7264     free (dynbuf);
7265   return FALSE;
7266 }
7267
7268 struct elf_symbuf_symbol
7269 {
7270   unsigned long st_name;        /* Symbol name, index in string tbl */
7271   unsigned char st_info;        /* Type and binding attributes */
7272   unsigned char st_other;       /* Visibilty, and target specific */
7273 };
7274
7275 struct elf_symbuf_head
7276 {
7277   struct elf_symbuf_symbol *ssym;
7278   bfd_size_type count;
7279   unsigned int st_shndx;
7280 };
7281
7282 struct elf_symbol
7283 {
7284   union
7285     {
7286       Elf_Internal_Sym *isym;
7287       struct elf_symbuf_symbol *ssym;
7288     } u;
7289   const char *name;
7290 };
7291
7292 /* Sort references to symbols by ascending section number.  */
7293
7294 static int
7295 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7296 {
7297   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7298   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7299
7300   return s1->st_shndx - s2->st_shndx;
7301 }
7302
7303 static int
7304 elf_sym_name_compare (const void *arg1, const void *arg2)
7305 {
7306   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7307   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7308   return strcmp (s1->name, s2->name);
7309 }
7310
7311 static struct elf_symbuf_head *
7312 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7313 {
7314   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7315   struct elf_symbuf_symbol *ssym;
7316   struct elf_symbuf_head *ssymbuf, *ssymhead;
7317   bfd_size_type i, shndx_count, total_size;
7318
7319   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7320   if (indbuf == NULL)
7321     return NULL;
7322
7323   for (ind = indbuf, i = 0; i < symcount; i++)
7324     if (isymbuf[i].st_shndx != SHN_UNDEF)
7325       *ind++ = &isymbuf[i];
7326   indbufend = ind;
7327
7328   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7329          elf_sort_elf_symbol);
7330
7331   shndx_count = 0;
7332   if (indbufend > indbuf)
7333     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7334       if (ind[0]->st_shndx != ind[1]->st_shndx)
7335         shndx_count++;
7336
7337   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7338                 + (indbufend - indbuf) * sizeof (*ssym));
7339   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7340   if (ssymbuf == NULL)
7341     {
7342       free (indbuf);
7343       return NULL;
7344     }
7345
7346   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7347   ssymbuf->ssym = NULL;
7348   ssymbuf->count = shndx_count;
7349   ssymbuf->st_shndx = 0;
7350   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7351     {
7352       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7353         {
7354           ssymhead++;
7355           ssymhead->ssym = ssym;
7356           ssymhead->count = 0;
7357           ssymhead->st_shndx = (*ind)->st_shndx;
7358         }
7359       ssym->st_name = (*ind)->st_name;
7360       ssym->st_info = (*ind)->st_info;
7361       ssym->st_other = (*ind)->st_other;
7362       ssymhead->count++;
7363     }
7364   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7365               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7366                   == total_size));
7367
7368   free (indbuf);
7369   return ssymbuf;
7370 }
7371
7372 /* Check if 2 sections define the same set of local and global
7373    symbols.  */
7374
7375 static bfd_boolean
7376 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7377                                    struct bfd_link_info *info)
7378 {
7379   bfd *bfd1, *bfd2;
7380   const struct elf_backend_data *bed1, *bed2;
7381   Elf_Internal_Shdr *hdr1, *hdr2;
7382   bfd_size_type symcount1, symcount2;
7383   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7384   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7385   Elf_Internal_Sym *isym, *isymend;
7386   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7387   bfd_size_type count1, count2, i;
7388   unsigned int shndx1, shndx2;
7389   bfd_boolean result;
7390
7391   bfd1 = sec1->owner;
7392   bfd2 = sec2->owner;
7393
7394   /* Both sections have to be in ELF.  */
7395   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7396       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7397     return FALSE;
7398
7399   if (elf_section_type (sec1) != elf_section_type (sec2))
7400     return FALSE;
7401
7402   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7403   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7404   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7405     return FALSE;
7406
7407   bed1 = get_elf_backend_data (bfd1);
7408   bed2 = get_elf_backend_data (bfd2);
7409   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7410   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7411   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7412   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7413
7414   if (symcount1 == 0 || symcount2 == 0)
7415     return FALSE;
7416
7417   result = FALSE;
7418   isymbuf1 = NULL;
7419   isymbuf2 = NULL;
7420   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7421   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7422
7423   if (ssymbuf1 == NULL)
7424     {
7425       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7426                                        NULL, NULL, NULL);
7427       if (isymbuf1 == NULL)
7428         goto done;
7429
7430       if (!info->reduce_memory_overheads)
7431         elf_tdata (bfd1)->symbuf = ssymbuf1
7432           = elf_create_symbuf (symcount1, isymbuf1);
7433     }
7434
7435   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7436     {
7437       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7438                                        NULL, NULL, NULL);
7439       if (isymbuf2 == NULL)
7440         goto done;
7441
7442       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7443         elf_tdata (bfd2)->symbuf = ssymbuf2
7444           = elf_create_symbuf (symcount2, isymbuf2);
7445     }
7446
7447   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7448     {
7449       /* Optimized faster version.  */
7450       bfd_size_type lo, hi, mid;
7451       struct elf_symbol *symp;
7452       struct elf_symbuf_symbol *ssym, *ssymend;
7453
7454       lo = 0;
7455       hi = ssymbuf1->count;
7456       ssymbuf1++;
7457       count1 = 0;
7458       while (lo < hi)
7459         {
7460           mid = (lo + hi) / 2;
7461           if (shndx1 < ssymbuf1[mid].st_shndx)
7462             hi = mid;
7463           else if (shndx1 > ssymbuf1[mid].st_shndx)
7464             lo = mid + 1;
7465           else
7466             {
7467               count1 = ssymbuf1[mid].count;
7468               ssymbuf1 += mid;
7469               break;
7470             }
7471         }
7472
7473       lo = 0;
7474       hi = ssymbuf2->count;
7475       ssymbuf2++;
7476       count2 = 0;
7477       while (lo < hi)
7478         {
7479           mid = (lo + hi) / 2;
7480           if (shndx2 < ssymbuf2[mid].st_shndx)
7481             hi = mid;
7482           else if (shndx2 > ssymbuf2[mid].st_shndx)
7483             lo = mid + 1;
7484           else
7485             {
7486               count2 = ssymbuf2[mid].count;
7487               ssymbuf2 += mid;
7488               break;
7489             }
7490         }
7491
7492       if (count1 == 0 || count2 == 0 || count1 != count2)
7493         goto done;
7494
7495       symtable1
7496         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7497       symtable2
7498         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7499       if (symtable1 == NULL || symtable2 == NULL)
7500         goto done;
7501
7502       symp = symtable1;
7503       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7504            ssym < ssymend; ssym++, symp++)
7505         {
7506           symp->u.ssym = ssym;
7507           symp->name = bfd_elf_string_from_elf_section (bfd1,
7508                                                         hdr1->sh_link,
7509                                                         ssym->st_name);
7510         }
7511
7512       symp = symtable2;
7513       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7514            ssym < ssymend; ssym++, symp++)
7515         {
7516           symp->u.ssym = ssym;
7517           symp->name = bfd_elf_string_from_elf_section (bfd2,
7518                                                         hdr2->sh_link,
7519                                                         ssym->st_name);
7520         }
7521
7522       /* Sort symbol by name.  */
7523       qsort (symtable1, count1, sizeof (struct elf_symbol),
7524              elf_sym_name_compare);
7525       qsort (symtable2, count1, sizeof (struct elf_symbol),
7526              elf_sym_name_compare);
7527
7528       for (i = 0; i < count1; i++)
7529         /* Two symbols must have the same binding, type and name.  */
7530         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7531             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7532             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7533           goto done;
7534
7535       result = TRUE;
7536       goto done;
7537     }
7538
7539   symtable1 = (struct elf_symbol *)
7540       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7541   symtable2 = (struct elf_symbol *)
7542       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7543   if (symtable1 == NULL || symtable2 == NULL)
7544     goto done;
7545
7546   /* Count definitions in the section.  */
7547   count1 = 0;
7548   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7549     if (isym->st_shndx == shndx1)
7550       symtable1[count1++].u.isym = isym;
7551
7552   count2 = 0;
7553   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7554     if (isym->st_shndx == shndx2)
7555       symtable2[count2++].u.isym = isym;
7556
7557   if (count1 == 0 || count2 == 0 || count1 != count2)
7558     goto done;
7559
7560   for (i = 0; i < count1; i++)
7561     symtable1[i].name
7562       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7563                                          symtable1[i].u.isym->st_name);
7564
7565   for (i = 0; i < count2; i++)
7566     symtable2[i].name
7567       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7568                                          symtable2[i].u.isym->st_name);
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.isym->st_info != symtable2 [i].u.isym->st_info
7579         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7580         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7581       goto done;
7582
7583   result = TRUE;
7584
7585 done:
7586   if (symtable1)
7587     free (symtable1);
7588   if (symtable2)
7589     free (symtable2);
7590   if (isymbuf1)
7591     free (isymbuf1);
7592   if (isymbuf2)
7593     free (isymbuf2);
7594
7595   return result;
7596 }
7597
7598 /* Return TRUE if 2 section types are compatible.  */
7599
7600 bfd_boolean
7601 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7602                                  bfd *bbfd, const asection *bsec)
7603 {
7604   if (asec == NULL
7605       || bsec == NULL
7606       || abfd->xvec->flavour != bfd_target_elf_flavour
7607       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7608     return TRUE;
7609
7610   return elf_section_type (asec) == elf_section_type (bsec);
7611 }
7612 \f
7613 /* Final phase of ELF linker.  */
7614
7615 /* A structure we use to avoid passing large numbers of arguments.  */
7616
7617 struct elf_final_link_info
7618 {
7619   /* General link information.  */
7620   struct bfd_link_info *info;
7621   /* Output BFD.  */
7622   bfd *output_bfd;
7623   /* Symbol string table.  */
7624   struct elf_strtab_hash *symstrtab;
7625   /* .hash section.  */
7626   asection *hash_sec;
7627   /* symbol version section (.gnu.version).  */
7628   asection *symver_sec;
7629   /* Buffer large enough to hold contents of any section.  */
7630   bfd_byte *contents;
7631   /* Buffer large enough to hold external relocs of any section.  */
7632   void *external_relocs;
7633   /* Buffer large enough to hold internal relocs of any section.  */
7634   Elf_Internal_Rela *internal_relocs;
7635   /* Buffer large enough to hold external local symbols of any input
7636      BFD.  */
7637   bfd_byte *external_syms;
7638   /* And a buffer for symbol section indices.  */
7639   Elf_External_Sym_Shndx *locsym_shndx;
7640   /* Buffer large enough to hold internal local symbols of any input
7641      BFD.  */
7642   Elf_Internal_Sym *internal_syms;
7643   /* Array large enough to hold a symbol index for each local symbol
7644      of any input BFD.  */
7645   long *indices;
7646   /* Array large enough to hold a section pointer for each local
7647      symbol of any input BFD.  */
7648   asection **sections;
7649   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7650   Elf_External_Sym_Shndx *symshndxbuf;
7651   /* Number of STT_FILE syms seen.  */
7652   size_t filesym_count;
7653 };
7654
7655 /* This struct is used to pass information to elf_link_output_extsym.  */
7656
7657 struct elf_outext_info
7658 {
7659   bfd_boolean failed;
7660   bfd_boolean localsyms;
7661   bfd_boolean file_sym_done;
7662   struct elf_final_link_info *flinfo;
7663 };
7664
7665
7666 /* Support for evaluating a complex relocation.
7667
7668    Complex relocations are generalized, self-describing relocations.  The
7669    implementation of them consists of two parts: complex symbols, and the
7670    relocations themselves.
7671
7672    The relocations are use a reserved elf-wide relocation type code (R_RELC
7673    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7674    information (start bit, end bit, word width, etc) into the addend.  This
7675    information is extracted from CGEN-generated operand tables within gas.
7676
7677    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7678    internal) representing prefix-notation expressions, including but not
7679    limited to those sorts of expressions normally encoded as addends in the
7680    addend field.  The symbol mangling format is:
7681
7682    <node> := <literal>
7683           |  <unary-operator> ':' <node>
7684           |  <binary-operator> ':' <node> ':' <node>
7685           ;
7686
7687    <literal> := 's' <digits=N> ':' <N character symbol name>
7688              |  'S' <digits=N> ':' <N character section name>
7689              |  '#' <hexdigits>
7690              ;
7691
7692    <binary-operator> := as in C
7693    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7694
7695 static void
7696 set_symbol_value (bfd *bfd_with_globals,
7697                   Elf_Internal_Sym *isymbuf,
7698                   size_t locsymcount,
7699                   size_t symidx,
7700                   bfd_vma val)
7701 {
7702   struct elf_link_hash_entry **sym_hashes;
7703   struct elf_link_hash_entry *h;
7704   size_t extsymoff = locsymcount;
7705
7706   if (symidx < locsymcount)
7707     {
7708       Elf_Internal_Sym *sym;
7709
7710       sym = isymbuf + symidx;
7711       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7712         {
7713           /* It is a local symbol: move it to the
7714              "absolute" section and give it a value.  */
7715           sym->st_shndx = SHN_ABS;
7716           sym->st_value = val;
7717           return;
7718         }
7719       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7720       extsymoff = 0;
7721     }
7722
7723   /* It is a global symbol: set its link type
7724      to "defined" and give it a value.  */
7725
7726   sym_hashes = elf_sym_hashes (bfd_with_globals);
7727   h = sym_hashes [symidx - extsymoff];
7728   while (h->root.type == bfd_link_hash_indirect
7729          || h->root.type == bfd_link_hash_warning)
7730     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7731   h->root.type = bfd_link_hash_defined;
7732   h->root.u.def.value = val;
7733   h->root.u.def.section = bfd_abs_section_ptr;
7734 }
7735
7736 static bfd_boolean
7737 resolve_symbol (const char *name,
7738                 bfd *input_bfd,
7739                 struct elf_final_link_info *flinfo,
7740                 bfd_vma *result,
7741                 Elf_Internal_Sym *isymbuf,
7742                 size_t locsymcount)
7743 {
7744   Elf_Internal_Sym *sym;
7745   struct bfd_link_hash_entry *global_entry;
7746   const char *candidate = NULL;
7747   Elf_Internal_Shdr *symtab_hdr;
7748   size_t i;
7749
7750   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7751
7752   for (i = 0; i < locsymcount; ++ i)
7753     {
7754       sym = isymbuf + i;
7755
7756       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7757         continue;
7758
7759       candidate = bfd_elf_string_from_elf_section (input_bfd,
7760                                                    symtab_hdr->sh_link,
7761                                                    sym->st_name);
7762 #ifdef DEBUG
7763       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7764               name, candidate, (unsigned long) sym->st_value);
7765 #endif
7766       if (candidate && strcmp (candidate, name) == 0)
7767         {
7768           asection *sec = flinfo->sections [i];
7769
7770           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7771           *result += sec->output_offset + sec->output_section->vma;
7772 #ifdef DEBUG
7773           printf ("Found symbol with value %8.8lx\n",
7774                   (unsigned long) *result);
7775 #endif
7776           return TRUE;
7777         }
7778     }
7779
7780   /* Hmm, haven't found it yet. perhaps it is a global.  */
7781   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7782                                        FALSE, FALSE, TRUE);
7783   if (!global_entry)
7784     return FALSE;
7785
7786   if (global_entry->type == bfd_link_hash_defined
7787       || global_entry->type == bfd_link_hash_defweak)
7788     {
7789       *result = (global_entry->u.def.value
7790                  + global_entry->u.def.section->output_section->vma
7791                  + global_entry->u.def.section->output_offset);
7792 #ifdef DEBUG
7793       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7794               global_entry->root.string, (unsigned long) *result);
7795 #endif
7796       return TRUE;
7797     }
7798
7799   return FALSE;
7800 }
7801
7802 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
7803    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
7804    names like "foo.end" which is the end address of section "foo".  */
7805    
7806 static bfd_boolean
7807 resolve_section (const char *name,
7808                  asection *sections,
7809                  bfd_vma *result,
7810                  bfd * abfd)
7811 {
7812   asection *curr;
7813   unsigned int len;
7814
7815   for (curr = sections; curr; curr = curr->next)
7816     if (strcmp (curr->name, name) == 0)
7817       {
7818         *result = curr->vma;
7819         return TRUE;
7820       }
7821
7822   /* Hmm. still haven't found it. try pseudo-section names.  */
7823   /* FIXME: This could be coded more efficiently...  */
7824   for (curr = sections; curr; curr = curr->next)
7825     {
7826       len = strlen (curr->name);
7827       if (len > strlen (name))
7828         continue;
7829
7830       if (strncmp (curr->name, name, len) == 0)
7831         {
7832           if (strncmp (".end", name + len, 4) == 0)
7833             {
7834               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
7835               return TRUE;
7836             }
7837
7838           /* Insert more pseudo-section names here, if you like.  */
7839         }
7840     }
7841
7842   return FALSE;
7843 }
7844
7845 static void
7846 undefined_reference (const char *reftype, const char *name)
7847 {
7848   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7849                       reftype, name);
7850 }
7851
7852 static bfd_boolean
7853 eval_symbol (bfd_vma *result,
7854              const char **symp,
7855              bfd *input_bfd,
7856              struct elf_final_link_info *flinfo,
7857              bfd_vma dot,
7858              Elf_Internal_Sym *isymbuf,
7859              size_t locsymcount,
7860              int signed_p)
7861 {
7862   size_t len;
7863   size_t symlen;
7864   bfd_vma a;
7865   bfd_vma b;
7866   char symbuf[4096];
7867   const char *sym = *symp;
7868   const char *symend;
7869   bfd_boolean symbol_is_section = FALSE;
7870
7871   len = strlen (sym);
7872   symend = sym + len;
7873
7874   if (len < 1 || len > sizeof (symbuf))
7875     {
7876       bfd_set_error (bfd_error_invalid_operation);
7877       return FALSE;
7878     }
7879
7880   switch (* sym)
7881     {
7882     case '.':
7883       *result = dot;
7884       *symp = sym + 1;
7885       return TRUE;
7886
7887     case '#':
7888       ++sym;
7889       *result = strtoul (sym, (char **) symp, 16);
7890       return TRUE;
7891
7892     case 'S':
7893       symbol_is_section = TRUE;
7894     case 's':
7895       ++sym;
7896       symlen = strtol (sym, (char **) symp, 10);
7897       sym = *symp + 1; /* Skip the trailing ':'.  */
7898
7899       if (symend < sym || symlen + 1 > sizeof (symbuf))
7900         {
7901           bfd_set_error (bfd_error_invalid_operation);
7902           return FALSE;
7903         }
7904
7905       memcpy (symbuf, sym, symlen);
7906       symbuf[symlen] = '\0';
7907       *symp = sym + symlen;
7908
7909       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7910          the symbol as a section, or vice-versa. so we're pretty liberal in our
7911          interpretation here; section means "try section first", not "must be a
7912          section", and likewise with symbol.  */
7913
7914       if (symbol_is_section)
7915         {
7916           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
7917               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7918                                   isymbuf, locsymcount))
7919             {
7920               undefined_reference ("section", symbuf);
7921               return FALSE;
7922             }
7923         }
7924       else
7925         {
7926           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7927                                isymbuf, locsymcount)
7928               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7929                                    result, input_bfd))
7930             {
7931               undefined_reference ("symbol", symbuf);
7932               return FALSE;
7933             }
7934         }
7935
7936       return TRUE;
7937
7938       /* All that remains are operators.  */
7939
7940 #define UNARY_OP(op)                                            \
7941   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7942     {                                                           \
7943       sym += strlen (#op);                                      \
7944       if (*sym == ':')                                          \
7945         ++sym;                                                  \
7946       *symp = sym;                                              \
7947       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7948                         isymbuf, locsymcount, signed_p))        \
7949         return FALSE;                                           \
7950       if (signed_p)                                             \
7951         *result = op ((bfd_signed_vma) a);                      \
7952       else                                                      \
7953         *result = op a;                                         \
7954       return TRUE;                                              \
7955     }
7956
7957 #define BINARY_OP(op)                                           \
7958   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7959     {                                                           \
7960       sym += strlen (#op);                                      \
7961       if (*sym == ':')                                          \
7962         ++sym;                                                  \
7963       *symp = sym;                                              \
7964       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7965                         isymbuf, locsymcount, signed_p))        \
7966         return FALSE;                                           \
7967       ++*symp;                                                  \
7968       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7969                         isymbuf, locsymcount, signed_p))        \
7970         return FALSE;                                           \
7971       if (signed_p)                                             \
7972         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7973       else                                                      \
7974         *result = a op b;                                       \
7975       return TRUE;                                              \
7976     }
7977
7978     default:
7979       UNARY_OP  (0-);
7980       BINARY_OP (<<);
7981       BINARY_OP (>>);
7982       BINARY_OP (==);
7983       BINARY_OP (!=);
7984       BINARY_OP (<=);
7985       BINARY_OP (>=);
7986       BINARY_OP (&&);
7987       BINARY_OP (||);
7988       UNARY_OP  (~);
7989       UNARY_OP  (!);
7990       BINARY_OP (*);
7991       BINARY_OP (/);
7992       BINARY_OP (%);
7993       BINARY_OP (^);
7994       BINARY_OP (|);
7995       BINARY_OP (&);
7996       BINARY_OP (+);
7997       BINARY_OP (-);
7998       BINARY_OP (<);
7999       BINARY_OP (>);
8000 #undef UNARY_OP
8001 #undef BINARY_OP
8002       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8003       bfd_set_error (bfd_error_invalid_operation);
8004       return FALSE;
8005     }
8006 }
8007
8008 static void
8009 put_value (bfd_vma size,
8010            unsigned long chunksz,
8011            bfd *input_bfd,
8012            bfd_vma x,
8013            bfd_byte *location)
8014 {
8015   location += (size - chunksz);
8016
8017   for (; size; size -= chunksz, location -= chunksz)
8018     {
8019       switch (chunksz)
8020         {
8021         case 1:
8022           bfd_put_8 (input_bfd, x, location);
8023           x >>= 8;
8024           break;
8025         case 2:
8026           bfd_put_16 (input_bfd, x, location);
8027           x >>= 16;
8028           break;
8029         case 4:
8030           bfd_put_32 (input_bfd, x, location);
8031           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8032           x >>= 16;
8033           x >>= 16;
8034           break;
8035 #ifdef BFD64
8036         case 8:
8037           bfd_put_64 (input_bfd, x, location);
8038           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8039           x >>= 32;
8040           x >>= 32;
8041           break;
8042 #endif
8043         default:
8044           abort ();
8045           break;
8046         }
8047     }
8048 }
8049
8050 static bfd_vma
8051 get_value (bfd_vma size,
8052            unsigned long chunksz,
8053            bfd *input_bfd,
8054            bfd_byte *location)
8055 {
8056   int shift;
8057   bfd_vma x = 0;
8058
8059   /* Sanity checks.  */
8060   BFD_ASSERT (chunksz <= sizeof (x)
8061               && size >= chunksz
8062               && chunksz != 0
8063               && (size % chunksz) == 0
8064               && input_bfd != NULL
8065               && location != NULL);
8066
8067   if (chunksz == sizeof (x))
8068     {
8069       BFD_ASSERT (size == chunksz);
8070
8071       /* Make sure that we do not perform an undefined shift operation.
8072          We know that size == chunksz so there will only be one iteration
8073          of the loop below.  */
8074       shift = 0;
8075     }
8076   else
8077     shift = 8 * chunksz;
8078
8079   for (; size; size -= chunksz, location += chunksz)
8080     {
8081       switch (chunksz)
8082         {
8083         case 1:
8084           x = (x << shift) | bfd_get_8 (input_bfd, location);
8085           break;
8086         case 2:
8087           x = (x << shift) | bfd_get_16 (input_bfd, location);
8088           break;
8089         case 4:
8090           x = (x << shift) | bfd_get_32 (input_bfd, location);
8091           break;
8092 #ifdef BFD64
8093         case 8:
8094           x = (x << shift) | bfd_get_64 (input_bfd, location);
8095           break;
8096 #endif
8097         default:
8098           abort ();
8099         }
8100     }
8101   return x;
8102 }
8103
8104 static void
8105 decode_complex_addend (unsigned long *start,   /* in bits */
8106                        unsigned long *oplen,   /* in bits */
8107                        unsigned long *len,     /* in bits */
8108                        unsigned long *wordsz,  /* in bytes */
8109                        unsigned long *chunksz, /* in bytes */
8110                        unsigned long *lsb0_p,
8111                        unsigned long *signed_p,
8112                        unsigned long *trunc_p,
8113                        unsigned long encoded)
8114 {
8115   * start     =  encoded        & 0x3F;
8116   * len       = (encoded >>  6) & 0x3F;
8117   * oplen     = (encoded >> 12) & 0x3F;
8118   * wordsz    = (encoded >> 18) & 0xF;
8119   * chunksz   = (encoded >> 22) & 0xF;
8120   * lsb0_p    = (encoded >> 27) & 1;
8121   * signed_p  = (encoded >> 28) & 1;
8122   * trunc_p   = (encoded >> 29) & 1;
8123 }
8124
8125 bfd_reloc_status_type
8126 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8127                                     asection *input_section ATTRIBUTE_UNUSED,
8128                                     bfd_byte *contents,
8129                                     Elf_Internal_Rela *rel,
8130                                     bfd_vma relocation)
8131 {
8132   bfd_vma shift, x, mask;
8133   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8134   bfd_reloc_status_type r;
8135
8136   /*  Perform this reloc, since it is complex.
8137       (this is not to say that it necessarily refers to a complex
8138       symbol; merely that it is a self-describing CGEN based reloc.
8139       i.e. the addend has the complete reloc information (bit start, end,
8140       word size, etc) encoded within it.).  */
8141
8142   decode_complex_addend (&start, &oplen, &len, &wordsz,
8143                          &chunksz, &lsb0_p, &signed_p,
8144                          &trunc_p, rel->r_addend);
8145
8146   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8147
8148   if (lsb0_p)
8149     shift = (start + 1) - len;
8150   else
8151     shift = (8 * wordsz) - (start + len);
8152
8153   x = get_value (wordsz, chunksz, input_bfd,
8154                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8155
8156 #ifdef DEBUG
8157   printf ("Doing complex reloc: "
8158           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8159           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8160           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8161           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8162           oplen, (unsigned long) x, (unsigned long) mask,
8163           (unsigned long) relocation);
8164 #endif
8165
8166   r = bfd_reloc_ok;
8167   if (! trunc_p)
8168     /* Now do an overflow check.  */
8169     r = bfd_check_overflow ((signed_p
8170                              ? complain_overflow_signed
8171                              : complain_overflow_unsigned),
8172                             len, 0, (8 * wordsz),
8173                             relocation);
8174
8175   /* Do the deed.  */
8176   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8177
8178 #ifdef DEBUG
8179   printf ("           relocation: %8.8lx\n"
8180           "         shifted mask: %8.8lx\n"
8181           " shifted/masked reloc: %8.8lx\n"
8182           "               result: %8.8lx\n",
8183           (unsigned long) relocation, (unsigned long) (mask << shift),
8184           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8185 #endif
8186   put_value (wordsz, chunksz, input_bfd, x,
8187              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8188   return r;
8189 }
8190
8191 /* Functions to read r_offset from external (target order) reloc
8192    entry.  Faster than bfd_getl32 et al, because we let the compiler
8193    know the value is aligned.  */
8194
8195 static bfd_vma
8196 ext32l_r_offset (const void *p)
8197 {
8198   union aligned32
8199   {
8200     uint32_t v;
8201     unsigned char c[4];
8202   };
8203   const union aligned32 *a
8204     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8205
8206   uint32_t aval = (  (uint32_t) a->c[0]
8207                    | (uint32_t) a->c[1] << 8
8208                    | (uint32_t) a->c[2] << 16
8209                    | (uint32_t) a->c[3] << 24);
8210   return aval;
8211 }
8212
8213 static bfd_vma
8214 ext32b_r_offset (const void *p)
8215 {
8216   union aligned32
8217   {
8218     uint32_t v;
8219     unsigned char c[4];
8220   };
8221   const union aligned32 *a
8222     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8223
8224   uint32_t aval = (  (uint32_t) a->c[0] << 24
8225                    | (uint32_t) a->c[1] << 16
8226                    | (uint32_t) a->c[2] << 8
8227                    | (uint32_t) a->c[3]);
8228   return aval;
8229 }
8230
8231 #ifdef BFD_HOST_64_BIT
8232 static bfd_vma
8233 ext64l_r_offset (const void *p)
8234 {
8235   union aligned64
8236   {
8237     uint64_t v;
8238     unsigned char c[8];
8239   };
8240   const union aligned64 *a
8241     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8242
8243   uint64_t aval = (  (uint64_t) a->c[0]
8244                    | (uint64_t) a->c[1] << 8
8245                    | (uint64_t) a->c[2] << 16
8246                    | (uint64_t) a->c[3] << 24
8247                    | (uint64_t) a->c[4] << 32
8248                    | (uint64_t) a->c[5] << 40
8249                    | (uint64_t) a->c[6] << 48
8250                    | (uint64_t) a->c[7] << 56);
8251   return aval;
8252 }
8253
8254 static bfd_vma
8255 ext64b_r_offset (const void *p)
8256 {
8257   union aligned64
8258   {
8259     uint64_t v;
8260     unsigned char c[8];
8261   };
8262   const union aligned64 *a
8263     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8264
8265   uint64_t aval = (  (uint64_t) a->c[0] << 56
8266                    | (uint64_t) a->c[1] << 48
8267                    | (uint64_t) a->c[2] << 40
8268                    | (uint64_t) a->c[3] << 32
8269                    | (uint64_t) a->c[4] << 24
8270                    | (uint64_t) a->c[5] << 16
8271                    | (uint64_t) a->c[6] << 8
8272                    | (uint64_t) a->c[7]);
8273   return aval;
8274 }
8275 #endif
8276
8277 /* When performing a relocatable link, the input relocations are
8278    preserved.  But, if they reference global symbols, the indices
8279    referenced must be updated.  Update all the relocations found in
8280    RELDATA.  */
8281
8282 static bfd_boolean
8283 elf_link_adjust_relocs (bfd *abfd,
8284                         struct bfd_elf_section_reloc_data *reldata,
8285                         bfd_boolean sort)
8286 {
8287   unsigned int i;
8288   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8289   bfd_byte *erela;
8290   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8291   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8292   bfd_vma r_type_mask;
8293   int r_sym_shift;
8294   unsigned int count = reldata->count;
8295   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8296
8297   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8298     {
8299       swap_in = bed->s->swap_reloc_in;
8300       swap_out = bed->s->swap_reloc_out;
8301     }
8302   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8303     {
8304       swap_in = bed->s->swap_reloca_in;
8305       swap_out = bed->s->swap_reloca_out;
8306     }
8307   else
8308     abort ();
8309
8310   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8311     abort ();
8312
8313   if (bed->s->arch_size == 32)
8314     {
8315       r_type_mask = 0xff;
8316       r_sym_shift = 8;
8317     }
8318   else
8319     {
8320       r_type_mask = 0xffffffff;
8321       r_sym_shift = 32;
8322     }
8323
8324   erela = reldata->hdr->contents;
8325   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8326     {
8327       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8328       unsigned int j;
8329
8330       if (*rel_hash == NULL)
8331         continue;
8332
8333       BFD_ASSERT ((*rel_hash)->indx >= 0);
8334
8335       (*swap_in) (abfd, erela, irela);
8336       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8337         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8338                            | (irela[j].r_info & r_type_mask));
8339       (*swap_out) (abfd, irela, erela);
8340     }
8341
8342   if (sort && count != 0)
8343     {
8344       bfd_vma (*ext_r_off) (const void *);
8345       bfd_vma r_off;
8346       size_t elt_size;
8347       bfd_byte *base, *end, *p, *loc;
8348       bfd_byte *buf = NULL;
8349
8350       if (bed->s->arch_size == 32)
8351         {
8352           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8353             ext_r_off = ext32l_r_offset;
8354           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8355             ext_r_off = ext32b_r_offset;
8356           else
8357             abort ();
8358         }
8359       else
8360         {
8361 #ifdef BFD_HOST_64_BIT
8362           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8363             ext_r_off = ext64l_r_offset;
8364           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8365             ext_r_off = ext64b_r_offset;
8366           else
8367 #endif
8368             abort ();
8369         }
8370
8371       /*  Must use a stable sort here.  A modified insertion sort,
8372           since the relocs are mostly sorted already.  */
8373       elt_size = reldata->hdr->sh_entsize;
8374       base = reldata->hdr->contents;
8375       end = base + count * elt_size;
8376       if (elt_size > sizeof (Elf64_External_Rela))
8377         abort ();
8378
8379       /* Ensure the first element is lowest.  This acts as a sentinel,
8380          speeding the main loop below.  */
8381       r_off = (*ext_r_off) (base);
8382       for (p = loc = base; (p += elt_size) < end; )
8383         {
8384           bfd_vma r_off2 = (*ext_r_off) (p);
8385           if (r_off > r_off2)
8386             {
8387               r_off = r_off2;
8388               loc = p;
8389             }
8390         }
8391       if (loc != base)
8392         {
8393           /* Don't just swap *base and *loc as that changes the order
8394              of the original base[0] and base[1] if they happen to
8395              have the same r_offset.  */
8396           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8397           memcpy (onebuf, loc, elt_size);
8398           memmove (base + elt_size, base, loc - base);
8399           memcpy (base, onebuf, elt_size);
8400         }
8401
8402       for (p = base + elt_size; (p += elt_size) < end; )
8403         {
8404           /* base to p is sorted, *p is next to insert.  */
8405           r_off = (*ext_r_off) (p);
8406           /* Search the sorted region for location to insert.  */
8407           loc = p - elt_size;
8408           while (r_off < (*ext_r_off) (loc))
8409             loc -= elt_size;
8410           loc += elt_size;
8411           if (loc != p)
8412             {
8413               /* Chances are there is a run of relocs to insert here,
8414                  from one of more input files.  Files are not always
8415                  linked in order due to the way elf_link_input_bfd is
8416                  called.  See pr17666.  */
8417               size_t sortlen = p - loc;
8418               bfd_vma r_off2 = (*ext_r_off) (loc);
8419               size_t runlen = elt_size;
8420               size_t buf_size = 96 * 1024;
8421               while (p + runlen < end
8422                      && (sortlen <= buf_size
8423                          || runlen + elt_size <= buf_size)
8424                      && r_off2 > (*ext_r_off) (p + runlen))
8425                 runlen += elt_size;
8426               if (buf == NULL)
8427                 {
8428                   buf = bfd_malloc (buf_size);
8429                   if (buf == NULL)
8430                     return FALSE;
8431                 }
8432               if (runlen < sortlen)
8433                 {
8434                   memcpy (buf, p, runlen);
8435                   memmove (loc + runlen, loc, sortlen);
8436                   memcpy (loc, buf, runlen);
8437                 }
8438               else
8439                 {
8440                   memcpy (buf, loc, sortlen);
8441                   memmove (loc, p, runlen);
8442                   memcpy (loc + runlen, buf, sortlen);
8443                 }
8444               p += runlen - elt_size;
8445             }
8446         }
8447       /* Hashes are no longer valid.  */
8448       free (reldata->hashes);
8449       reldata->hashes = NULL;
8450       free (buf);
8451     }
8452   return TRUE;
8453 }
8454
8455 struct elf_link_sort_rela
8456 {
8457   union {
8458     bfd_vma offset;
8459     bfd_vma sym_mask;
8460   } u;
8461   enum elf_reloc_type_class type;
8462   /* We use this as an array of size int_rels_per_ext_rel.  */
8463   Elf_Internal_Rela rela[1];
8464 };
8465
8466 static int
8467 elf_link_sort_cmp1 (const void *A, const void *B)
8468 {
8469   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8470   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8471   int relativea, relativeb;
8472
8473   relativea = a->type == reloc_class_relative;
8474   relativeb = b->type == reloc_class_relative;
8475
8476   if (relativea < relativeb)
8477     return 1;
8478   if (relativea > relativeb)
8479     return -1;
8480   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8481     return -1;
8482   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8483     return 1;
8484   if (a->rela->r_offset < b->rela->r_offset)
8485     return -1;
8486   if (a->rela->r_offset > b->rela->r_offset)
8487     return 1;
8488   return 0;
8489 }
8490
8491 static int
8492 elf_link_sort_cmp2 (const void *A, const void *B)
8493 {
8494   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8495   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8496
8497   if (a->type < b->type)
8498     return -1;
8499   if (a->type > b->type)
8500     return 1;
8501   if (a->u.offset < b->u.offset)
8502     return -1;
8503   if (a->u.offset > b->u.offset)
8504     return 1;
8505   if (a->rela->r_offset < b->rela->r_offset)
8506     return -1;
8507   if (a->rela->r_offset > b->rela->r_offset)
8508     return 1;
8509   return 0;
8510 }
8511
8512 static size_t
8513 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8514 {
8515   asection *dynamic_relocs;
8516   asection *rela_dyn;
8517   asection *rel_dyn;
8518   bfd_size_type count, size;
8519   size_t i, ret, sort_elt, ext_size;
8520   bfd_byte *sort, *s_non_relative, *p;
8521   struct elf_link_sort_rela *sq;
8522   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8523   int i2e = bed->s->int_rels_per_ext_rel;
8524   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8525   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8526   struct bfd_link_order *lo;
8527   bfd_vma r_sym_mask;
8528   bfd_boolean use_rela;
8529
8530   /* Find a dynamic reloc section.  */
8531   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8532   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8533   if (rela_dyn != NULL && rela_dyn->size > 0
8534       && rel_dyn != NULL && rel_dyn->size > 0)
8535     {
8536       bfd_boolean use_rela_initialised = FALSE;
8537
8538       /* This is just here to stop gcc from complaining.
8539          It's initialization checking code is not perfect.  */
8540       use_rela = TRUE;
8541
8542       /* Both sections are present.  Examine the sizes
8543          of the indirect sections to help us choose.  */
8544       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8545         if (lo->type == bfd_indirect_link_order)
8546           {
8547             asection *o = lo->u.indirect.section;
8548
8549             if ((o->size % bed->s->sizeof_rela) == 0)
8550               {
8551                 if ((o->size % bed->s->sizeof_rel) == 0)
8552                   /* Section size is divisible by both rel and rela sizes.
8553                      It is of no help to us.  */
8554                   ;
8555                 else
8556                   {
8557                     /* Section size is only divisible by rela.  */
8558                     if (use_rela_initialised && (use_rela == FALSE))
8559                       {
8560                         _bfd_error_handler
8561                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8562                         bfd_set_error (bfd_error_invalid_operation);
8563                         return 0;
8564                       }
8565                     else
8566                       {
8567                         use_rela = TRUE;
8568                         use_rela_initialised = TRUE;
8569                       }
8570                   }
8571               }
8572             else if ((o->size % bed->s->sizeof_rel) == 0)
8573               {
8574                 /* Section size is only divisible by rel.  */
8575                 if (use_rela_initialised && (use_rela == TRUE))
8576                   {
8577                     _bfd_error_handler
8578                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8579                     bfd_set_error (bfd_error_invalid_operation);
8580                     return 0;
8581                   }
8582                 else
8583                   {
8584                     use_rela = FALSE;
8585                     use_rela_initialised = TRUE;
8586                   }
8587               }
8588             else
8589               {
8590                 /* The section size is not divisible by either - something is wrong.  */
8591                 _bfd_error_handler
8592                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8593                 bfd_set_error (bfd_error_invalid_operation);
8594                 return 0;
8595               }
8596           }
8597
8598       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8599         if (lo->type == bfd_indirect_link_order)
8600           {
8601             asection *o = lo->u.indirect.section;
8602
8603             if ((o->size % bed->s->sizeof_rela) == 0)
8604               {
8605                 if ((o->size % bed->s->sizeof_rel) == 0)
8606                   /* Section size is divisible by both rel and rela sizes.
8607                      It is of no help to us.  */
8608                   ;
8609                 else
8610                   {
8611                     /* Section size is only divisible by rela.  */
8612                     if (use_rela_initialised && (use_rela == FALSE))
8613                       {
8614                         _bfd_error_handler
8615                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8616                         bfd_set_error (bfd_error_invalid_operation);
8617                         return 0;
8618                       }
8619                     else
8620                       {
8621                         use_rela = TRUE;
8622                         use_rela_initialised = TRUE;
8623                       }
8624                   }
8625               }
8626             else if ((o->size % bed->s->sizeof_rel) == 0)
8627               {
8628                 /* Section size is only divisible by rel.  */
8629                 if (use_rela_initialised && (use_rela == TRUE))
8630                   {
8631                     _bfd_error_handler
8632                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8633                     bfd_set_error (bfd_error_invalid_operation);
8634                     return 0;
8635                   }
8636                 else
8637                   {
8638                     use_rela = FALSE;
8639                     use_rela_initialised = TRUE;
8640                   }
8641               }
8642             else
8643               {
8644                 /* The section size is not divisible by either - something is wrong.  */
8645                 _bfd_error_handler
8646                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8647                 bfd_set_error (bfd_error_invalid_operation);
8648                 return 0;
8649               }
8650           }
8651
8652       if (! use_rela_initialised)
8653         /* Make a guess.  */
8654         use_rela = TRUE;
8655     }
8656   else if (rela_dyn != NULL && rela_dyn->size > 0)
8657     use_rela = TRUE;
8658   else if (rel_dyn != NULL && rel_dyn->size > 0)
8659     use_rela = FALSE;
8660   else
8661     return 0;
8662
8663   if (use_rela)
8664     {
8665       dynamic_relocs = rela_dyn;
8666       ext_size = bed->s->sizeof_rela;
8667       swap_in = bed->s->swap_reloca_in;
8668       swap_out = bed->s->swap_reloca_out;
8669     }
8670   else
8671     {
8672       dynamic_relocs = rel_dyn;
8673       ext_size = bed->s->sizeof_rel;
8674       swap_in = bed->s->swap_reloc_in;
8675       swap_out = bed->s->swap_reloc_out;
8676     }
8677
8678   size = 0;
8679   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8680     if (lo->type == bfd_indirect_link_order)
8681       size += lo->u.indirect.section->size;
8682
8683   if (size != dynamic_relocs->size)
8684     return 0;
8685
8686   sort_elt = (sizeof (struct elf_link_sort_rela)
8687               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8688
8689   count = dynamic_relocs->size / ext_size;
8690   if (count == 0)
8691     return 0;
8692   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8693
8694   if (sort == NULL)
8695     {
8696       (*info->callbacks->warning)
8697         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8698       return 0;
8699     }
8700
8701   if (bed->s->arch_size == 32)
8702     r_sym_mask = ~(bfd_vma) 0xff;
8703   else
8704     r_sym_mask = ~(bfd_vma) 0xffffffff;
8705
8706   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8707     if (lo->type == bfd_indirect_link_order)
8708       {
8709         bfd_byte *erel, *erelend;
8710         asection *o = lo->u.indirect.section;
8711
8712         if (o->contents == NULL && o->size != 0)
8713           {
8714             /* This is a reloc section that is being handled as a normal
8715                section.  See bfd_section_from_shdr.  We can't combine
8716                relocs in this case.  */
8717             free (sort);
8718             return 0;
8719           }
8720         erel = o->contents;
8721         erelend = o->contents + o->size;
8722         /* FIXME: octets_per_byte.  */
8723         p = sort + o->output_offset / ext_size * sort_elt;
8724
8725         while (erel < erelend)
8726           {
8727             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8728
8729             (*swap_in) (abfd, erel, s->rela);
8730             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8731             s->u.sym_mask = r_sym_mask;
8732             p += sort_elt;
8733             erel += ext_size;
8734           }
8735       }
8736
8737   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8738
8739   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8740     {
8741       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8742       if (s->type != reloc_class_relative)
8743         break;
8744     }
8745   ret = i;
8746   s_non_relative = p;
8747
8748   sq = (struct elf_link_sort_rela *) s_non_relative;
8749   for (; i < count; i++, p += sort_elt)
8750     {
8751       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8752       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8753         sq = sp;
8754       sp->u.offset = sq->rela->r_offset;
8755     }
8756
8757   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8758
8759   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8760     if (lo->type == bfd_indirect_link_order)
8761       {
8762         bfd_byte *erel, *erelend;
8763         asection *o = lo->u.indirect.section;
8764
8765         erel = o->contents;
8766         erelend = o->contents + o->size;
8767         /* FIXME: octets_per_byte.  */
8768         p = sort + o->output_offset / ext_size * sort_elt;
8769         while (erel < erelend)
8770           {
8771             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8772             (*swap_out) (abfd, s->rela, erel);
8773             p += sort_elt;
8774             erel += ext_size;
8775           }
8776       }
8777
8778   free (sort);
8779   *psec = dynamic_relocs;
8780   return ret;
8781 }
8782
8783 /* Add a symbol to the output symbol string table.  */
8784
8785 static int
8786 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8787                            const char *name,
8788                            Elf_Internal_Sym *elfsym,
8789                            asection *input_sec,
8790                            struct elf_link_hash_entry *h)
8791 {
8792   int (*output_symbol_hook)
8793     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8794      struct elf_link_hash_entry *);
8795   struct elf_link_hash_table *hash_table;
8796   const struct elf_backend_data *bed;
8797   bfd_size_type strtabsize;
8798
8799   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8800
8801   bed = get_elf_backend_data (flinfo->output_bfd);
8802   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8803   if (output_symbol_hook != NULL)
8804     {
8805       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8806       if (ret != 1)
8807         return ret;
8808     }
8809
8810   if (name == NULL
8811       || *name == '\0'
8812       || (input_sec->flags & SEC_EXCLUDE))
8813     elfsym->st_name = (unsigned long) -1;
8814   else
8815     {
8816       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8817          to get the final offset for st_name.  */
8818       elfsym->st_name
8819         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8820                                                name, FALSE);
8821       if (elfsym->st_name == (unsigned long) -1)
8822         return 0;
8823     }
8824
8825   hash_table = elf_hash_table (flinfo->info);
8826   strtabsize = hash_table->strtabsize;
8827   if (strtabsize <= hash_table->strtabcount)
8828     {
8829       strtabsize += strtabsize;
8830       hash_table->strtabsize = strtabsize;
8831       strtabsize *= sizeof (*hash_table->strtab);
8832       hash_table->strtab
8833         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8834                                                  strtabsize);
8835       if (hash_table->strtab == NULL)
8836         return 0;
8837     }
8838   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8839   hash_table->strtab[hash_table->strtabcount].dest_index
8840     = hash_table->strtabcount;
8841   hash_table->strtab[hash_table->strtabcount].destshndx_index
8842     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8843
8844   bfd_get_symcount (flinfo->output_bfd) += 1;
8845   hash_table->strtabcount += 1;
8846
8847   return 1;
8848 }
8849
8850 /* Swap symbols out to the symbol table and flush the output symbols to
8851    the file.  */
8852
8853 static bfd_boolean
8854 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8855 {
8856   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8857   bfd_size_type amt, i;
8858   const struct elf_backend_data *bed;
8859   bfd_byte *symbuf;
8860   Elf_Internal_Shdr *hdr;
8861   file_ptr pos;
8862   bfd_boolean ret;
8863
8864   if (!hash_table->strtabcount)
8865     return TRUE;
8866
8867   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8868
8869   bed = get_elf_backend_data (flinfo->output_bfd);
8870
8871   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8872   symbuf = (bfd_byte *) bfd_malloc (amt);
8873   if (symbuf == NULL)
8874     return FALSE;
8875
8876   if (flinfo->symshndxbuf)
8877     {
8878       amt = (sizeof (Elf_External_Sym_Shndx)
8879              * (bfd_get_symcount (flinfo->output_bfd)));
8880       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8881       if (flinfo->symshndxbuf == NULL)
8882         {
8883           free (symbuf);
8884           return FALSE;
8885         }
8886     }
8887
8888   for (i = 0; i < hash_table->strtabcount; i++)
8889     {
8890       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8891       if (elfsym->sym.st_name == (unsigned long) -1)
8892         elfsym->sym.st_name = 0;
8893       else
8894         elfsym->sym.st_name
8895           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8896                                                     elfsym->sym.st_name);
8897       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8898                                ((bfd_byte *) symbuf
8899                                 + (elfsym->dest_index
8900                                    * bed->s->sizeof_sym)),
8901                                (flinfo->symshndxbuf
8902                                 + elfsym->destshndx_index));
8903     }
8904
8905   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8906   pos = hdr->sh_offset + hdr->sh_size;
8907   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8908   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8909       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8910     {
8911       hdr->sh_size += amt;
8912       ret = TRUE;
8913     }
8914   else
8915     ret = FALSE;
8916
8917   free (symbuf);
8918
8919   free (hash_table->strtab);
8920   hash_table->strtab = NULL;
8921
8922   return ret;
8923 }
8924
8925 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8926
8927 static bfd_boolean
8928 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8929 {
8930   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8931       && sym->st_shndx < SHN_LORESERVE)
8932     {
8933       /* The gABI doesn't support dynamic symbols in output sections
8934          beyond 64k.  */
8935       (*_bfd_error_handler)
8936         (_("%B: Too many sections: %d (>= %d)"),
8937          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8938       bfd_set_error (bfd_error_nonrepresentable_section);
8939       return FALSE;
8940     }
8941   return TRUE;
8942 }
8943
8944 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8945    allowing an unsatisfied unversioned symbol in the DSO to match a
8946    versioned symbol that would normally require an explicit version.
8947    We also handle the case that a DSO references a hidden symbol
8948    which may be satisfied by a versioned symbol in another DSO.  */
8949
8950 static bfd_boolean
8951 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8952                                  const struct elf_backend_data *bed,
8953                                  struct elf_link_hash_entry *h)
8954 {
8955   bfd *abfd;
8956   struct elf_link_loaded_list *loaded;
8957
8958   if (!is_elf_hash_table (info->hash))
8959     return FALSE;
8960
8961   /* Check indirect symbol.  */
8962   while (h->root.type == bfd_link_hash_indirect)
8963     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8964
8965   switch (h->root.type)
8966     {
8967     default:
8968       abfd = NULL;
8969       break;
8970
8971     case bfd_link_hash_undefined:
8972     case bfd_link_hash_undefweak:
8973       abfd = h->root.u.undef.abfd;
8974       if ((abfd->flags & DYNAMIC) == 0
8975           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8976         return FALSE;
8977       break;
8978
8979     case bfd_link_hash_defined:
8980     case bfd_link_hash_defweak:
8981       abfd = h->root.u.def.section->owner;
8982       break;
8983
8984     case bfd_link_hash_common:
8985       abfd = h->root.u.c.p->section->owner;
8986       break;
8987     }
8988   BFD_ASSERT (abfd != NULL);
8989
8990   for (loaded = elf_hash_table (info)->loaded;
8991        loaded != NULL;
8992        loaded = loaded->next)
8993     {
8994       bfd *input;
8995       Elf_Internal_Shdr *hdr;
8996       bfd_size_type symcount;
8997       bfd_size_type extsymcount;
8998       bfd_size_type extsymoff;
8999       Elf_Internal_Shdr *versymhdr;
9000       Elf_Internal_Sym *isym;
9001       Elf_Internal_Sym *isymend;
9002       Elf_Internal_Sym *isymbuf;
9003       Elf_External_Versym *ever;
9004       Elf_External_Versym *extversym;
9005
9006       input = loaded->abfd;
9007
9008       /* We check each DSO for a possible hidden versioned definition.  */
9009       if (input == abfd
9010           || (input->flags & DYNAMIC) == 0
9011           || elf_dynversym (input) == 0)
9012         continue;
9013
9014       hdr = &elf_tdata (input)->dynsymtab_hdr;
9015
9016       symcount = hdr->sh_size / bed->s->sizeof_sym;
9017       if (elf_bad_symtab (input))
9018         {
9019           extsymcount = symcount;
9020           extsymoff = 0;
9021         }
9022       else
9023         {
9024           extsymcount = symcount - hdr->sh_info;
9025           extsymoff = hdr->sh_info;
9026         }
9027
9028       if (extsymcount == 0)
9029         continue;
9030
9031       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9032                                       NULL, NULL, NULL);
9033       if (isymbuf == NULL)
9034         return FALSE;
9035
9036       /* Read in any version definitions.  */
9037       versymhdr = &elf_tdata (input)->dynversym_hdr;
9038       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9039       if (extversym == NULL)
9040         goto error_ret;
9041
9042       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9043           || (bfd_bread (extversym, versymhdr->sh_size, input)
9044               != versymhdr->sh_size))
9045         {
9046           free (extversym);
9047         error_ret:
9048           free (isymbuf);
9049           return FALSE;
9050         }
9051
9052       ever = extversym + extsymoff;
9053       isymend = isymbuf + extsymcount;
9054       for (isym = isymbuf; isym < isymend; isym++, ever++)
9055         {
9056           const char *name;
9057           Elf_Internal_Versym iver;
9058           unsigned short version_index;
9059
9060           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9061               || isym->st_shndx == SHN_UNDEF)
9062             continue;
9063
9064           name = bfd_elf_string_from_elf_section (input,
9065                                                   hdr->sh_link,
9066                                                   isym->st_name);
9067           if (strcmp (name, h->root.root.string) != 0)
9068             continue;
9069
9070           _bfd_elf_swap_versym_in (input, ever, &iver);
9071
9072           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9073               && !(h->def_regular
9074                    && h->forced_local))
9075             {
9076               /* If we have a non-hidden versioned sym, then it should
9077                  have provided a definition for the undefined sym unless
9078                  it is defined in a non-shared object and forced local.
9079                */
9080               abort ();
9081             }
9082
9083           version_index = iver.vs_vers & VERSYM_VERSION;
9084           if (version_index == 1 || version_index == 2)
9085             {
9086               /* This is the base or first version.  We can use it.  */
9087               free (extversym);
9088               free (isymbuf);
9089               return TRUE;
9090             }
9091         }
9092
9093       free (extversym);
9094       free (isymbuf);
9095     }
9096
9097   return FALSE;
9098 }
9099
9100 /* Convert ELF common symbol TYPE.  */
9101
9102 static int
9103 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9104 {
9105   /* Commom symbol can only appear in relocatable link.  */
9106   if (!bfd_link_relocatable (info))
9107     abort ();
9108   switch (info->elf_stt_common)
9109     {
9110     case unchanged:
9111       break;
9112     case elf_stt_common:
9113       type = STT_COMMON;
9114       break;
9115     case no_elf_stt_common:
9116       type = STT_OBJECT;
9117       break;
9118     }
9119   return type;
9120 }
9121
9122 /* Add an external symbol to the symbol table.  This is called from
9123    the hash table traversal routine.  When generating a shared object,
9124    we go through the symbol table twice.  The first time we output
9125    anything that might have been forced to local scope in a version
9126    script.  The second time we output the symbols that are still
9127    global symbols.  */
9128
9129 static bfd_boolean
9130 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9131 {
9132   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9133   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9134   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9135   bfd_boolean strip;
9136   Elf_Internal_Sym sym;
9137   asection *input_sec;
9138   const struct elf_backend_data *bed;
9139   long indx;
9140   int ret;
9141   unsigned int type;
9142   /* A symbol is bound locally if it is forced local or it is locally
9143      defined, hidden versioned, not referenced by shared library and
9144      not exported when linking executable.  */
9145   bfd_boolean local_bind = (h->forced_local
9146                             || (bfd_link_executable (flinfo->info)
9147                                 && !flinfo->info->export_dynamic
9148                                 && !h->dynamic
9149                                 && !h->ref_dynamic
9150                                 && h->def_regular
9151                                 && h->versioned == versioned_hidden));
9152
9153   if (h->root.type == bfd_link_hash_warning)
9154     {
9155       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9156       if (h->root.type == bfd_link_hash_new)
9157         return TRUE;
9158     }
9159
9160   /* Decide whether to output this symbol in this pass.  */
9161   if (eoinfo->localsyms)
9162     {
9163       if (!local_bind)
9164         return TRUE;
9165     }
9166   else
9167     {
9168       if (local_bind)
9169         return TRUE;
9170     }
9171
9172   bed = get_elf_backend_data (flinfo->output_bfd);
9173
9174   if (h->root.type == bfd_link_hash_undefined)
9175     {
9176       /* If we have an undefined symbol reference here then it must have
9177          come from a shared library that is being linked in.  (Undefined
9178          references in regular files have already been handled unless
9179          they are in unreferenced sections which are removed by garbage
9180          collection).  */
9181       bfd_boolean ignore_undef = FALSE;
9182
9183       /* Some symbols may be special in that the fact that they're
9184          undefined can be safely ignored - let backend determine that.  */
9185       if (bed->elf_backend_ignore_undef_symbol)
9186         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9187
9188       /* If we are reporting errors for this situation then do so now.  */
9189       if (!ignore_undef
9190           && h->ref_dynamic
9191           && (!h->ref_regular || flinfo->info->gc_sections)
9192           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9193           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9194         {
9195           if (!(flinfo->info->callbacks->undefined_symbol
9196                 (flinfo->info, h->root.root.string,
9197                  h->ref_regular ? NULL : h->root.u.undef.abfd,
9198                  NULL, 0,
9199                  (flinfo->info->unresolved_syms_in_shared_libs
9200                   == RM_GENERATE_ERROR))))
9201             {
9202               bfd_set_error (bfd_error_bad_value);
9203               eoinfo->failed = TRUE;
9204               return FALSE;
9205             }
9206         }
9207     }
9208
9209   /* We should also warn if a forced local symbol is referenced from
9210      shared libraries.  */
9211   if (bfd_link_executable (flinfo->info)
9212       && h->forced_local
9213       && h->ref_dynamic
9214       && h->def_regular
9215       && !h->dynamic_def
9216       && h->ref_dynamic_nonweak
9217       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9218     {
9219       bfd *def_bfd;
9220       const char *msg;
9221       struct elf_link_hash_entry *hi = h;
9222
9223       /* Check indirect symbol.  */
9224       while (hi->root.type == bfd_link_hash_indirect)
9225         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9226
9227       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9228         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9229       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9230         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9231       else
9232         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9233       def_bfd = flinfo->output_bfd;
9234       if (hi->root.u.def.section != bfd_abs_section_ptr)
9235         def_bfd = hi->root.u.def.section->owner;
9236       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9237                              h->root.root.string);
9238       bfd_set_error (bfd_error_bad_value);
9239       eoinfo->failed = TRUE;
9240       return FALSE;
9241     }
9242
9243   /* We don't want to output symbols that have never been mentioned by
9244      a regular file, or that we have been told to strip.  However, if
9245      h->indx is set to -2, the symbol is used by a reloc and we must
9246      output it.  */
9247   strip = FALSE;
9248   if (h->indx == -2)
9249     ;
9250   else if ((h->def_dynamic
9251             || h->ref_dynamic
9252             || h->root.type == bfd_link_hash_new)
9253            && !h->def_regular
9254            && !h->ref_regular)
9255     strip = TRUE;
9256   else if (flinfo->info->strip == strip_all)
9257     strip = TRUE;
9258   else if (flinfo->info->strip == strip_some
9259            && bfd_hash_lookup (flinfo->info->keep_hash,
9260                                h->root.root.string, FALSE, FALSE) == NULL)
9261     strip = TRUE;
9262   else if ((h->root.type == bfd_link_hash_defined
9263             || h->root.type == bfd_link_hash_defweak)
9264            && ((flinfo->info->strip_discarded
9265                 && discarded_section (h->root.u.def.section))
9266                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9267                    && h->root.u.def.section->owner != NULL
9268                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9269     strip = TRUE;
9270   else if ((h->root.type == bfd_link_hash_undefined
9271             || h->root.type == bfd_link_hash_undefweak)
9272            && h->root.u.undef.abfd != NULL
9273            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9274     strip = TRUE;
9275
9276   type = h->type;
9277
9278   /* If we're stripping it, and it's not a dynamic symbol, there's
9279      nothing else to do.   However, if it is a forced local symbol or
9280      an ifunc symbol we need to give the backend finish_dynamic_symbol
9281      function a chance to make it dynamic.  */
9282   if (strip
9283       && h->dynindx == -1
9284       && type != STT_GNU_IFUNC
9285       && !h->forced_local)
9286     return TRUE;
9287
9288   sym.st_value = 0;
9289   sym.st_size = h->size;
9290   sym.st_other = h->other;
9291   switch (h->root.type)
9292     {
9293     default:
9294     case bfd_link_hash_new:
9295     case bfd_link_hash_warning:
9296       abort ();
9297       return FALSE;
9298
9299     case bfd_link_hash_undefined:
9300     case bfd_link_hash_undefweak:
9301       input_sec = bfd_und_section_ptr;
9302       sym.st_shndx = SHN_UNDEF;
9303       break;
9304
9305     case bfd_link_hash_defined:
9306     case bfd_link_hash_defweak:
9307       {
9308         input_sec = h->root.u.def.section;
9309         if (input_sec->output_section != NULL)
9310           {
9311             sym.st_shndx =
9312               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9313                                                  input_sec->output_section);
9314             if (sym.st_shndx == SHN_BAD)
9315               {
9316                 (*_bfd_error_handler)
9317                   (_("%B: could not find output section %A for input section %A"),
9318                    flinfo->output_bfd, input_sec->output_section, input_sec);
9319                 bfd_set_error (bfd_error_nonrepresentable_section);
9320                 eoinfo->failed = TRUE;
9321                 return FALSE;
9322               }
9323
9324             /* ELF symbols in relocatable files are section relative,
9325                but in nonrelocatable files they are virtual
9326                addresses.  */
9327             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9328             if (!bfd_link_relocatable (flinfo->info))
9329               {
9330                 sym.st_value += input_sec->output_section->vma;
9331                 if (h->type == STT_TLS)
9332                   {
9333                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9334                     if (tls_sec != NULL)
9335                       sym.st_value -= tls_sec->vma;
9336                   }
9337               }
9338           }
9339         else
9340           {
9341             BFD_ASSERT (input_sec->owner == NULL
9342                         || (input_sec->owner->flags & DYNAMIC) != 0);
9343             sym.st_shndx = SHN_UNDEF;
9344             input_sec = bfd_und_section_ptr;
9345           }
9346       }
9347       break;
9348
9349     case bfd_link_hash_common:
9350       input_sec = h->root.u.c.p->section;
9351       sym.st_shndx = bed->common_section_index (input_sec);
9352       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9353       break;
9354
9355     case bfd_link_hash_indirect:
9356       /* These symbols are created by symbol versioning.  They point
9357          to the decorated version of the name.  For example, if the
9358          symbol foo@@GNU_1.2 is the default, which should be used when
9359          foo is used with no version, then we add an indirect symbol
9360          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9361          since the indirected symbol is already in the hash table.  */
9362       return TRUE;
9363     }
9364
9365   if (type == STT_COMMON || type == STT_OBJECT)
9366     switch (h->root.type)
9367       {
9368       case bfd_link_hash_common:
9369         type = elf_link_convert_common_type (flinfo->info, type);
9370         break;
9371       case bfd_link_hash_defined:
9372       case bfd_link_hash_defweak:
9373         if (bed->common_definition (&sym))
9374           type = elf_link_convert_common_type (flinfo->info, type);
9375         else
9376           type = STT_OBJECT;
9377         break;
9378       case bfd_link_hash_undefined:
9379       case bfd_link_hash_undefweak:
9380         break;
9381       default:
9382         abort ();
9383       }
9384
9385   if (local_bind)
9386     {
9387       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9388       /* Turn off visibility on local symbol.  */
9389       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9390     }
9391   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9392   else if (h->unique_global && h->def_regular)
9393     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9394   else if (h->root.type == bfd_link_hash_undefweak
9395            || h->root.type == bfd_link_hash_defweak)
9396     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9397   else
9398     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9399   sym.st_target_internal = h->target_internal;
9400
9401   /* Give the processor backend a chance to tweak the symbol value,
9402      and also to finish up anything that needs to be done for this
9403      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9404      forced local syms when non-shared is due to a historical quirk.
9405      STT_GNU_IFUNC symbol must go through PLT.  */
9406   if ((h->type == STT_GNU_IFUNC
9407        && h->def_regular
9408        && !bfd_link_relocatable (flinfo->info))
9409       || ((h->dynindx != -1
9410            || h->forced_local)
9411           && ((bfd_link_pic (flinfo->info)
9412                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9413                    || h->root.type != bfd_link_hash_undefweak))
9414               || !h->forced_local)
9415           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9416     {
9417       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9418              (flinfo->output_bfd, flinfo->info, h, &sym)))
9419         {
9420           eoinfo->failed = TRUE;
9421           return FALSE;
9422         }
9423     }
9424
9425   /* If we are marking the symbol as undefined, and there are no
9426      non-weak references to this symbol from a regular object, then
9427      mark the symbol as weak undefined; if there are non-weak
9428      references, mark the symbol as strong.  We can't do this earlier,
9429      because it might not be marked as undefined until the
9430      finish_dynamic_symbol routine gets through with it.  */
9431   if (sym.st_shndx == SHN_UNDEF
9432       && h->ref_regular
9433       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9434           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9435     {
9436       int bindtype;
9437       type = ELF_ST_TYPE (sym.st_info);
9438
9439       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9440       if (type == STT_GNU_IFUNC)
9441         type = STT_FUNC;
9442
9443       if (h->ref_regular_nonweak)
9444         bindtype = STB_GLOBAL;
9445       else
9446         bindtype = STB_WEAK;
9447       sym.st_info = ELF_ST_INFO (bindtype, type);
9448     }
9449
9450   /* If this is a symbol defined in a dynamic library, don't use the
9451      symbol size from the dynamic library.  Relinking an executable
9452      against a new library may introduce gratuitous changes in the
9453      executable's symbols if we keep the size.  */
9454   if (sym.st_shndx == SHN_UNDEF
9455       && !h->def_regular
9456       && h->def_dynamic)
9457     sym.st_size = 0;
9458
9459   /* If a non-weak symbol with non-default visibility is not defined
9460      locally, it is a fatal error.  */
9461   if (!bfd_link_relocatable (flinfo->info)
9462       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9463       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9464       && h->root.type == bfd_link_hash_undefined
9465       && !h->def_regular)
9466     {
9467       const char *msg;
9468
9469       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9470         msg = _("%B: protected symbol `%s' isn't defined");
9471       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9472         msg = _("%B: internal symbol `%s' isn't defined");
9473       else
9474         msg = _("%B: hidden symbol `%s' isn't defined");
9475       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9476       bfd_set_error (bfd_error_bad_value);
9477       eoinfo->failed = TRUE;
9478       return FALSE;
9479     }
9480
9481   /* If this symbol should be put in the .dynsym section, then put it
9482      there now.  We already know the symbol index.  We also fill in
9483      the entry in the .hash section.  */
9484   if (elf_hash_table (flinfo->info)->dynsym != NULL
9485       && h->dynindx != -1
9486       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9487     {
9488       bfd_byte *esym;
9489
9490       /* Since there is no version information in the dynamic string,
9491          if there is no version info in symbol version section, we will
9492          have a run-time problem if not linking executable, referenced
9493          by shared library, not locally defined, or not bound locally.
9494       */
9495       if (h->verinfo.verdef == NULL
9496           && !local_bind
9497           && (!bfd_link_executable (flinfo->info)
9498               || h->ref_dynamic
9499               || !h->def_regular))
9500         {
9501           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9502
9503           if (p && p [1] != '\0')
9504             {
9505               (*_bfd_error_handler)
9506                 (_("%B: No symbol version section for versioned symbol `%s'"),
9507                  flinfo->output_bfd, h->root.root.string);
9508               eoinfo->failed = TRUE;
9509               return FALSE;
9510             }
9511         }
9512
9513       sym.st_name = h->dynstr_index;
9514       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9515               + h->dynindx * bed->s->sizeof_sym);
9516       if (!check_dynsym (flinfo->output_bfd, &sym))
9517         {
9518           eoinfo->failed = TRUE;
9519           return FALSE;
9520         }
9521       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9522
9523       if (flinfo->hash_sec != NULL)
9524         {
9525           size_t hash_entry_size;
9526           bfd_byte *bucketpos;
9527           bfd_vma chain;
9528           size_t bucketcount;
9529           size_t bucket;
9530
9531           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9532           bucket = h->u.elf_hash_value % bucketcount;
9533
9534           hash_entry_size
9535             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9536           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9537                        + (bucket + 2) * hash_entry_size);
9538           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9539           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9540                    bucketpos);
9541           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9542                    ((bfd_byte *) flinfo->hash_sec->contents
9543                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9544         }
9545
9546       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9547         {
9548           Elf_Internal_Versym iversym;
9549           Elf_External_Versym *eversym;
9550
9551           if (!h->def_regular)
9552             {
9553               if (h->verinfo.verdef == NULL
9554                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9555                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9556                 iversym.vs_vers = 0;
9557               else
9558                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9559             }
9560           else
9561             {
9562               if (h->verinfo.vertree == NULL)
9563                 iversym.vs_vers = 1;
9564               else
9565                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9566               if (flinfo->info->create_default_symver)
9567                 iversym.vs_vers++;
9568             }
9569
9570           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9571              defined locally.  */
9572           if (h->versioned == versioned_hidden && h->def_regular)
9573             iversym.vs_vers |= VERSYM_HIDDEN;
9574
9575           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9576           eversym += h->dynindx;
9577           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9578         }
9579     }
9580
9581   /* If the symbol is undefined, and we didn't output it to .dynsym,
9582      strip it from .symtab too.  Obviously we can't do this for
9583      relocatable output or when needed for --emit-relocs.  */
9584   else if (input_sec == bfd_und_section_ptr
9585            && h->indx != -2
9586            && !bfd_link_relocatable (flinfo->info))
9587     return TRUE;
9588   /* Also strip others that we couldn't earlier due to dynamic symbol
9589      processing.  */
9590   if (strip)
9591     return TRUE;
9592   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9593     return TRUE;
9594
9595   /* Output a FILE symbol so that following locals are not associated
9596      with the wrong input file.  We need one for forced local symbols
9597      if we've seen more than one FILE symbol or when we have exactly
9598      one FILE symbol but global symbols are present in a file other
9599      than the one with the FILE symbol.  We also need one if linker
9600      defined symbols are present.  In practice these conditions are
9601      always met, so just emit the FILE symbol unconditionally.  */
9602   if (eoinfo->localsyms
9603       && !eoinfo->file_sym_done
9604       && eoinfo->flinfo->filesym_count != 0)
9605     {
9606       Elf_Internal_Sym fsym;
9607
9608       memset (&fsym, 0, sizeof (fsym));
9609       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9610       fsym.st_shndx = SHN_ABS;
9611       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9612                                       bfd_und_section_ptr, NULL))
9613         return FALSE;
9614
9615       eoinfo->file_sym_done = TRUE;
9616     }
9617
9618   indx = bfd_get_symcount (flinfo->output_bfd);
9619   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9620                                    input_sec, h);
9621   if (ret == 0)
9622     {
9623       eoinfo->failed = TRUE;
9624       return FALSE;
9625     }
9626   else if (ret == 1)
9627     h->indx = indx;
9628   else if (h->indx == -2)
9629     abort();
9630
9631   return TRUE;
9632 }
9633
9634 /* Return TRUE if special handling is done for relocs in SEC against
9635    symbols defined in discarded sections.  */
9636
9637 static bfd_boolean
9638 elf_section_ignore_discarded_relocs (asection *sec)
9639 {
9640   const struct elf_backend_data *bed;
9641
9642   switch (sec->sec_info_type)
9643     {
9644     case SEC_INFO_TYPE_STABS:
9645     case SEC_INFO_TYPE_EH_FRAME:
9646     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9647       return TRUE;
9648     default:
9649       break;
9650     }
9651
9652   bed = get_elf_backend_data (sec->owner);
9653   if (bed->elf_backend_ignore_discarded_relocs != NULL
9654       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9655     return TRUE;
9656
9657   return FALSE;
9658 }
9659
9660 /* Return a mask saying how ld should treat relocations in SEC against
9661    symbols defined in discarded sections.  If this function returns
9662    COMPLAIN set, ld will issue a warning message.  If this function
9663    returns PRETEND set, and the discarded section was link-once and the
9664    same size as the kept link-once section, ld will pretend that the
9665    symbol was actually defined in the kept section.  Otherwise ld will
9666    zero the reloc (at least that is the intent, but some cooperation by
9667    the target dependent code is needed, particularly for REL targets).  */
9668
9669 unsigned int
9670 _bfd_elf_default_action_discarded (asection *sec)
9671 {
9672   if (sec->flags & SEC_DEBUGGING)
9673     return PRETEND;
9674
9675   if (strcmp (".eh_frame", sec->name) == 0)
9676     return 0;
9677
9678   if (strcmp (".gcc_except_table", sec->name) == 0)
9679     return 0;
9680
9681   return COMPLAIN | PRETEND;
9682 }
9683
9684 /* Find a match between a section and a member of a section group.  */
9685
9686 static asection *
9687 match_group_member (asection *sec, asection *group,
9688                     struct bfd_link_info *info)
9689 {
9690   asection *first = elf_next_in_group (group);
9691   asection *s = first;
9692
9693   while (s != NULL)
9694     {
9695       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9696         return s;
9697
9698       s = elf_next_in_group (s);
9699       if (s == first)
9700         break;
9701     }
9702
9703   return NULL;
9704 }
9705
9706 /* Check if the kept section of a discarded section SEC can be used
9707    to replace it.  Return the replacement if it is OK.  Otherwise return
9708    NULL.  */
9709
9710 asection *
9711 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9712 {
9713   asection *kept;
9714
9715   kept = sec->kept_section;
9716   if (kept != NULL)
9717     {
9718       if ((kept->flags & SEC_GROUP) != 0)
9719         kept = match_group_member (sec, kept, info);
9720       if (kept != NULL
9721           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9722               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9723         kept = NULL;
9724       sec->kept_section = kept;
9725     }
9726   return kept;
9727 }
9728
9729 /* Link an input file into the linker output file.  This function
9730    handles all the sections and relocations of the input file at once.
9731    This is so that we only have to read the local symbols once, and
9732    don't have to keep them in memory.  */
9733
9734 static bfd_boolean
9735 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9736 {
9737   int (*relocate_section)
9738     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9739      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9740   bfd *output_bfd;
9741   Elf_Internal_Shdr *symtab_hdr;
9742   size_t locsymcount;
9743   size_t extsymoff;
9744   Elf_Internal_Sym *isymbuf;
9745   Elf_Internal_Sym *isym;
9746   Elf_Internal_Sym *isymend;
9747   long *pindex;
9748   asection **ppsection;
9749   asection *o;
9750   const struct elf_backend_data *bed;
9751   struct elf_link_hash_entry **sym_hashes;
9752   bfd_size_type address_size;
9753   bfd_vma r_type_mask;
9754   int r_sym_shift;
9755   bfd_boolean have_file_sym = FALSE;
9756
9757   output_bfd = flinfo->output_bfd;
9758   bed = get_elf_backend_data (output_bfd);
9759   relocate_section = bed->elf_backend_relocate_section;
9760
9761   /* If this is a dynamic object, we don't want to do anything here:
9762      we don't want the local symbols, and we don't want the section
9763      contents.  */
9764   if ((input_bfd->flags & DYNAMIC) != 0)
9765     return TRUE;
9766
9767   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9768   if (elf_bad_symtab (input_bfd))
9769     {
9770       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9771       extsymoff = 0;
9772     }
9773   else
9774     {
9775       locsymcount = symtab_hdr->sh_info;
9776       extsymoff = symtab_hdr->sh_info;
9777     }
9778
9779   /* Read the local symbols.  */
9780   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9781   if (isymbuf == NULL && locsymcount != 0)
9782     {
9783       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9784                                       flinfo->internal_syms,
9785                                       flinfo->external_syms,
9786                                       flinfo->locsym_shndx);
9787       if (isymbuf == NULL)
9788         return FALSE;
9789     }
9790
9791   /* Find local symbol sections and adjust values of symbols in
9792      SEC_MERGE sections.  Write out those local symbols we know are
9793      going into the output file.  */
9794   isymend = isymbuf + locsymcount;
9795   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9796        isym < isymend;
9797        isym++, pindex++, ppsection++)
9798     {
9799       asection *isec;
9800       const char *name;
9801       Elf_Internal_Sym osym;
9802       long indx;
9803       int ret;
9804
9805       *pindex = -1;
9806
9807       if (elf_bad_symtab (input_bfd))
9808         {
9809           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9810             {
9811               *ppsection = NULL;
9812               continue;
9813             }
9814         }
9815
9816       if (isym->st_shndx == SHN_UNDEF)
9817         isec = bfd_und_section_ptr;
9818       else if (isym->st_shndx == SHN_ABS)
9819         isec = bfd_abs_section_ptr;
9820       else if (isym->st_shndx == SHN_COMMON)
9821         isec = bfd_com_section_ptr;
9822       else
9823         {
9824           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9825           if (isec == NULL)
9826             {
9827               /* Don't attempt to output symbols with st_shnx in the
9828                  reserved range other than SHN_ABS and SHN_COMMON.  */
9829               *ppsection = NULL;
9830               continue;
9831             }
9832           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9833                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9834             isym->st_value =
9835               _bfd_merged_section_offset (output_bfd, &isec,
9836                                           elf_section_data (isec)->sec_info,
9837                                           isym->st_value);
9838         }
9839
9840       *ppsection = isec;
9841
9842       /* Don't output the first, undefined, symbol.  In fact, don't
9843          output any undefined local symbol.  */
9844       if (isec == bfd_und_section_ptr)
9845         continue;
9846
9847       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9848         {
9849           /* We never output section symbols.  Instead, we use the
9850              section symbol of the corresponding section in the output
9851              file.  */
9852           continue;
9853         }
9854
9855       /* If we are stripping all symbols, we don't want to output this
9856          one.  */
9857       if (flinfo->info->strip == strip_all)
9858         continue;
9859
9860       /* If we are discarding all local symbols, we don't want to
9861          output this one.  If we are generating a relocatable output
9862          file, then some of the local symbols may be required by
9863          relocs; we output them below as we discover that they are
9864          needed.  */
9865       if (flinfo->info->discard == discard_all)
9866         continue;
9867
9868       /* If this symbol is defined in a section which we are
9869          discarding, we don't need to keep it.  */
9870       if (isym->st_shndx != SHN_UNDEF
9871           && isym->st_shndx < SHN_LORESERVE
9872           && bfd_section_removed_from_list (output_bfd,
9873                                             isec->output_section))
9874         continue;
9875
9876       /* Get the name of the symbol.  */
9877       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9878                                               isym->st_name);
9879       if (name == NULL)
9880         return FALSE;
9881
9882       /* See if we are discarding symbols with this name.  */
9883       if ((flinfo->info->strip == strip_some
9884            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9885                == NULL))
9886           || (((flinfo->info->discard == discard_sec_merge
9887                 && (isec->flags & SEC_MERGE)
9888                 && !bfd_link_relocatable (flinfo->info))
9889                || flinfo->info->discard == discard_l)
9890               && bfd_is_local_label_name (input_bfd, name)))
9891         continue;
9892
9893       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9894         {
9895           if (input_bfd->lto_output)
9896             /* -flto puts a temp file name here.  This means builds
9897                are not reproducible.  Discard the symbol.  */
9898             continue;
9899           have_file_sym = TRUE;
9900           flinfo->filesym_count += 1;
9901         }
9902       if (!have_file_sym)
9903         {
9904           /* In the absence of debug info, bfd_find_nearest_line uses
9905              FILE symbols to determine the source file for local
9906              function symbols.  Provide a FILE symbol here if input
9907              files lack such, so that their symbols won't be
9908              associated with a previous input file.  It's not the
9909              source file, but the best we can do.  */
9910           have_file_sym = TRUE;
9911           flinfo->filesym_count += 1;
9912           memset (&osym, 0, sizeof (osym));
9913           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9914           osym.st_shndx = SHN_ABS;
9915           if (!elf_link_output_symstrtab (flinfo,
9916                                           (input_bfd->lto_output ? NULL
9917                                            : input_bfd->filename),
9918                                           &osym, bfd_abs_section_ptr,
9919                                           NULL))
9920             return FALSE;
9921         }
9922
9923       osym = *isym;
9924
9925       /* Adjust the section index for the output file.  */
9926       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9927                                                          isec->output_section);
9928       if (osym.st_shndx == SHN_BAD)
9929         return FALSE;
9930
9931       /* ELF symbols in relocatable files are section relative, but
9932          in executable files they are virtual addresses.  Note that
9933          this code assumes that all ELF sections have an associated
9934          BFD section with a reasonable value for output_offset; below
9935          we assume that they also have a reasonable value for
9936          output_section.  Any special sections must be set up to meet
9937          these requirements.  */
9938       osym.st_value += isec->output_offset;
9939       if (!bfd_link_relocatable (flinfo->info))
9940         {
9941           osym.st_value += isec->output_section->vma;
9942           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9943             {
9944               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9945               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9946               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9947             }
9948         }
9949
9950       indx = bfd_get_symcount (output_bfd);
9951       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
9952       if (ret == 0)
9953         return FALSE;
9954       else if (ret == 1)
9955         *pindex = indx;
9956     }
9957
9958   if (bed->s->arch_size == 32)
9959     {
9960       r_type_mask = 0xff;
9961       r_sym_shift = 8;
9962       address_size = 4;
9963     }
9964   else
9965     {
9966       r_type_mask = 0xffffffff;
9967       r_sym_shift = 32;
9968       address_size = 8;
9969     }
9970
9971   /* Relocate the contents of each section.  */
9972   sym_hashes = elf_sym_hashes (input_bfd);
9973   for (o = input_bfd->sections; o != NULL; o = o->next)
9974     {
9975       bfd_byte *contents;
9976
9977       if (! o->linker_mark)
9978         {
9979           /* This section was omitted from the link.  */
9980           continue;
9981         }
9982
9983       if (bfd_link_relocatable (flinfo->info)
9984           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9985         {
9986           /* Deal with the group signature symbol.  */
9987           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9988           unsigned long symndx = sec_data->this_hdr.sh_info;
9989           asection *osec = o->output_section;
9990
9991           if (symndx >= locsymcount
9992               || (elf_bad_symtab (input_bfd)
9993                   && flinfo->sections[symndx] == NULL))
9994             {
9995               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9996               while (h->root.type == bfd_link_hash_indirect
9997                      || h->root.type == bfd_link_hash_warning)
9998                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9999               /* Arrange for symbol to be output.  */
10000               h->indx = -2;
10001               elf_section_data (osec)->this_hdr.sh_info = -2;
10002             }
10003           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10004             {
10005               /* We'll use the output section target_index.  */
10006               asection *sec = flinfo->sections[symndx]->output_section;
10007               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10008             }
10009           else
10010             {
10011               if (flinfo->indices[symndx] == -1)
10012                 {
10013                   /* Otherwise output the local symbol now.  */
10014                   Elf_Internal_Sym sym = isymbuf[symndx];
10015                   asection *sec = flinfo->sections[symndx]->output_section;
10016                   const char *name;
10017                   long indx;
10018                   int ret;
10019
10020                   name = bfd_elf_string_from_elf_section (input_bfd,
10021                                                           symtab_hdr->sh_link,
10022                                                           sym.st_name);
10023                   if (name == NULL)
10024                     return FALSE;
10025
10026                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10027                                                                     sec);
10028                   if (sym.st_shndx == SHN_BAD)
10029                     return FALSE;
10030
10031                   sym.st_value += o->output_offset;
10032
10033                   indx = bfd_get_symcount (output_bfd);
10034                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10035                                                    NULL);
10036                   if (ret == 0)
10037                     return FALSE;
10038                   else if (ret == 1)
10039                     flinfo->indices[symndx] = indx;
10040                   else
10041                     abort ();
10042                 }
10043               elf_section_data (osec)->this_hdr.sh_info
10044                 = flinfo->indices[symndx];
10045             }
10046         }
10047
10048       if ((o->flags & SEC_HAS_CONTENTS) == 0
10049           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10050         continue;
10051
10052       if ((o->flags & SEC_LINKER_CREATED) != 0)
10053         {
10054           /* Section was created by _bfd_elf_link_create_dynamic_sections
10055              or somesuch.  */
10056           continue;
10057         }
10058
10059       /* Get the contents of the section.  They have been cached by a
10060          relaxation routine.  Note that o is a section in an input
10061          file, so the contents field will not have been set by any of
10062          the routines which work on output files.  */
10063       if (elf_section_data (o)->this_hdr.contents != NULL)
10064         {
10065           contents = elf_section_data (o)->this_hdr.contents;
10066           if (bed->caches_rawsize
10067               && o->rawsize != 0
10068               && o->rawsize < o->size)
10069             {
10070               memcpy (flinfo->contents, contents, o->rawsize);
10071               contents = flinfo->contents;
10072             }
10073         }
10074       else
10075         {
10076           contents = flinfo->contents;
10077           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10078             return FALSE;
10079         }
10080
10081       if ((o->flags & SEC_RELOC) != 0)
10082         {
10083           Elf_Internal_Rela *internal_relocs;
10084           Elf_Internal_Rela *rel, *relend;
10085           int action_discarded;
10086           int ret;
10087
10088           /* Get the swapped relocs.  */
10089           internal_relocs
10090             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10091                                          flinfo->internal_relocs, FALSE);
10092           if (internal_relocs == NULL
10093               && o->reloc_count > 0)
10094             return FALSE;
10095
10096           /* We need to reverse-copy input .ctors/.dtors sections if
10097              they are placed in .init_array/.finit_array for output.  */
10098           if (o->size > address_size
10099               && ((strncmp (o->name, ".ctors", 6) == 0
10100                    && strcmp (o->output_section->name,
10101                               ".init_array") == 0)
10102                   || (strncmp (o->name, ".dtors", 6) == 0
10103                       && strcmp (o->output_section->name,
10104                                  ".fini_array") == 0))
10105               && (o->name[6] == 0 || o->name[6] == '.'))
10106             {
10107               if (o->size != o->reloc_count * address_size)
10108                 {
10109                   (*_bfd_error_handler)
10110                     (_("error: %B: size of section %A is not "
10111                        "multiple of address size"),
10112                      input_bfd, o);
10113                   bfd_set_error (bfd_error_on_input);
10114                   return FALSE;
10115                 }
10116               o->flags |= SEC_ELF_REVERSE_COPY;
10117             }
10118
10119           action_discarded = -1;
10120           if (!elf_section_ignore_discarded_relocs (o))
10121             action_discarded = (*bed->action_discarded) (o);
10122
10123           /* Run through the relocs evaluating complex reloc symbols and
10124              looking for relocs against symbols from discarded sections
10125              or section symbols from removed link-once sections.
10126              Complain about relocs against discarded sections.  Zero
10127              relocs against removed link-once sections.  */
10128
10129           rel = internal_relocs;
10130           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10131           for ( ; rel < relend; rel++)
10132             {
10133               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10134               unsigned int s_type;
10135               asection **ps, *sec;
10136               struct elf_link_hash_entry *h = NULL;
10137               const char *sym_name;
10138
10139               if (r_symndx == STN_UNDEF)
10140                 continue;
10141
10142               if (r_symndx >= locsymcount
10143                   || (elf_bad_symtab (input_bfd)
10144                       && flinfo->sections[r_symndx] == NULL))
10145                 {
10146                   h = sym_hashes[r_symndx - extsymoff];
10147
10148                   /* Badly formatted input files can contain relocs that
10149                      reference non-existant symbols.  Check here so that
10150                      we do not seg fault.  */
10151                   if (h == NULL)
10152                     {
10153                       char buffer [32];
10154
10155                       sprintf_vma (buffer, rel->r_info);
10156                       (*_bfd_error_handler)
10157                         (_("error: %B contains a reloc (0x%s) for section %A "
10158                            "that references a non-existent global symbol"),
10159                          input_bfd, o, buffer);
10160                       bfd_set_error (bfd_error_bad_value);
10161                       return FALSE;
10162                     }
10163
10164                   while (h->root.type == bfd_link_hash_indirect
10165                          || h->root.type == bfd_link_hash_warning)
10166                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10167
10168                   s_type = h->type;
10169
10170                   /* If a plugin symbol is referenced from a non-IR file,
10171                      mark the symbol as undefined.  Note that the
10172                      linker may attach linker created dynamic sections
10173                      to the plugin bfd.  Symbols defined in linker
10174                      created sections are not plugin symbols.  */
10175                   if (h->root.non_ir_ref
10176                       && (h->root.type == bfd_link_hash_defined
10177                           || h->root.type == bfd_link_hash_defweak)
10178                       && (h->root.u.def.section->flags
10179                           & SEC_LINKER_CREATED) == 0
10180                       && h->root.u.def.section->owner != NULL
10181                       && (h->root.u.def.section->owner->flags
10182                           & BFD_PLUGIN) != 0)
10183                     {
10184                       h->root.type = bfd_link_hash_undefined;
10185                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10186                     }
10187
10188                   ps = NULL;
10189                   if (h->root.type == bfd_link_hash_defined
10190                       || h->root.type == bfd_link_hash_defweak)
10191                     ps = &h->root.u.def.section;
10192
10193                   sym_name = h->root.root.string;
10194                 }
10195               else
10196                 {
10197                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10198
10199                   s_type = ELF_ST_TYPE (sym->st_info);
10200                   ps = &flinfo->sections[r_symndx];
10201                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10202                                                sym, *ps);
10203                 }
10204
10205               if ((s_type == STT_RELC || s_type == STT_SRELC)
10206                   && !bfd_link_relocatable (flinfo->info))
10207                 {
10208                   bfd_vma val;
10209                   bfd_vma dot = (rel->r_offset
10210                                  + o->output_offset + o->output_section->vma);
10211 #ifdef DEBUG
10212                   printf ("Encountered a complex symbol!");
10213                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10214                           input_bfd->filename, o->name,
10215                           (long) (rel - internal_relocs));
10216                   printf (" symbol: idx  %8.8lx, name %s\n",
10217                           r_symndx, sym_name);
10218                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10219                           (unsigned long) rel->r_info,
10220                           (unsigned long) rel->r_offset);
10221 #endif
10222                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10223                                     isymbuf, locsymcount, s_type == STT_SRELC))
10224                     return FALSE;
10225
10226                   /* Symbol evaluated OK.  Update to absolute value.  */
10227                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10228                                     r_symndx, val);
10229                   continue;
10230                 }
10231
10232               if (action_discarded != -1 && ps != NULL)
10233                 {
10234                   /* Complain if the definition comes from a
10235                      discarded section.  */
10236                   if ((sec = *ps) != NULL && discarded_section (sec))
10237                     {
10238                       BFD_ASSERT (r_symndx != STN_UNDEF);
10239                       if (action_discarded & COMPLAIN)
10240                         (*flinfo->info->callbacks->einfo)
10241                           (_("%X`%s' referenced in section `%A' of %B: "
10242                              "defined in discarded section `%A' of %B\n"),
10243                            sym_name, o, input_bfd, sec, sec->owner);
10244
10245                       /* Try to do the best we can to support buggy old
10246                          versions of gcc.  Pretend that the symbol is
10247                          really defined in the kept linkonce section.
10248                          FIXME: This is quite broken.  Modifying the
10249                          symbol here means we will be changing all later
10250                          uses of the symbol, not just in this section.  */
10251                       if (action_discarded & PRETEND)
10252                         {
10253                           asection *kept;
10254
10255                           kept = _bfd_elf_check_kept_section (sec,
10256                                                               flinfo->info);
10257                           if (kept != NULL)
10258                             {
10259                               *ps = kept;
10260                               continue;
10261                             }
10262                         }
10263                     }
10264                 }
10265             }
10266
10267           /* Relocate the section by invoking a back end routine.
10268
10269              The back end routine is responsible for adjusting the
10270              section contents as necessary, and (if using Rela relocs
10271              and generating a relocatable output file) adjusting the
10272              reloc addend as necessary.
10273
10274              The back end routine does not have to worry about setting
10275              the reloc address or the reloc symbol index.
10276
10277              The back end routine is given a pointer to the swapped in
10278              internal symbols, and can access the hash table entries
10279              for the external symbols via elf_sym_hashes (input_bfd).
10280
10281              When generating relocatable output, the back end routine
10282              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10283              output symbol is going to be a section symbol
10284              corresponding to the output section, which will require
10285              the addend to be adjusted.  */
10286
10287           ret = (*relocate_section) (output_bfd, flinfo->info,
10288                                      input_bfd, o, contents,
10289                                      internal_relocs,
10290                                      isymbuf,
10291                                      flinfo->sections);
10292           if (!ret)
10293             return FALSE;
10294
10295           if (ret == 2
10296               || bfd_link_relocatable (flinfo->info)
10297               || flinfo->info->emitrelocations)
10298             {
10299               Elf_Internal_Rela *irela;
10300               Elf_Internal_Rela *irelaend, *irelamid;
10301               bfd_vma last_offset;
10302               struct elf_link_hash_entry **rel_hash;
10303               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10304               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10305               unsigned int next_erel;
10306               bfd_boolean rela_normal;
10307               struct bfd_elf_section_data *esdi, *esdo;
10308
10309               esdi = elf_section_data (o);
10310               esdo = elf_section_data (o->output_section);
10311               rela_normal = FALSE;
10312
10313               /* Adjust the reloc addresses and symbol indices.  */
10314
10315               irela = internal_relocs;
10316               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10317               rel_hash = esdo->rel.hashes + esdo->rel.count;
10318               /* We start processing the REL relocs, if any.  When we reach
10319                  IRELAMID in the loop, we switch to the RELA relocs.  */
10320               irelamid = irela;
10321               if (esdi->rel.hdr != NULL)
10322                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10323                              * bed->s->int_rels_per_ext_rel);
10324               rel_hash_list = rel_hash;
10325               rela_hash_list = NULL;
10326               last_offset = o->output_offset;
10327               if (!bfd_link_relocatable (flinfo->info))
10328                 last_offset += o->output_section->vma;
10329               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10330                 {
10331                   unsigned long r_symndx;
10332                   asection *sec;
10333                   Elf_Internal_Sym sym;
10334
10335                   if (next_erel == bed->s->int_rels_per_ext_rel)
10336                     {
10337                       rel_hash++;
10338                       next_erel = 0;
10339                     }
10340
10341                   if (irela == irelamid)
10342                     {
10343                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10344                       rela_hash_list = rel_hash;
10345                       rela_normal = bed->rela_normal;
10346                     }
10347
10348                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10349                                                              flinfo->info, o,
10350                                                              irela->r_offset);
10351                   if (irela->r_offset >= (bfd_vma) -2)
10352                     {
10353                       /* This is a reloc for a deleted entry or somesuch.
10354                          Turn it into an R_*_NONE reloc, at the same
10355                          offset as the last reloc.  elf_eh_frame.c and
10356                          bfd_elf_discard_info rely on reloc offsets
10357                          being ordered.  */
10358                       irela->r_offset = last_offset;
10359                       irela->r_info = 0;
10360                       irela->r_addend = 0;
10361                       continue;
10362                     }
10363
10364                   irela->r_offset += o->output_offset;
10365
10366                   /* Relocs in an executable have to be virtual addresses.  */
10367                   if (!bfd_link_relocatable (flinfo->info))
10368                     irela->r_offset += o->output_section->vma;
10369
10370                   last_offset = irela->r_offset;
10371
10372                   r_symndx = irela->r_info >> r_sym_shift;
10373                   if (r_symndx == STN_UNDEF)
10374                     continue;
10375
10376                   if (r_symndx >= locsymcount
10377                       || (elf_bad_symtab (input_bfd)
10378                           && flinfo->sections[r_symndx] == NULL))
10379                     {
10380                       struct elf_link_hash_entry *rh;
10381                       unsigned long indx;
10382
10383                       /* This is a reloc against a global symbol.  We
10384                          have not yet output all the local symbols, so
10385                          we do not know the symbol index of any global
10386                          symbol.  We set the rel_hash entry for this
10387                          reloc to point to the global hash table entry
10388                          for this symbol.  The symbol index is then
10389                          set at the end of bfd_elf_final_link.  */
10390                       indx = r_symndx - extsymoff;
10391                       rh = elf_sym_hashes (input_bfd)[indx];
10392                       while (rh->root.type == bfd_link_hash_indirect
10393                              || rh->root.type == bfd_link_hash_warning)
10394                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10395
10396                       /* Setting the index to -2 tells
10397                          elf_link_output_extsym that this symbol is
10398                          used by a reloc.  */
10399                       BFD_ASSERT (rh->indx < 0);
10400                       rh->indx = -2;
10401
10402                       *rel_hash = rh;
10403
10404                       continue;
10405                     }
10406
10407                   /* This is a reloc against a local symbol.  */
10408
10409                   *rel_hash = NULL;
10410                   sym = isymbuf[r_symndx];
10411                   sec = flinfo->sections[r_symndx];
10412                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10413                     {
10414                       /* I suppose the backend ought to fill in the
10415                          section of any STT_SECTION symbol against a
10416                          processor specific section.  */
10417                       r_symndx = STN_UNDEF;
10418                       if (bfd_is_abs_section (sec))
10419                         ;
10420                       else if (sec == NULL || sec->owner == NULL)
10421                         {
10422                           bfd_set_error (bfd_error_bad_value);
10423                           return FALSE;
10424                         }
10425                       else
10426                         {
10427                           asection *osec = sec->output_section;
10428
10429                           /* If we have discarded a section, the output
10430                              section will be the absolute section.  In
10431                              case of discarded SEC_MERGE sections, use
10432                              the kept section.  relocate_section should
10433                              have already handled discarded linkonce
10434                              sections.  */
10435                           if (bfd_is_abs_section (osec)
10436                               && sec->kept_section != NULL
10437                               && sec->kept_section->output_section != NULL)
10438                             {
10439                               osec = sec->kept_section->output_section;
10440                               irela->r_addend -= osec->vma;
10441                             }
10442
10443                           if (!bfd_is_abs_section (osec))
10444                             {
10445                               r_symndx = osec->target_index;
10446                               if (r_symndx == STN_UNDEF)
10447                                 {
10448                                   irela->r_addend += osec->vma;
10449                                   osec = _bfd_nearby_section (output_bfd, osec,
10450                                                               osec->vma);
10451                                   irela->r_addend -= osec->vma;
10452                                   r_symndx = osec->target_index;
10453                                 }
10454                             }
10455                         }
10456
10457                       /* Adjust the addend according to where the
10458                          section winds up in the output section.  */
10459                       if (rela_normal)
10460                         irela->r_addend += sec->output_offset;
10461                     }
10462                   else
10463                     {
10464                       if (flinfo->indices[r_symndx] == -1)
10465                         {
10466                           unsigned long shlink;
10467                           const char *name;
10468                           asection *osec;
10469                           long indx;
10470
10471                           if (flinfo->info->strip == strip_all)
10472                             {
10473                               /* You can't do ld -r -s.  */
10474                               bfd_set_error (bfd_error_invalid_operation);
10475                               return FALSE;
10476                             }
10477
10478                           /* This symbol was skipped earlier, but
10479                              since it is needed by a reloc, we
10480                              must output it now.  */
10481                           shlink = symtab_hdr->sh_link;
10482                           name = (bfd_elf_string_from_elf_section
10483                                   (input_bfd, shlink, sym.st_name));
10484                           if (name == NULL)
10485                             return FALSE;
10486
10487                           osec = sec->output_section;
10488                           sym.st_shndx =
10489                             _bfd_elf_section_from_bfd_section (output_bfd,
10490                                                                osec);
10491                           if (sym.st_shndx == SHN_BAD)
10492                             return FALSE;
10493
10494                           sym.st_value += sec->output_offset;
10495                           if (!bfd_link_relocatable (flinfo->info))
10496                             {
10497                               sym.st_value += osec->vma;
10498                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10499                                 {
10500                                   /* STT_TLS symbols are relative to PT_TLS
10501                                      segment base.  */
10502                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10503                                               ->tls_sec != NULL);
10504                                   sym.st_value -= (elf_hash_table (flinfo->info)
10505                                                    ->tls_sec->vma);
10506                                 }
10507                             }
10508
10509                           indx = bfd_get_symcount (output_bfd);
10510                           ret = elf_link_output_symstrtab (flinfo, name,
10511                                                            &sym, sec,
10512                                                            NULL);
10513                           if (ret == 0)
10514                             return FALSE;
10515                           else if (ret == 1)
10516                             flinfo->indices[r_symndx] = indx;
10517                           else
10518                             abort ();
10519                         }
10520
10521                       r_symndx = flinfo->indices[r_symndx];
10522                     }
10523
10524                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10525                                    | (irela->r_info & r_type_mask));
10526                 }
10527
10528               /* Swap out the relocs.  */
10529               input_rel_hdr = esdi->rel.hdr;
10530               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10531                 {
10532                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10533                                                      input_rel_hdr,
10534                                                      internal_relocs,
10535                                                      rel_hash_list))
10536                     return FALSE;
10537                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10538                                       * bed->s->int_rels_per_ext_rel);
10539                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10540                 }
10541
10542               input_rela_hdr = esdi->rela.hdr;
10543               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10544                 {
10545                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10546                                                      input_rela_hdr,
10547                                                      internal_relocs,
10548                                                      rela_hash_list))
10549                     return FALSE;
10550                 }
10551             }
10552         }
10553
10554       /* Write out the modified section contents.  */
10555       if (bed->elf_backend_write_section
10556           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10557                                                 contents))
10558         {
10559           /* Section written out.  */
10560         }
10561       else switch (o->sec_info_type)
10562         {
10563         case SEC_INFO_TYPE_STABS:
10564           if (! (_bfd_write_section_stabs
10565                  (output_bfd,
10566                   &elf_hash_table (flinfo->info)->stab_info,
10567                   o, &elf_section_data (o)->sec_info, contents)))
10568             return FALSE;
10569           break;
10570         case SEC_INFO_TYPE_MERGE:
10571           if (! _bfd_write_merged_section (output_bfd, o,
10572                                            elf_section_data (o)->sec_info))
10573             return FALSE;
10574           break;
10575         case SEC_INFO_TYPE_EH_FRAME:
10576           {
10577             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10578                                                    o, contents))
10579               return FALSE;
10580           }
10581           break;
10582         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10583           {
10584             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10585                                                          flinfo->info,
10586                                                          o, contents))
10587               return FALSE;
10588           }
10589           break;
10590         default:
10591           {
10592             if (! (o->flags & SEC_EXCLUDE))
10593               {
10594                 file_ptr offset = (file_ptr) o->output_offset;
10595                 bfd_size_type todo = o->size;
10596
10597                 offset *= bfd_octets_per_byte (output_bfd);
10598
10599                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10600                   {
10601                     /* Reverse-copy input section to output.  */
10602                     do
10603                       {
10604                         todo -= address_size;
10605                         if (! bfd_set_section_contents (output_bfd,
10606                                                         o->output_section,
10607                                                         contents + todo,
10608                                                         offset,
10609                                                         address_size))
10610                           return FALSE;
10611                         if (todo == 0)
10612                           break;
10613                         offset += address_size;
10614                       }
10615                     while (1);
10616                   }
10617                 else if (! bfd_set_section_contents (output_bfd,
10618                                                      o->output_section,
10619                                                      contents,
10620                                                      offset, todo))
10621                   return FALSE;
10622               }
10623           }
10624           break;
10625         }
10626     }
10627
10628   return TRUE;
10629 }
10630
10631 /* Generate a reloc when linking an ELF file.  This is a reloc
10632    requested by the linker, and does not come from any input file.  This
10633    is used to build constructor and destructor tables when linking
10634    with -Ur.  */
10635
10636 static bfd_boolean
10637 elf_reloc_link_order (bfd *output_bfd,
10638                       struct bfd_link_info *info,
10639                       asection *output_section,
10640                       struct bfd_link_order *link_order)
10641 {
10642   reloc_howto_type *howto;
10643   long indx;
10644   bfd_vma offset;
10645   bfd_vma addend;
10646   struct bfd_elf_section_reloc_data *reldata;
10647   struct elf_link_hash_entry **rel_hash_ptr;
10648   Elf_Internal_Shdr *rel_hdr;
10649   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10650   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10651   bfd_byte *erel;
10652   unsigned int i;
10653   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10654
10655   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10656   if (howto == NULL)
10657     {
10658       bfd_set_error (bfd_error_bad_value);
10659       return FALSE;
10660     }
10661
10662   addend = link_order->u.reloc.p->addend;
10663
10664   if (esdo->rel.hdr)
10665     reldata = &esdo->rel;
10666   else if (esdo->rela.hdr)
10667     reldata = &esdo->rela;
10668   else
10669     {
10670       reldata = NULL;
10671       BFD_ASSERT (0);
10672     }
10673
10674   /* Figure out the symbol index.  */
10675   rel_hash_ptr = reldata->hashes + reldata->count;
10676   if (link_order->type == bfd_section_reloc_link_order)
10677     {
10678       indx = link_order->u.reloc.p->u.section->target_index;
10679       BFD_ASSERT (indx != 0);
10680       *rel_hash_ptr = NULL;
10681     }
10682   else
10683     {
10684       struct elf_link_hash_entry *h;
10685
10686       /* Treat a reloc against a defined symbol as though it were
10687          actually against the section.  */
10688       h = ((struct elf_link_hash_entry *)
10689            bfd_wrapped_link_hash_lookup (output_bfd, info,
10690                                          link_order->u.reloc.p->u.name,
10691                                          FALSE, FALSE, TRUE));
10692       if (h != NULL
10693           && (h->root.type == bfd_link_hash_defined
10694               || h->root.type == bfd_link_hash_defweak))
10695         {
10696           asection *section;
10697
10698           section = h->root.u.def.section;
10699           indx = section->output_section->target_index;
10700           *rel_hash_ptr = NULL;
10701           /* It seems that we ought to add the symbol value to the
10702              addend here, but in practice it has already been added
10703              because it was passed to constructor_callback.  */
10704           addend += section->output_section->vma + section->output_offset;
10705         }
10706       else if (h != NULL)
10707         {
10708           /* Setting the index to -2 tells elf_link_output_extsym that
10709              this symbol is used by a reloc.  */
10710           h->indx = -2;
10711           *rel_hash_ptr = h;
10712           indx = 0;
10713         }
10714       else
10715         {
10716           if (! ((*info->callbacks->unattached_reloc)
10717                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10718             return FALSE;
10719           indx = 0;
10720         }
10721     }
10722
10723   /* If this is an inplace reloc, we must write the addend into the
10724      object file.  */
10725   if (howto->partial_inplace && addend != 0)
10726     {
10727       bfd_size_type size;
10728       bfd_reloc_status_type rstat;
10729       bfd_byte *buf;
10730       bfd_boolean ok;
10731       const char *sym_name;
10732
10733       size = (bfd_size_type) bfd_get_reloc_size (howto);
10734       buf = (bfd_byte *) bfd_zmalloc (size);
10735       if (buf == NULL && size != 0)
10736         return FALSE;
10737       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10738       switch (rstat)
10739         {
10740         case bfd_reloc_ok:
10741           break;
10742
10743         default:
10744         case bfd_reloc_outofrange:
10745           abort ();
10746
10747         case bfd_reloc_overflow:
10748           if (link_order->type == bfd_section_reloc_link_order)
10749             sym_name = bfd_section_name (output_bfd,
10750                                          link_order->u.reloc.p->u.section);
10751           else
10752             sym_name = link_order->u.reloc.p->u.name;
10753           if (! ((*info->callbacks->reloc_overflow)
10754                  (info, NULL, sym_name, howto->name, addend, NULL,
10755                   NULL, (bfd_vma) 0)))
10756             {
10757               free (buf);
10758               return FALSE;
10759             }
10760           break;
10761         }
10762
10763       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10764                                      link_order->offset
10765                                      * bfd_octets_per_byte (output_bfd),
10766                                      size);
10767       free (buf);
10768       if (! ok)
10769         return FALSE;
10770     }
10771
10772   /* The address of a reloc is relative to the section in a
10773      relocatable file, and is a virtual address in an executable
10774      file.  */
10775   offset = link_order->offset;
10776   if (! bfd_link_relocatable (info))
10777     offset += output_section->vma;
10778
10779   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10780     {
10781       irel[i].r_offset = offset;
10782       irel[i].r_info = 0;
10783       irel[i].r_addend = 0;
10784     }
10785   if (bed->s->arch_size == 32)
10786     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10787   else
10788     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10789
10790   rel_hdr = reldata->hdr;
10791   erel = rel_hdr->contents;
10792   if (rel_hdr->sh_type == SHT_REL)
10793     {
10794       erel += reldata->count * bed->s->sizeof_rel;
10795       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10796     }
10797   else
10798     {
10799       irel[0].r_addend = addend;
10800       erel += reldata->count * bed->s->sizeof_rela;
10801       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10802     }
10803
10804   ++reldata->count;
10805
10806   return TRUE;
10807 }
10808
10809
10810 /* Get the output vma of the section pointed to by the sh_link field.  */
10811
10812 static bfd_vma
10813 elf_get_linked_section_vma (struct bfd_link_order *p)
10814 {
10815   Elf_Internal_Shdr **elf_shdrp;
10816   asection *s;
10817   int elfsec;
10818
10819   s = p->u.indirect.section;
10820   elf_shdrp = elf_elfsections (s->owner);
10821   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10822   elfsec = elf_shdrp[elfsec]->sh_link;
10823   /* PR 290:
10824      The Intel C compiler generates SHT_IA_64_UNWIND with
10825      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10826      sh_info fields.  Hence we could get the situation
10827      where elfsec is 0.  */
10828   if (elfsec == 0)
10829     {
10830       const struct elf_backend_data *bed
10831         = get_elf_backend_data (s->owner);
10832       if (bed->link_order_error_handler)
10833         bed->link_order_error_handler
10834           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10835       return 0;
10836     }
10837   else
10838     {
10839       s = elf_shdrp[elfsec]->bfd_section;
10840       return s->output_section->vma + s->output_offset;
10841     }
10842 }
10843
10844
10845 /* Compare two sections based on the locations of the sections they are
10846    linked to.  Used by elf_fixup_link_order.  */
10847
10848 static int
10849 compare_link_order (const void * a, const void * b)
10850 {
10851   bfd_vma apos;
10852   bfd_vma bpos;
10853
10854   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10855   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10856   if (apos < bpos)
10857     return -1;
10858   return apos > bpos;
10859 }
10860
10861
10862 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10863    order as their linked sections.  Returns false if this could not be done
10864    because an output section includes both ordered and unordered
10865    sections.  Ideally we'd do this in the linker proper.  */
10866
10867 static bfd_boolean
10868 elf_fixup_link_order (bfd *abfd, asection *o)
10869 {
10870   int seen_linkorder;
10871   int seen_other;
10872   int n;
10873   struct bfd_link_order *p;
10874   bfd *sub;
10875   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10876   unsigned elfsec;
10877   struct bfd_link_order **sections;
10878   asection *s, *other_sec, *linkorder_sec;
10879   bfd_vma offset;
10880
10881   other_sec = NULL;
10882   linkorder_sec = NULL;
10883   seen_other = 0;
10884   seen_linkorder = 0;
10885   for (p = o->map_head.link_order; p != NULL; p = p->next)
10886     {
10887       if (p->type == bfd_indirect_link_order)
10888         {
10889           s = p->u.indirect.section;
10890           sub = s->owner;
10891           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10892               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10893               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10894               && elfsec < elf_numsections (sub)
10895               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10896               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10897             {
10898               seen_linkorder++;
10899               linkorder_sec = s;
10900             }
10901           else
10902             {
10903               seen_other++;
10904               other_sec = s;
10905             }
10906         }
10907       else
10908         seen_other++;
10909
10910       if (seen_other && seen_linkorder)
10911         {
10912           if (other_sec && linkorder_sec)
10913             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10914                                    o, linkorder_sec,
10915                                    linkorder_sec->owner, other_sec,
10916                                    other_sec->owner);
10917           else
10918             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10919                                    o);
10920           bfd_set_error (bfd_error_bad_value);
10921           return FALSE;
10922         }
10923     }
10924
10925   if (!seen_linkorder)
10926     return TRUE;
10927
10928   sections = (struct bfd_link_order **)
10929     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10930   if (sections == NULL)
10931     return FALSE;
10932   seen_linkorder = 0;
10933
10934   for (p = o->map_head.link_order; p != NULL; p = p->next)
10935     {
10936       sections[seen_linkorder++] = p;
10937     }
10938   /* Sort the input sections in the order of their linked section.  */
10939   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10940          compare_link_order);
10941
10942   /* Change the offsets of the sections.  */
10943   offset = 0;
10944   for (n = 0; n < seen_linkorder; n++)
10945     {
10946       s = sections[n]->u.indirect.section;
10947       offset &= ~(bfd_vma) 0 << s->alignment_power;
10948       s->output_offset = offset / bfd_octets_per_byte (abfd);
10949       sections[n]->offset = offset;
10950       offset += sections[n]->size;
10951     }
10952
10953   free (sections);
10954   return TRUE;
10955 }
10956
10957 static void
10958 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10959 {
10960   asection *o;
10961
10962   if (flinfo->symstrtab != NULL)
10963     _bfd_elf_strtab_free (flinfo->symstrtab);
10964   if (flinfo->contents != NULL)
10965     free (flinfo->contents);
10966   if (flinfo->external_relocs != NULL)
10967     free (flinfo->external_relocs);
10968   if (flinfo->internal_relocs != NULL)
10969     free (flinfo->internal_relocs);
10970   if (flinfo->external_syms != NULL)
10971     free (flinfo->external_syms);
10972   if (flinfo->locsym_shndx != NULL)
10973     free (flinfo->locsym_shndx);
10974   if (flinfo->internal_syms != NULL)
10975     free (flinfo->internal_syms);
10976   if (flinfo->indices != NULL)
10977     free (flinfo->indices);
10978   if (flinfo->sections != NULL)
10979     free (flinfo->sections);
10980   if (flinfo->symshndxbuf != NULL)
10981     free (flinfo->symshndxbuf);
10982   for (o = obfd->sections; o != NULL; o = o->next)
10983     {
10984       struct bfd_elf_section_data *esdo = elf_section_data (o);
10985       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10986         free (esdo->rel.hashes);
10987       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10988         free (esdo->rela.hashes);
10989     }
10990 }
10991
10992 /* Do the final step of an ELF link.  */
10993
10994 bfd_boolean
10995 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10996 {
10997   bfd_boolean dynamic;
10998   bfd_boolean emit_relocs;
10999   bfd *dynobj;
11000   struct elf_final_link_info flinfo;
11001   asection *o;
11002   struct bfd_link_order *p;
11003   bfd *sub;
11004   bfd_size_type max_contents_size;
11005   bfd_size_type max_external_reloc_size;
11006   bfd_size_type max_internal_reloc_count;
11007   bfd_size_type max_sym_count;
11008   bfd_size_type max_sym_shndx_count;
11009   Elf_Internal_Sym elfsym;
11010   unsigned int i;
11011   Elf_Internal_Shdr *symtab_hdr;
11012   Elf_Internal_Shdr *symtab_shndx_hdr;
11013   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11014   struct elf_outext_info eoinfo;
11015   bfd_boolean merged;
11016   size_t relativecount = 0;
11017   asection *reldyn = 0;
11018   bfd_size_type amt;
11019   asection *attr_section = NULL;
11020   bfd_vma attr_size = 0;
11021   const char *std_attrs_section;
11022
11023   if (! is_elf_hash_table (info->hash))
11024     return FALSE;
11025
11026   if (bfd_link_pic (info))
11027     abfd->flags |= DYNAMIC;
11028
11029   dynamic = elf_hash_table (info)->dynamic_sections_created;
11030   dynobj = elf_hash_table (info)->dynobj;
11031
11032   emit_relocs = (bfd_link_relocatable (info)
11033                  || info->emitrelocations);
11034
11035   flinfo.info = info;
11036   flinfo.output_bfd = abfd;
11037   flinfo.symstrtab = _bfd_elf_strtab_init ();
11038   if (flinfo.symstrtab == NULL)
11039     return FALSE;
11040
11041   if (! dynamic)
11042     {
11043       flinfo.hash_sec = NULL;
11044       flinfo.symver_sec = NULL;
11045     }
11046   else
11047     {
11048       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11049       /* Note that dynsym_sec can be NULL (on VMS).  */
11050       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11051       /* Note that it is OK if symver_sec is NULL.  */
11052     }
11053
11054   flinfo.contents = NULL;
11055   flinfo.external_relocs = NULL;
11056   flinfo.internal_relocs = NULL;
11057   flinfo.external_syms = NULL;
11058   flinfo.locsym_shndx = NULL;
11059   flinfo.internal_syms = NULL;
11060   flinfo.indices = NULL;
11061   flinfo.sections = NULL;
11062   flinfo.symshndxbuf = NULL;
11063   flinfo.filesym_count = 0;
11064
11065   /* The object attributes have been merged.  Remove the input
11066      sections from the link, and set the contents of the output
11067      secton.  */
11068   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11069   for (o = abfd->sections; o != NULL; o = o->next)
11070     {
11071       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11072           || strcmp (o->name, ".gnu.attributes") == 0)
11073         {
11074           for (p = o->map_head.link_order; p != NULL; p = p->next)
11075             {
11076               asection *input_section;
11077
11078               if (p->type != bfd_indirect_link_order)
11079                 continue;
11080               input_section = p->u.indirect.section;
11081               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11082                  elf_link_input_bfd ignores this section.  */
11083               input_section->flags &= ~SEC_HAS_CONTENTS;
11084             }
11085
11086           attr_size = bfd_elf_obj_attr_size (abfd);
11087           if (attr_size)
11088             {
11089               bfd_set_section_size (abfd, o, attr_size);
11090               attr_section = o;
11091               /* Skip this section later on.  */
11092               o->map_head.link_order = NULL;
11093             }
11094           else
11095             o->flags |= SEC_EXCLUDE;
11096         }
11097     }
11098
11099   /* Count up the number of relocations we will output for each output
11100      section, so that we know the sizes of the reloc sections.  We
11101      also figure out some maximum sizes.  */
11102   max_contents_size = 0;
11103   max_external_reloc_size = 0;
11104   max_internal_reloc_count = 0;
11105   max_sym_count = 0;
11106   max_sym_shndx_count = 0;
11107   merged = FALSE;
11108   for (o = abfd->sections; o != NULL; o = o->next)
11109     {
11110       struct bfd_elf_section_data *esdo = elf_section_data (o);
11111       o->reloc_count = 0;
11112
11113       for (p = o->map_head.link_order; p != NULL; p = p->next)
11114         {
11115           unsigned int reloc_count = 0;
11116           unsigned int additional_reloc_count = 0;
11117           struct bfd_elf_section_data *esdi = NULL;
11118
11119           if (p->type == bfd_section_reloc_link_order
11120               || p->type == bfd_symbol_reloc_link_order)
11121             reloc_count = 1;
11122           else if (p->type == bfd_indirect_link_order)
11123             {
11124               asection *sec;
11125
11126               sec = p->u.indirect.section;
11127               esdi = elf_section_data (sec);
11128
11129               /* Mark all sections which are to be included in the
11130                  link.  This will normally be every section.  We need
11131                  to do this so that we can identify any sections which
11132                  the linker has decided to not include.  */
11133               sec->linker_mark = TRUE;
11134
11135               if (sec->flags & SEC_MERGE)
11136                 merged = TRUE;
11137
11138               if (esdo->this_hdr.sh_type == SHT_REL
11139                   || esdo->this_hdr.sh_type == SHT_RELA)
11140                 /* Some backends use reloc_count in relocation sections
11141                    to count particular types of relocs.  Of course,
11142                    reloc sections themselves can't have relocations.  */
11143                 reloc_count = 0;
11144               else if (emit_relocs)
11145                 {
11146                   reloc_count = sec->reloc_count;
11147                   if (bed->elf_backend_count_additional_relocs)
11148                     {
11149                       int c;
11150                       c = (*bed->elf_backend_count_additional_relocs) (sec);
11151                       additional_reloc_count += c;
11152                     }
11153                 }
11154               else if (bed->elf_backend_count_relocs)
11155                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11156
11157               if (sec->rawsize > max_contents_size)
11158                 max_contents_size = sec->rawsize;
11159               if (sec->size > max_contents_size)
11160                 max_contents_size = sec->size;
11161
11162               /* We are interested in just local symbols, not all
11163                  symbols.  */
11164               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11165                   && (sec->owner->flags & DYNAMIC) == 0)
11166                 {
11167                   size_t sym_count;
11168
11169                   if (elf_bad_symtab (sec->owner))
11170                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11171                                  / bed->s->sizeof_sym);
11172                   else
11173                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11174
11175                   if (sym_count > max_sym_count)
11176                     max_sym_count = sym_count;
11177
11178                   if (sym_count > max_sym_shndx_count
11179                       && elf_symtab_shndx_list (sec->owner) != NULL)
11180                     max_sym_shndx_count = sym_count;
11181
11182                   if ((sec->flags & SEC_RELOC) != 0)
11183                     {
11184                       size_t ext_size = 0;
11185
11186                       if (esdi->rel.hdr != NULL)
11187                         ext_size = esdi->rel.hdr->sh_size;
11188                       if (esdi->rela.hdr != NULL)
11189                         ext_size += esdi->rela.hdr->sh_size;
11190
11191                       if (ext_size > max_external_reloc_size)
11192                         max_external_reloc_size = ext_size;
11193                       if (sec->reloc_count > max_internal_reloc_count)
11194                         max_internal_reloc_count = sec->reloc_count;
11195                     }
11196                 }
11197             }
11198
11199           if (reloc_count == 0)
11200             continue;
11201
11202           reloc_count += additional_reloc_count;
11203           o->reloc_count += reloc_count;
11204
11205           if (p->type == bfd_indirect_link_order && emit_relocs)
11206             {
11207               if (esdi->rel.hdr)
11208                 {
11209                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11210                   esdo->rel.count += additional_reloc_count;
11211                 }
11212               if (esdi->rela.hdr)
11213                 {
11214                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11215                   esdo->rela.count += additional_reloc_count;
11216                 }
11217             }
11218           else
11219             {
11220               if (o->use_rela_p)
11221                 esdo->rela.count += reloc_count;
11222               else
11223                 esdo->rel.count += reloc_count;
11224             }
11225         }
11226
11227       if (o->reloc_count > 0)
11228         o->flags |= SEC_RELOC;
11229       else
11230         {
11231           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11232              set it (this is probably a bug) and if it is set
11233              assign_section_numbers will create a reloc section.  */
11234           o->flags &=~ SEC_RELOC;
11235         }
11236
11237       /* If the SEC_ALLOC flag is not set, force the section VMA to
11238          zero.  This is done in elf_fake_sections as well, but forcing
11239          the VMA to 0 here will ensure that relocs against these
11240          sections are handled correctly.  */
11241       if ((o->flags & SEC_ALLOC) == 0
11242           && ! o->user_set_vma)
11243         o->vma = 0;
11244     }
11245
11246   if (! bfd_link_relocatable (info) && merged)
11247     elf_link_hash_traverse (elf_hash_table (info),
11248                             _bfd_elf_link_sec_merge_syms, abfd);
11249
11250   /* Figure out the file positions for everything but the symbol table
11251      and the relocs.  We set symcount to force assign_section_numbers
11252      to create a symbol table.  */
11253   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11254   BFD_ASSERT (! abfd->output_has_begun);
11255   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11256     goto error_return;
11257
11258   /* Set sizes, and assign file positions for reloc sections.  */
11259   for (o = abfd->sections; o != NULL; o = o->next)
11260     {
11261       struct bfd_elf_section_data *esdo = elf_section_data (o);
11262       if ((o->flags & SEC_RELOC) != 0)
11263         {
11264           if (esdo->rel.hdr
11265               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11266             goto error_return;
11267
11268           if (esdo->rela.hdr
11269               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11270             goto error_return;
11271         }
11272
11273       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11274          to count upwards while actually outputting the relocations.  */
11275       esdo->rel.count = 0;
11276       esdo->rela.count = 0;
11277
11278       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11279         {
11280           /* Cache the section contents so that they can be compressed
11281              later.  Use bfd_malloc since it will be freed by
11282              bfd_compress_section_contents.  */
11283           unsigned char *contents = esdo->this_hdr.contents;
11284           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11285             abort ();
11286           contents
11287             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11288           if (contents == NULL)
11289             goto error_return;
11290           esdo->this_hdr.contents = contents;
11291         }
11292     }
11293
11294   /* We have now assigned file positions for all the sections except
11295      .symtab, .strtab, and non-loaded reloc sections.  We start the
11296      .symtab section at the current file position, and write directly
11297      to it.  We build the .strtab section in memory.  */
11298   bfd_get_symcount (abfd) = 0;
11299   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11300   /* sh_name is set in prep_headers.  */
11301   symtab_hdr->sh_type = SHT_SYMTAB;
11302   /* sh_flags, sh_addr and sh_size all start off zero.  */
11303   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11304   /* sh_link is set in assign_section_numbers.  */
11305   /* sh_info is set below.  */
11306   /* sh_offset is set just below.  */
11307   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11308
11309   if (max_sym_count < 20)
11310     max_sym_count = 20;
11311   elf_hash_table (info)->strtabsize = max_sym_count;
11312   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11313   elf_hash_table (info)->strtab
11314     = (struct elf_sym_strtab *) bfd_malloc (amt);
11315   if (elf_hash_table (info)->strtab == NULL)
11316     goto error_return;
11317   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11318   flinfo.symshndxbuf
11319     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11320        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11321
11322   if (info->strip != strip_all || emit_relocs)
11323     {
11324       file_ptr off = elf_next_file_pos (abfd);
11325
11326       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11327
11328       /* Note that at this point elf_next_file_pos (abfd) is
11329          incorrect.  We do not yet know the size of the .symtab section.
11330          We correct next_file_pos below, after we do know the size.  */
11331
11332       /* Start writing out the symbol table.  The first symbol is always a
11333          dummy symbol.  */
11334       elfsym.st_value = 0;
11335       elfsym.st_size = 0;
11336       elfsym.st_info = 0;
11337       elfsym.st_other = 0;
11338       elfsym.st_shndx = SHN_UNDEF;
11339       elfsym.st_target_internal = 0;
11340       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11341                                      bfd_und_section_ptr, NULL) != 1)
11342         goto error_return;
11343
11344       /* Output a symbol for each section.  We output these even if we are
11345          discarding local symbols, since they are used for relocs.  These
11346          symbols have no names.  We store the index of each one in the
11347          index field of the section, so that we can find it again when
11348          outputting relocs.  */
11349
11350       elfsym.st_size = 0;
11351       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11352       elfsym.st_other = 0;
11353       elfsym.st_value = 0;
11354       elfsym.st_target_internal = 0;
11355       for (i = 1; i < elf_numsections (abfd); i++)
11356         {
11357           o = bfd_section_from_elf_index (abfd, i);
11358           if (o != NULL)
11359             {
11360               o->target_index = bfd_get_symcount (abfd);
11361               elfsym.st_shndx = i;
11362               if (!bfd_link_relocatable (info))
11363                 elfsym.st_value = o->vma;
11364               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11365                                              NULL) != 1)
11366                 goto error_return;
11367             }
11368         }
11369     }
11370
11371   /* Allocate some memory to hold information read in from the input
11372      files.  */
11373   if (max_contents_size != 0)
11374     {
11375       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11376       if (flinfo.contents == NULL)
11377         goto error_return;
11378     }
11379
11380   if (max_external_reloc_size != 0)
11381     {
11382       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11383       if (flinfo.external_relocs == NULL)
11384         goto error_return;
11385     }
11386
11387   if (max_internal_reloc_count != 0)
11388     {
11389       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11390       amt *= sizeof (Elf_Internal_Rela);
11391       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11392       if (flinfo.internal_relocs == NULL)
11393         goto error_return;
11394     }
11395
11396   if (max_sym_count != 0)
11397     {
11398       amt = max_sym_count * bed->s->sizeof_sym;
11399       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11400       if (flinfo.external_syms == NULL)
11401         goto error_return;
11402
11403       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11404       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11405       if (flinfo.internal_syms == NULL)
11406         goto error_return;
11407
11408       amt = max_sym_count * sizeof (long);
11409       flinfo.indices = (long int *) bfd_malloc (amt);
11410       if (flinfo.indices == NULL)
11411         goto error_return;
11412
11413       amt = max_sym_count * sizeof (asection *);
11414       flinfo.sections = (asection **) bfd_malloc (amt);
11415       if (flinfo.sections == NULL)
11416         goto error_return;
11417     }
11418
11419   if (max_sym_shndx_count != 0)
11420     {
11421       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11422       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11423       if (flinfo.locsym_shndx == NULL)
11424         goto error_return;
11425     }
11426
11427   if (elf_hash_table (info)->tls_sec)
11428     {
11429       bfd_vma base, end = 0;
11430       asection *sec;
11431
11432       for (sec = elf_hash_table (info)->tls_sec;
11433            sec && (sec->flags & SEC_THREAD_LOCAL);
11434            sec = sec->next)
11435         {
11436           bfd_size_type size = sec->size;
11437
11438           if (size == 0
11439               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11440             {
11441               struct bfd_link_order *ord = sec->map_tail.link_order;
11442
11443               if (ord != NULL)
11444                 size = ord->offset + ord->size;
11445             }
11446           end = sec->vma + size;
11447         }
11448       base = elf_hash_table (info)->tls_sec->vma;
11449       /* Only align end of TLS section if static TLS doesn't have special
11450          alignment requirements.  */
11451       if (bed->static_tls_alignment == 1)
11452         end = align_power (end,
11453                            elf_hash_table (info)->tls_sec->alignment_power);
11454       elf_hash_table (info)->tls_size = end - base;
11455     }
11456
11457   /* Reorder SHF_LINK_ORDER sections.  */
11458   for (o = abfd->sections; o != NULL; o = o->next)
11459     {
11460       if (!elf_fixup_link_order (abfd, o))
11461         return FALSE;
11462     }
11463
11464   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11465     return FALSE;
11466
11467   /* Since ELF permits relocations to be against local symbols, we
11468      must have the local symbols available when we do the relocations.
11469      Since we would rather only read the local symbols once, and we
11470      would rather not keep them in memory, we handle all the
11471      relocations for a single input file at the same time.
11472
11473      Unfortunately, there is no way to know the total number of local
11474      symbols until we have seen all of them, and the local symbol
11475      indices precede the global symbol indices.  This means that when
11476      we are generating relocatable output, and we see a reloc against
11477      a global symbol, we can not know the symbol index until we have
11478      finished examining all the local symbols to see which ones we are
11479      going to output.  To deal with this, we keep the relocations in
11480      memory, and don't output them until the end of the link.  This is
11481      an unfortunate waste of memory, but I don't see a good way around
11482      it.  Fortunately, it only happens when performing a relocatable
11483      link, which is not the common case.  FIXME: If keep_memory is set
11484      we could write the relocs out and then read them again; I don't
11485      know how bad the memory loss will be.  */
11486
11487   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11488     sub->output_has_begun = FALSE;
11489   for (o = abfd->sections; o != NULL; o = o->next)
11490     {
11491       for (p = o->map_head.link_order; p != NULL; p = p->next)
11492         {
11493           if (p->type == bfd_indirect_link_order
11494               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11495                   == bfd_target_elf_flavour)
11496               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11497             {
11498               if (! sub->output_has_begun)
11499                 {
11500                   if (! elf_link_input_bfd (&flinfo, sub))
11501                     goto error_return;
11502                   sub->output_has_begun = TRUE;
11503                 }
11504             }
11505           else if (p->type == bfd_section_reloc_link_order
11506                    || p->type == bfd_symbol_reloc_link_order)
11507             {
11508               if (! elf_reloc_link_order (abfd, info, o, p))
11509                 goto error_return;
11510             }
11511           else
11512             {
11513               if (! _bfd_default_link_order (abfd, info, o, p))
11514                 {
11515                   if (p->type == bfd_indirect_link_order
11516                       && (bfd_get_flavour (sub)
11517                           == bfd_target_elf_flavour)
11518                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11519                           != bed->s->elfclass))
11520                     {
11521                       const char *iclass, *oclass;
11522
11523                       switch (bed->s->elfclass)
11524                         {
11525                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11526                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11527                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11528                         default: abort ();
11529                         }
11530
11531                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11532                         {
11533                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11534                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11535                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11536                         default: abort ();
11537                         }
11538
11539                       bfd_set_error (bfd_error_wrong_format);
11540                       (*_bfd_error_handler)
11541                         (_("%B: file class %s incompatible with %s"),
11542                          sub, iclass, oclass);
11543                     }
11544
11545                   goto error_return;
11546                 }
11547             }
11548         }
11549     }
11550
11551   /* Free symbol buffer if needed.  */
11552   if (!info->reduce_memory_overheads)
11553     {
11554       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11555         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11556             && elf_tdata (sub)->symbuf)
11557           {
11558             free (elf_tdata (sub)->symbuf);
11559             elf_tdata (sub)->symbuf = NULL;
11560           }
11561     }
11562
11563   /* Output any global symbols that got converted to local in a
11564      version script or due to symbol visibility.  We do this in a
11565      separate step since ELF requires all local symbols to appear
11566      prior to any global symbols.  FIXME: We should only do this if
11567      some global symbols were, in fact, converted to become local.
11568      FIXME: Will this work correctly with the Irix 5 linker?  */
11569   eoinfo.failed = FALSE;
11570   eoinfo.flinfo = &flinfo;
11571   eoinfo.localsyms = TRUE;
11572   eoinfo.file_sym_done = FALSE;
11573   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11574   if (eoinfo.failed)
11575     return FALSE;
11576
11577   /* If backend needs to output some local symbols not present in the hash
11578      table, do it now.  */
11579   if (bed->elf_backend_output_arch_local_syms
11580       && (info->strip != strip_all || emit_relocs))
11581     {
11582       typedef int (*out_sym_func)
11583         (void *, const char *, Elf_Internal_Sym *, asection *,
11584          struct elf_link_hash_entry *);
11585
11586       if (! ((*bed->elf_backend_output_arch_local_syms)
11587              (abfd, info, &flinfo,
11588               (out_sym_func) elf_link_output_symstrtab)))
11589         return FALSE;
11590     }
11591
11592   /* That wrote out all the local symbols.  Finish up the symbol table
11593      with the global symbols. Even if we want to strip everything we
11594      can, we still need to deal with those global symbols that got
11595      converted to local in a version script.  */
11596
11597   /* The sh_info field records the index of the first non local symbol.  */
11598   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11599
11600   if (dynamic
11601       && elf_hash_table (info)->dynsym != NULL
11602       && (elf_hash_table (info)->dynsym->output_section
11603           != bfd_abs_section_ptr))
11604     {
11605       Elf_Internal_Sym sym;
11606       bfd_byte *dynsym = elf_hash_table (info)->dynsym->contents;
11607       long last_local = 0;
11608
11609       /* Write out the section symbols for the output sections.  */
11610       if (bfd_link_pic (info)
11611           || elf_hash_table (info)->is_relocatable_executable)
11612         {
11613           asection *s;
11614
11615           sym.st_size = 0;
11616           sym.st_name = 0;
11617           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11618           sym.st_other = 0;
11619           sym.st_target_internal = 0;
11620
11621           for (s = abfd->sections; s != NULL; s = s->next)
11622             {
11623               int indx;
11624               bfd_byte *dest;
11625               long dynindx;
11626
11627               dynindx = elf_section_data (s)->dynindx;
11628               if (dynindx <= 0)
11629                 continue;
11630               indx = elf_section_data (s)->this_idx;
11631               BFD_ASSERT (indx > 0);
11632               sym.st_shndx = indx;
11633               if (! check_dynsym (abfd, &sym))
11634                 return FALSE;
11635               sym.st_value = s->vma;
11636               dest = dynsym + dynindx * bed->s->sizeof_sym;
11637               if (last_local < dynindx)
11638                 last_local = dynindx;
11639               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11640             }
11641         }
11642
11643       /* Write out the local dynsyms.  */
11644       if (elf_hash_table (info)->dynlocal)
11645         {
11646           struct elf_link_local_dynamic_entry *e;
11647           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11648             {
11649               asection *s;
11650               bfd_byte *dest;
11651
11652               /* Copy the internal symbol and turn off visibility.
11653                  Note that we saved a word of storage and overwrote
11654                  the original st_name with the dynstr_index.  */
11655               sym = e->isym;
11656               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11657
11658               s = bfd_section_from_elf_index (e->input_bfd,
11659                                               e->isym.st_shndx);
11660               if (s != NULL)
11661                 {
11662                   sym.st_shndx =
11663                     elf_section_data (s->output_section)->this_idx;
11664                   if (! check_dynsym (abfd, &sym))
11665                     return FALSE;
11666                   sym.st_value = (s->output_section->vma
11667                                   + s->output_offset
11668                                   + e->isym.st_value);
11669                 }
11670
11671               if (last_local < e->dynindx)
11672                 last_local = e->dynindx;
11673
11674               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11675               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11676             }
11677         }
11678
11679       elf_section_data (elf_hash_table (info)->dynsym->output_section)->this_hdr.sh_info =
11680         last_local + 1;
11681     }
11682
11683   /* We get the global symbols from the hash table.  */
11684   eoinfo.failed = FALSE;
11685   eoinfo.localsyms = FALSE;
11686   eoinfo.flinfo = &flinfo;
11687   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11688   if (eoinfo.failed)
11689     return FALSE;
11690
11691   /* If backend needs to output some symbols not present in the hash
11692      table, do it now.  */
11693   if (bed->elf_backend_output_arch_syms
11694       && (info->strip != strip_all || emit_relocs))
11695     {
11696       typedef int (*out_sym_func)
11697         (void *, const char *, Elf_Internal_Sym *, asection *,
11698          struct elf_link_hash_entry *);
11699
11700       if (! ((*bed->elf_backend_output_arch_syms)
11701              (abfd, info, &flinfo,
11702               (out_sym_func) elf_link_output_symstrtab)))
11703         return FALSE;
11704     }
11705
11706   /* Finalize the .strtab section.  */
11707   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11708
11709   /* Swap out the .strtab section. */
11710   if (!elf_link_swap_symbols_out (&flinfo))
11711     return FALSE;
11712
11713   /* Now we know the size of the symtab section.  */
11714   if (bfd_get_symcount (abfd) > 0)
11715     {
11716       /* Finish up and write out the symbol string table (.strtab)
11717          section.  */
11718       Elf_Internal_Shdr *symstrtab_hdr;
11719       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11720
11721       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
11722       if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
11723         {
11724           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11725           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11726           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11727           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11728           symtab_shndx_hdr->sh_size = amt;
11729
11730           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11731                                                            off, TRUE);
11732
11733           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11734               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11735             return FALSE;
11736         }
11737
11738       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11739       /* sh_name was set in prep_headers.  */
11740       symstrtab_hdr->sh_type = SHT_STRTAB;
11741       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
11742       symstrtab_hdr->sh_addr = 0;
11743       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11744       symstrtab_hdr->sh_entsize = 0;
11745       symstrtab_hdr->sh_link = 0;
11746       symstrtab_hdr->sh_info = 0;
11747       /* sh_offset is set just below.  */
11748       symstrtab_hdr->sh_addralign = 1;
11749
11750       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11751                                                        off, TRUE);
11752       elf_next_file_pos (abfd) = off;
11753
11754       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11755           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11756         return FALSE;
11757     }
11758
11759   /* Adjust the relocs to have the correct symbol indices.  */
11760   for (o = abfd->sections; o != NULL; o = o->next)
11761     {
11762       struct bfd_elf_section_data *esdo = elf_section_data (o);
11763       bfd_boolean sort;
11764       if ((o->flags & SEC_RELOC) == 0)
11765         continue;
11766
11767       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11768       if (esdo->rel.hdr != NULL
11769           && !elf_link_adjust_relocs (abfd, &esdo->rel, sort))
11770         return FALSE;
11771       if (esdo->rela.hdr != NULL
11772           && !elf_link_adjust_relocs (abfd, &esdo->rela, sort))
11773         return FALSE;
11774
11775       /* Set the reloc_count field to 0 to prevent write_relocs from
11776          trying to swap the relocs out itself.  */
11777       o->reloc_count = 0;
11778     }
11779
11780   if (dynamic && info->combreloc && dynobj != NULL)
11781     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11782
11783   /* If we are linking against a dynamic object, or generating a
11784      shared library, finish up the dynamic linking information.  */
11785   if (dynamic)
11786     {
11787       bfd_byte *dyncon, *dynconend;
11788
11789       /* Fix up .dynamic entries.  */
11790       o = bfd_get_linker_section (dynobj, ".dynamic");
11791       BFD_ASSERT (o != NULL);
11792
11793       dyncon = o->contents;
11794       dynconend = o->contents + o->size;
11795       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11796         {
11797           Elf_Internal_Dyn dyn;
11798           const char *name;
11799           unsigned int type;
11800
11801           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11802
11803           switch (dyn.d_tag)
11804             {
11805             default:
11806               continue;
11807             case DT_NULL:
11808               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11809                 {
11810                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11811                     {
11812                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11813                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11814                     default: continue;
11815                     }
11816                   dyn.d_un.d_val = relativecount;
11817                   relativecount = 0;
11818                   break;
11819                 }
11820               continue;
11821
11822             case DT_INIT:
11823               name = info->init_function;
11824               goto get_sym;
11825             case DT_FINI:
11826               name = info->fini_function;
11827             get_sym:
11828               {
11829                 struct elf_link_hash_entry *h;
11830
11831                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11832                                           FALSE, FALSE, TRUE);
11833                 if (h != NULL
11834                     && (h->root.type == bfd_link_hash_defined
11835                         || h->root.type == bfd_link_hash_defweak))
11836                   {
11837                     dyn.d_un.d_ptr = h->root.u.def.value;
11838                     o = h->root.u.def.section;
11839                     if (o->output_section != NULL)
11840                       dyn.d_un.d_ptr += (o->output_section->vma
11841                                          + o->output_offset);
11842                     else
11843                       {
11844                         /* The symbol is imported from another shared
11845                            library and does not apply to this one.  */
11846                         dyn.d_un.d_ptr = 0;
11847                       }
11848                     break;
11849                   }
11850               }
11851               continue;
11852
11853             case DT_PREINIT_ARRAYSZ:
11854               name = ".preinit_array";
11855               goto get_size;
11856             case DT_INIT_ARRAYSZ:
11857               name = ".init_array";
11858               goto get_size;
11859             case DT_FINI_ARRAYSZ:
11860               name = ".fini_array";
11861             get_size:
11862               o = bfd_get_section_by_name (abfd, name);
11863               if (o == NULL)
11864                 {
11865                   (*_bfd_error_handler)
11866                     (_("%B: could not find output section %s"), abfd, name);
11867                   goto error_return;
11868                 }
11869               if (o->size == 0)
11870                 (*_bfd_error_handler)
11871                   (_("warning: %s section has zero size"), name);
11872               dyn.d_un.d_val = o->size;
11873               break;
11874
11875             case DT_PREINIT_ARRAY:
11876               name = ".preinit_array";
11877               goto get_vma;
11878             case DT_INIT_ARRAY:
11879               name = ".init_array";
11880               goto get_vma;
11881             case DT_FINI_ARRAY:
11882               name = ".fini_array";
11883               goto get_vma;
11884
11885             case DT_HASH:
11886               name = ".hash";
11887               goto get_vma;
11888             case DT_GNU_HASH:
11889               name = ".gnu.hash";
11890               goto get_vma;
11891             case DT_STRTAB:
11892               name = ".dynstr";
11893               goto get_vma;
11894             case DT_SYMTAB:
11895               name = ".dynsym";
11896               goto get_vma;
11897             case DT_VERDEF:
11898               name = ".gnu.version_d";
11899               goto get_vma;
11900             case DT_VERNEED:
11901               name = ".gnu.version_r";
11902               goto get_vma;
11903             case DT_VERSYM:
11904               name = ".gnu.version";
11905             get_vma:
11906               o = bfd_get_section_by_name (abfd, name);
11907               if (o == NULL)
11908                 {
11909                   (*_bfd_error_handler)
11910                     (_("%B: could not find output section %s"), abfd, name);
11911                   goto error_return;
11912                 }
11913               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11914                 {
11915                   (*_bfd_error_handler)
11916                     (_("warning: section '%s' is being made into a note"), name);
11917                   bfd_set_error (bfd_error_nonrepresentable_section);
11918                   goto error_return;
11919                 }
11920               dyn.d_un.d_ptr = o->vma;
11921               break;
11922
11923             case DT_REL:
11924             case DT_RELA:
11925             case DT_RELSZ:
11926             case DT_RELASZ:
11927               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11928                 type = SHT_REL;
11929               else
11930                 type = SHT_RELA;
11931               dyn.d_un.d_val = 0;
11932               dyn.d_un.d_ptr = 0;
11933               for (i = 1; i < elf_numsections (abfd); i++)
11934                 {
11935                   Elf_Internal_Shdr *hdr;
11936
11937                   hdr = elf_elfsections (abfd)[i];
11938                   if (hdr->sh_type == type
11939                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11940                     {
11941                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11942                         dyn.d_un.d_val += hdr->sh_size;
11943                       else
11944                         {
11945                           if (dyn.d_un.d_ptr == 0
11946                               || hdr->sh_addr < dyn.d_un.d_ptr)
11947                             dyn.d_un.d_ptr = hdr->sh_addr;
11948                         }
11949                     }
11950                 }
11951               break;
11952             }
11953           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11954         }
11955     }
11956
11957   /* If we have created any dynamic sections, then output them.  */
11958   if (dynobj != NULL)
11959     {
11960       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11961         goto error_return;
11962
11963       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11964       if (((info->warn_shared_textrel && bfd_link_pic (info))
11965            || info->error_textrel)
11966           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11967         {
11968           bfd_byte *dyncon, *dynconend;
11969
11970           dyncon = o->contents;
11971           dynconend = o->contents + o->size;
11972           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11973             {
11974               Elf_Internal_Dyn dyn;
11975
11976               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11977
11978               if (dyn.d_tag == DT_TEXTREL)
11979                 {
11980                   if (info->error_textrel)
11981                     info->callbacks->einfo
11982                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11983                   else
11984                     info->callbacks->einfo
11985                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11986                   break;
11987                 }
11988             }
11989         }
11990
11991       for (o = dynobj->sections; o != NULL; o = o->next)
11992         {
11993           if ((o->flags & SEC_HAS_CONTENTS) == 0
11994               || o->size == 0
11995               || o->output_section == bfd_abs_section_ptr)
11996             continue;
11997           if ((o->flags & SEC_LINKER_CREATED) == 0)
11998             {
11999               /* At this point, we are only interested in sections
12000                  created by _bfd_elf_link_create_dynamic_sections.  */
12001               continue;
12002             }
12003           if (elf_hash_table (info)->stab_info.stabstr == o)
12004             continue;
12005           if (elf_hash_table (info)->eh_info.hdr_sec == o)
12006             continue;
12007           if (strcmp (o->name, ".dynstr") != 0)
12008             {
12009               if (! bfd_set_section_contents (abfd, o->output_section,
12010                                               o->contents,
12011                                               (file_ptr) o->output_offset
12012                                               * bfd_octets_per_byte (abfd),
12013                                               o->size))
12014                 goto error_return;
12015             }
12016           else
12017             {
12018               /* The contents of the .dynstr section are actually in a
12019                  stringtab.  */
12020               file_ptr off;
12021
12022               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12023               if (bfd_seek (abfd, off, SEEK_SET) != 0
12024                   || ! _bfd_elf_strtab_emit (abfd,
12025                                              elf_hash_table (info)->dynstr))
12026                 goto error_return;
12027             }
12028         }
12029     }
12030
12031   if (bfd_link_relocatable (info))
12032     {
12033       bfd_boolean failed = FALSE;
12034
12035       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12036       if (failed)
12037         goto error_return;
12038     }
12039
12040   /* If we have optimized stabs strings, output them.  */
12041   if (elf_hash_table (info)->stab_info.stabstr != NULL)
12042     {
12043       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
12044         goto error_return;
12045     }
12046
12047   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12048     goto error_return;
12049
12050   elf_final_link_free (abfd, &flinfo);
12051
12052   elf_linker (abfd) = TRUE;
12053
12054   if (attr_section)
12055     {
12056       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12057       if (contents == NULL)
12058         return FALSE;   /* Bail out and fail.  */
12059       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12060       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12061       free (contents);
12062     }
12063
12064   return TRUE;
12065
12066  error_return:
12067   elf_final_link_free (abfd, &flinfo);
12068   return FALSE;
12069 }
12070 \f
12071 /* Initialize COOKIE for input bfd ABFD.  */
12072
12073 static bfd_boolean
12074 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12075                    struct bfd_link_info *info, bfd *abfd)
12076 {
12077   Elf_Internal_Shdr *symtab_hdr;
12078   const struct elf_backend_data *bed;
12079
12080   bed = get_elf_backend_data (abfd);
12081   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12082
12083   cookie->abfd = abfd;
12084   cookie->sym_hashes = elf_sym_hashes (abfd);
12085   cookie->bad_symtab = elf_bad_symtab (abfd);
12086   if (cookie->bad_symtab)
12087     {
12088       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12089       cookie->extsymoff = 0;
12090     }
12091   else
12092     {
12093       cookie->locsymcount = symtab_hdr->sh_info;
12094       cookie->extsymoff = symtab_hdr->sh_info;
12095     }
12096
12097   if (bed->s->arch_size == 32)
12098     cookie->r_sym_shift = 8;
12099   else
12100     cookie->r_sym_shift = 32;
12101
12102   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12103   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12104     {
12105       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12106                                               cookie->locsymcount, 0,
12107                                               NULL, NULL, NULL);
12108       if (cookie->locsyms == NULL)
12109         {
12110           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12111           return FALSE;
12112         }
12113       if (info->keep_memory)
12114         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12115     }
12116   return TRUE;
12117 }
12118
12119 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12120
12121 static void
12122 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12123 {
12124   Elf_Internal_Shdr *symtab_hdr;
12125
12126   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12127   if (cookie->locsyms != NULL
12128       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12129     free (cookie->locsyms);
12130 }
12131
12132 /* Initialize the relocation information in COOKIE for input section SEC
12133    of input bfd ABFD.  */
12134
12135 static bfd_boolean
12136 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12137                         struct bfd_link_info *info, bfd *abfd,
12138                         asection *sec)
12139 {
12140   const struct elf_backend_data *bed;
12141
12142   if (sec->reloc_count == 0)
12143     {
12144       cookie->rels = NULL;
12145       cookie->relend = NULL;
12146     }
12147   else
12148     {
12149       bed = get_elf_backend_data (abfd);
12150
12151       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12152                                                 info->keep_memory);
12153       if (cookie->rels == NULL)
12154         return FALSE;
12155       cookie->rel = cookie->rels;
12156       cookie->relend = (cookie->rels
12157                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12158     }
12159   cookie->rel = cookie->rels;
12160   return TRUE;
12161 }
12162
12163 /* Free the memory allocated by init_reloc_cookie_rels,
12164    if appropriate.  */
12165
12166 static void
12167 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12168                         asection *sec)
12169 {
12170   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12171     free (cookie->rels);
12172 }
12173
12174 /* Initialize the whole of COOKIE for input section SEC.  */
12175
12176 static bfd_boolean
12177 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12178                                struct bfd_link_info *info,
12179                                asection *sec)
12180 {
12181   if (!init_reloc_cookie (cookie, info, sec->owner))
12182     goto error1;
12183   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12184     goto error2;
12185   return TRUE;
12186
12187  error2:
12188   fini_reloc_cookie (cookie, sec->owner);
12189  error1:
12190   return FALSE;
12191 }
12192
12193 /* Free the memory allocated by init_reloc_cookie_for_section,
12194    if appropriate.  */
12195
12196 static void
12197 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12198                                asection *sec)
12199 {
12200   fini_reloc_cookie_rels (cookie, sec);
12201   fini_reloc_cookie (cookie, sec->owner);
12202 }
12203 \f
12204 /* Garbage collect unused sections.  */
12205
12206 /* Default gc_mark_hook.  */
12207
12208 asection *
12209 _bfd_elf_gc_mark_hook (asection *sec,
12210                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12211                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12212                        struct elf_link_hash_entry *h,
12213                        Elf_Internal_Sym *sym)
12214 {
12215   if (h != NULL)
12216     {
12217       switch (h->root.type)
12218         {
12219         case bfd_link_hash_defined:
12220         case bfd_link_hash_defweak:
12221           return h->root.u.def.section;
12222
12223         case bfd_link_hash_common:
12224           return h->root.u.c.p->section;
12225
12226         default:
12227           break;
12228         }
12229     }
12230   else
12231     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12232
12233   return NULL;
12234 }
12235
12236 /* COOKIE->rel describes a relocation against section SEC, which is
12237    a section we've decided to keep.  Return the section that contains
12238    the relocation symbol, or NULL if no section contains it.  */
12239
12240 asection *
12241 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12242                        elf_gc_mark_hook_fn gc_mark_hook,
12243                        struct elf_reloc_cookie *cookie,
12244                        bfd_boolean *start_stop)
12245 {
12246   unsigned long r_symndx;
12247   struct elf_link_hash_entry *h;
12248
12249   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12250   if (r_symndx == STN_UNDEF)
12251     return NULL;
12252
12253   if (r_symndx >= cookie->locsymcount
12254       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12255     {
12256       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12257       if (h == NULL)
12258         {
12259           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12260                                   sec->owner);
12261           return NULL;
12262         }
12263       while (h->root.type == bfd_link_hash_indirect
12264              || h->root.type == bfd_link_hash_warning)
12265         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12266       h->mark = 1;
12267       /* If this symbol is weak and there is a non-weak definition, we
12268          keep the non-weak definition because many backends put
12269          dynamic reloc info on the non-weak definition for code
12270          handling copy relocs.  */
12271       if (h->u.weakdef != NULL)
12272         h->u.weakdef->mark = 1;
12273
12274       if (start_stop != NULL
12275           && (h->root.type == bfd_link_hash_undefined
12276               || h->root.type == bfd_link_hash_undefweak))
12277         {
12278           /* To work around a glibc bug, mark all XXX input sections
12279              when there is an as yet undefined reference to __start_XXX
12280              or __stop_XXX symbols.  The linker will later define such
12281              symbols for orphan input sections that have a name
12282              representable as a C identifier.  */
12283           const char *sec_name = NULL;
12284           if (strncmp (h->root.root.string, "__start_", 8) == 0)
12285             sec_name = h->root.root.string + 8;
12286           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12287             sec_name = h->root.root.string + 7;
12288
12289           if (sec_name != NULL && *sec_name != '\0')
12290             {
12291               bfd *i;
12292
12293               for (i = info->input_bfds; i != NULL; i = i->link.next)
12294                 {
12295                   asection *s = bfd_get_section_by_name (i, sec_name);
12296                   if (s != NULL && !s->gc_mark)
12297                     {
12298                       *start_stop = TRUE;
12299                       return s;
12300                     }
12301                 }
12302             }
12303         }
12304
12305       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12306     }
12307
12308   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12309                           &cookie->locsyms[r_symndx]);
12310 }
12311
12312 /* COOKIE->rel describes a relocation against section SEC, which is
12313    a section we've decided to keep.  Mark the section that contains
12314    the relocation symbol.  */
12315
12316 bfd_boolean
12317 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12318                         asection *sec,
12319                         elf_gc_mark_hook_fn gc_mark_hook,
12320                         struct elf_reloc_cookie *cookie)
12321 {
12322   asection *rsec;
12323   bfd_boolean start_stop = FALSE;
12324
12325   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12326   while (rsec != NULL)
12327     {
12328       if (!rsec->gc_mark)
12329         {
12330           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12331               || (rsec->owner->flags & DYNAMIC) != 0)
12332             rsec->gc_mark = 1;
12333           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12334             return FALSE;
12335         }
12336       if (!start_stop)
12337         break;
12338       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12339     }
12340   return TRUE;
12341 }
12342
12343 /* The mark phase of garbage collection.  For a given section, mark
12344    it and any sections in this section's group, and all the sections
12345    which define symbols to which it refers.  */
12346
12347 bfd_boolean
12348 _bfd_elf_gc_mark (struct bfd_link_info *info,
12349                   asection *sec,
12350                   elf_gc_mark_hook_fn gc_mark_hook)
12351 {
12352   bfd_boolean ret;
12353   asection *group_sec, *eh_frame;
12354
12355   sec->gc_mark = 1;
12356
12357   /* Mark all the sections in the group.  */
12358   group_sec = elf_section_data (sec)->next_in_group;
12359   if (group_sec && !group_sec->gc_mark)
12360     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12361       return FALSE;
12362
12363   /* Look through the section relocs.  */
12364   ret = TRUE;
12365   eh_frame = elf_eh_frame_section (sec->owner);
12366   if ((sec->flags & SEC_RELOC) != 0
12367       && sec->reloc_count > 0
12368       && sec != eh_frame)
12369     {
12370       struct elf_reloc_cookie cookie;
12371
12372       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12373         ret = FALSE;
12374       else
12375         {
12376           for (; cookie.rel < cookie.relend; cookie.rel++)
12377             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12378               {
12379                 ret = FALSE;
12380                 break;
12381               }
12382           fini_reloc_cookie_for_section (&cookie, sec);
12383         }
12384     }
12385
12386   if (ret && eh_frame && elf_fde_list (sec))
12387     {
12388       struct elf_reloc_cookie cookie;
12389
12390       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12391         ret = FALSE;
12392       else
12393         {
12394           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12395                                       gc_mark_hook, &cookie))
12396             ret = FALSE;
12397           fini_reloc_cookie_for_section (&cookie, eh_frame);
12398         }
12399     }
12400
12401   eh_frame = elf_section_eh_frame_entry (sec);
12402   if (ret && eh_frame && !eh_frame->gc_mark)
12403     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12404       ret = FALSE;
12405
12406   return ret;
12407 }
12408
12409 /* Scan and mark sections in a special or debug section group.  */
12410
12411 static void
12412 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12413 {
12414   /* Point to first section of section group.  */
12415   asection *ssec;
12416   /* Used to iterate the section group.  */
12417   asection *msec;
12418
12419   bfd_boolean is_special_grp = TRUE;
12420   bfd_boolean is_debug_grp = TRUE;
12421
12422   /* First scan to see if group contains any section other than debug
12423      and special section.  */
12424   ssec = msec = elf_next_in_group (grp);
12425   do
12426     {
12427       if ((msec->flags & SEC_DEBUGGING) == 0)
12428         is_debug_grp = FALSE;
12429
12430       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12431         is_special_grp = FALSE;
12432
12433       msec = elf_next_in_group (msec);
12434     }
12435   while (msec != ssec);
12436
12437   /* If this is a pure debug section group or pure special section group,
12438      keep all sections in this group.  */
12439   if (is_debug_grp || is_special_grp)
12440     {
12441       do
12442         {
12443           msec->gc_mark = 1;
12444           msec = elf_next_in_group (msec);
12445         }
12446       while (msec != ssec);
12447     }
12448 }
12449
12450 /* Keep debug and special sections.  */
12451
12452 bfd_boolean
12453 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12454                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12455 {
12456   bfd *ibfd;
12457
12458   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12459     {
12460       asection *isec;
12461       bfd_boolean some_kept;
12462       bfd_boolean debug_frag_seen;
12463
12464       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12465         continue;
12466
12467       /* Ensure all linker created sections are kept,
12468          see if any other section is already marked,
12469          and note if we have any fragmented debug sections.  */
12470       debug_frag_seen = some_kept = FALSE;
12471       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12472         {
12473           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12474             isec->gc_mark = 1;
12475           else if (isec->gc_mark)
12476             some_kept = TRUE;
12477
12478           if (debug_frag_seen == FALSE
12479               && (isec->flags & SEC_DEBUGGING)
12480               && CONST_STRNEQ (isec->name, ".debug_line."))
12481             debug_frag_seen = TRUE;
12482         }
12483
12484       /* If no section in this file will be kept, then we can
12485          toss out the debug and special sections.  */
12486       if (!some_kept)
12487         continue;
12488
12489       /* Keep debug and special sections like .comment when they are
12490          not part of a group.  Also keep section groups that contain
12491          just debug sections or special sections.  */
12492       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12493         {
12494           if ((isec->flags & SEC_GROUP) != 0)
12495             _bfd_elf_gc_mark_debug_special_section_group (isec);
12496           else if (((isec->flags & SEC_DEBUGGING) != 0
12497                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12498                    && elf_next_in_group (isec) == NULL)
12499             isec->gc_mark = 1;
12500         }
12501
12502       if (! debug_frag_seen)
12503         continue;
12504
12505       /* Look for CODE sections which are going to be discarded,
12506          and find and discard any fragmented debug sections which
12507          are associated with that code section.  */
12508       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12509         if ((isec->flags & SEC_CODE) != 0
12510             && isec->gc_mark == 0)
12511           {
12512             unsigned int ilen;
12513             asection *dsec;
12514
12515             ilen = strlen (isec->name);
12516
12517             /* Association is determined by the name of the debug section
12518                containing the name of the code section as a suffix.  For
12519                example .debug_line.text.foo is a debug section associated
12520                with .text.foo.  */
12521             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12522               {
12523                 unsigned int dlen;
12524
12525                 if (dsec->gc_mark == 0
12526                     || (dsec->flags & SEC_DEBUGGING) == 0)
12527                   continue;
12528
12529                 dlen = strlen (dsec->name);
12530
12531                 if (dlen > ilen
12532                     && strncmp (dsec->name + (dlen - ilen),
12533                                 isec->name, ilen) == 0)
12534                   {
12535                     dsec->gc_mark = 0;
12536                   }
12537               }
12538           }
12539     }
12540   return TRUE;
12541 }
12542
12543 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12544
12545 struct elf_gc_sweep_symbol_info
12546 {
12547   struct bfd_link_info *info;
12548   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12549                        bfd_boolean);
12550 };
12551
12552 static bfd_boolean
12553 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12554 {
12555   if (!h->mark
12556       && (((h->root.type == bfd_link_hash_defined
12557             || h->root.type == bfd_link_hash_defweak)
12558            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12559                 && h->root.u.def.section->gc_mark))
12560           || h->root.type == bfd_link_hash_undefined
12561           || h->root.type == bfd_link_hash_undefweak))
12562     {
12563       struct elf_gc_sweep_symbol_info *inf;
12564
12565       inf = (struct elf_gc_sweep_symbol_info *) data;
12566       (*inf->hide_symbol) (inf->info, h, TRUE);
12567       h->def_regular = 0;
12568       h->ref_regular = 0;
12569       h->ref_regular_nonweak = 0;
12570     }
12571
12572   return TRUE;
12573 }
12574
12575 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12576
12577 typedef bfd_boolean (*gc_sweep_hook_fn)
12578   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12579
12580 static bfd_boolean
12581 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12582 {
12583   bfd *sub;
12584   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12585   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12586   unsigned long section_sym_count;
12587   struct elf_gc_sweep_symbol_info sweep_info;
12588
12589   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12590     {
12591       asection *o;
12592
12593       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12594           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12595         continue;
12596
12597       for (o = sub->sections; o != NULL; o = o->next)
12598         {
12599           /* When any section in a section group is kept, we keep all
12600              sections in the section group.  If the first member of
12601              the section group is excluded, we will also exclude the
12602              group section.  */
12603           if (o->flags & SEC_GROUP)
12604             {
12605               asection *first = elf_next_in_group (o);
12606               o->gc_mark = first->gc_mark;
12607             }
12608
12609           if (o->gc_mark)
12610             continue;
12611
12612           /* Skip sweeping sections already excluded.  */
12613           if (o->flags & SEC_EXCLUDE)
12614             continue;
12615
12616           /* Since this is early in the link process, it is simple
12617              to remove a section from the output.  */
12618           o->flags |= SEC_EXCLUDE;
12619
12620           if (info->print_gc_sections && o->size != 0)
12621             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12622
12623           /* But we also have to update some of the relocation
12624              info we collected before.  */
12625           if (gc_sweep_hook
12626               && (o->flags & SEC_RELOC) != 0
12627               && o->reloc_count != 0
12628               && !((info->strip == strip_all || info->strip == strip_debugger)
12629                    && (o->flags & SEC_DEBUGGING) != 0)
12630               && !bfd_is_abs_section (o->output_section))
12631             {
12632               Elf_Internal_Rela *internal_relocs;
12633               bfd_boolean r;
12634
12635               internal_relocs
12636                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12637                                              info->keep_memory);
12638               if (internal_relocs == NULL)
12639                 return FALSE;
12640
12641               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12642
12643               if (elf_section_data (o)->relocs != internal_relocs)
12644                 free (internal_relocs);
12645
12646               if (!r)
12647                 return FALSE;
12648             }
12649         }
12650     }
12651
12652   /* Remove the symbols that were in the swept sections from the dynamic
12653      symbol table.  GCFIXME: Anyone know how to get them out of the
12654      static symbol table as well?  */
12655   sweep_info.info = info;
12656   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12657   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12658                           &sweep_info);
12659
12660   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12661   return TRUE;
12662 }
12663
12664 /* Propagate collected vtable information.  This is called through
12665    elf_link_hash_traverse.  */
12666
12667 static bfd_boolean
12668 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12669 {
12670   /* Those that are not vtables.  */
12671   if (h->vtable == NULL || h->vtable->parent == NULL)
12672     return TRUE;
12673
12674   /* Those vtables that do not have parents, we cannot merge.  */
12675   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12676     return TRUE;
12677
12678   /* If we've already been done, exit.  */
12679   if (h->vtable->used && h->vtable->used[-1])
12680     return TRUE;
12681
12682   /* Make sure the parent's table is up to date.  */
12683   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12684
12685   if (h->vtable->used == NULL)
12686     {
12687       /* None of this table's entries were referenced.  Re-use the
12688          parent's table.  */
12689       h->vtable->used = h->vtable->parent->vtable->used;
12690       h->vtable->size = h->vtable->parent->vtable->size;
12691     }
12692   else
12693     {
12694       size_t n;
12695       bfd_boolean *cu, *pu;
12696
12697       /* Or the parent's entries into ours.  */
12698       cu = h->vtable->used;
12699       cu[-1] = TRUE;
12700       pu = h->vtable->parent->vtable->used;
12701       if (pu != NULL)
12702         {
12703           const struct elf_backend_data *bed;
12704           unsigned int log_file_align;
12705
12706           bed = get_elf_backend_data (h->root.u.def.section->owner);
12707           log_file_align = bed->s->log_file_align;
12708           n = h->vtable->parent->vtable->size >> log_file_align;
12709           while (n--)
12710             {
12711               if (*pu)
12712                 *cu = TRUE;
12713               pu++;
12714               cu++;
12715             }
12716         }
12717     }
12718
12719   return TRUE;
12720 }
12721
12722 static bfd_boolean
12723 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12724 {
12725   asection *sec;
12726   bfd_vma hstart, hend;
12727   Elf_Internal_Rela *relstart, *relend, *rel;
12728   const struct elf_backend_data *bed;
12729   unsigned int log_file_align;
12730
12731   /* Take care of both those symbols that do not describe vtables as
12732      well as those that are not loaded.  */
12733   if (h->vtable == NULL || h->vtable->parent == NULL)
12734     return TRUE;
12735
12736   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12737               || h->root.type == bfd_link_hash_defweak);
12738
12739   sec = h->root.u.def.section;
12740   hstart = h->root.u.def.value;
12741   hend = hstart + h->size;
12742
12743   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12744   if (!relstart)
12745     return *(bfd_boolean *) okp = FALSE;
12746   bed = get_elf_backend_data (sec->owner);
12747   log_file_align = bed->s->log_file_align;
12748
12749   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12750
12751   for (rel = relstart; rel < relend; ++rel)
12752     if (rel->r_offset >= hstart && rel->r_offset < hend)
12753       {
12754         /* If the entry is in use, do nothing.  */
12755         if (h->vtable->used
12756             && (rel->r_offset - hstart) < h->vtable->size)
12757           {
12758             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12759             if (h->vtable->used[entry])
12760               continue;
12761           }
12762         /* Otherwise, kill it.  */
12763         rel->r_offset = rel->r_info = rel->r_addend = 0;
12764       }
12765
12766   return TRUE;
12767 }
12768
12769 /* Mark sections containing dynamically referenced symbols.  When
12770    building shared libraries, we must assume that any visible symbol is
12771    referenced.  */
12772
12773 bfd_boolean
12774 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12775 {
12776   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12777   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12778
12779   if ((h->root.type == bfd_link_hash_defined
12780        || h->root.type == bfd_link_hash_defweak)
12781       && (h->ref_dynamic
12782           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12783               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12784               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12785               && (!bfd_link_executable (info)
12786                   || info->export_dynamic
12787                   || (h->dynamic
12788                       && d != NULL
12789                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12790               && (h->versioned >= versioned
12791                   || !bfd_hide_sym_by_version (info->version_info,
12792                                                h->root.root.string)))))
12793     h->root.u.def.section->flags |= SEC_KEEP;
12794
12795   return TRUE;
12796 }
12797
12798 /* Keep all sections containing symbols undefined on the command-line,
12799    and the section containing the entry symbol.  */
12800
12801 void
12802 _bfd_elf_gc_keep (struct bfd_link_info *info)
12803 {
12804   struct bfd_sym_chain *sym;
12805
12806   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12807     {
12808       struct elf_link_hash_entry *h;
12809
12810       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12811                                 FALSE, FALSE, FALSE);
12812
12813       if (h != NULL
12814           && (h->root.type == bfd_link_hash_defined
12815               || h->root.type == bfd_link_hash_defweak)
12816           && !bfd_is_abs_section (h->root.u.def.section))
12817         h->root.u.def.section->flags |= SEC_KEEP;
12818     }
12819 }
12820
12821 bfd_boolean
12822 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
12823                                 struct bfd_link_info *info)
12824 {
12825   bfd *ibfd = info->input_bfds;
12826
12827   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12828     {
12829       asection *sec;
12830       struct elf_reloc_cookie cookie;
12831
12832       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12833         continue;
12834
12835       if (!init_reloc_cookie (&cookie, info, ibfd))
12836         return FALSE;
12837
12838       for (sec = ibfd->sections; sec; sec = sec->next)
12839         {
12840           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
12841               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
12842             {
12843               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
12844               fini_reloc_cookie_rels (&cookie, sec);
12845             }
12846         }
12847     }
12848   return TRUE;
12849 }
12850
12851 /* Do mark and sweep of unused sections.  */
12852
12853 bfd_boolean
12854 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12855 {
12856   bfd_boolean ok = TRUE;
12857   bfd *sub;
12858   elf_gc_mark_hook_fn gc_mark_hook;
12859   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12860   struct elf_link_hash_table *htab;
12861
12862   if (!bed->can_gc_sections
12863       || !is_elf_hash_table (info->hash))
12864     {
12865       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12866       return TRUE;
12867     }
12868
12869   bed->gc_keep (info);
12870   htab = elf_hash_table (info);
12871
12872   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12873      at the .eh_frame section if we can mark the FDEs individually.  */
12874   for (sub = info->input_bfds;
12875        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
12876        sub = sub->link.next)
12877     {
12878       asection *sec;
12879       struct elf_reloc_cookie cookie;
12880
12881       sec = bfd_get_section_by_name (sub, ".eh_frame");
12882       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12883         {
12884           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12885           if (elf_section_data (sec)->sec_info
12886               && (sec->flags & SEC_LINKER_CREATED) == 0)
12887             elf_eh_frame_section (sub) = sec;
12888           fini_reloc_cookie_for_section (&cookie, sec);
12889           sec = bfd_get_next_section_by_name (NULL, sec);
12890         }
12891     }
12892
12893   /* Apply transitive closure to the vtable entry usage info.  */
12894   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12895   if (!ok)
12896     return FALSE;
12897
12898   /* Kill the vtable relocations that were not used.  */
12899   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12900   if (!ok)
12901     return FALSE;
12902
12903   /* Mark dynamically referenced symbols.  */
12904   if (htab->dynamic_sections_created)
12905     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12906
12907   /* Grovel through relocs to find out who stays ...  */
12908   gc_mark_hook = bed->gc_mark_hook;
12909   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12910     {
12911       asection *o;
12912
12913       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12914           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12915         continue;
12916
12917       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12918          Also treat note sections as a root, if the section is not part
12919          of a group.  */
12920       for (o = sub->sections; o != NULL; o = o->next)
12921         if (!o->gc_mark
12922             && (o->flags & SEC_EXCLUDE) == 0
12923             && ((o->flags & SEC_KEEP) != 0
12924                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12925                     && elf_next_in_group (o) == NULL )))
12926           {
12927             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12928               return FALSE;
12929           }
12930     }
12931
12932   /* Allow the backend to mark additional target specific sections.  */
12933   bed->gc_mark_extra_sections (info, gc_mark_hook);
12934
12935   /* ... and mark SEC_EXCLUDE for those that go.  */
12936   return elf_gc_sweep (abfd, info);
12937 }
12938 \f
12939 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12940
12941 bfd_boolean
12942 bfd_elf_gc_record_vtinherit (bfd *abfd,
12943                              asection *sec,
12944                              struct elf_link_hash_entry *h,
12945                              bfd_vma offset)
12946 {
12947   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12948   struct elf_link_hash_entry **search, *child;
12949   bfd_size_type extsymcount;
12950   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12951
12952   /* The sh_info field of the symtab header tells us where the
12953      external symbols start.  We don't care about the local symbols at
12954      this point.  */
12955   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12956   if (!elf_bad_symtab (abfd))
12957     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12958
12959   sym_hashes = elf_sym_hashes (abfd);
12960   sym_hashes_end = sym_hashes + extsymcount;
12961
12962   /* Hunt down the child symbol, which is in this section at the same
12963      offset as the relocation.  */
12964   for (search = sym_hashes; search != sym_hashes_end; ++search)
12965     {
12966       if ((child = *search) != NULL
12967           && (child->root.type == bfd_link_hash_defined
12968               || child->root.type == bfd_link_hash_defweak)
12969           && child->root.u.def.section == sec
12970           && child->root.u.def.value == offset)
12971         goto win;
12972     }
12973
12974   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12975                          abfd, sec, (unsigned long) offset);
12976   bfd_set_error (bfd_error_invalid_operation);
12977   return FALSE;
12978
12979  win:
12980   if (!child->vtable)
12981     {
12982       child->vtable = ((struct elf_link_virtual_table_entry *)
12983                        bfd_zalloc (abfd, sizeof (*child->vtable)));
12984       if (!child->vtable)
12985         return FALSE;
12986     }
12987   if (!h)
12988     {
12989       /* This *should* only be the absolute section.  It could potentially
12990          be that someone has defined a non-global vtable though, which
12991          would be bad.  It isn't worth paging in the local symbols to be
12992          sure though; that case should simply be handled by the assembler.  */
12993
12994       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12995     }
12996   else
12997     child->vtable->parent = h;
12998
12999   return TRUE;
13000 }
13001
13002 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13003
13004 bfd_boolean
13005 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13006                            asection *sec ATTRIBUTE_UNUSED,
13007                            struct elf_link_hash_entry *h,
13008                            bfd_vma addend)
13009 {
13010   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13011   unsigned int log_file_align = bed->s->log_file_align;
13012
13013   if (!h->vtable)
13014     {
13015       h->vtable = ((struct elf_link_virtual_table_entry *)
13016                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13017       if (!h->vtable)
13018         return FALSE;
13019     }
13020
13021   if (addend >= h->vtable->size)
13022     {
13023       size_t size, bytes, file_align;
13024       bfd_boolean *ptr = h->vtable->used;
13025
13026       /* While the symbol is undefined, we have to be prepared to handle
13027          a zero size.  */
13028       file_align = 1 << log_file_align;
13029       if (h->root.type == bfd_link_hash_undefined)
13030         size = addend + file_align;
13031       else
13032         {
13033           size = h->size;
13034           if (addend >= size)
13035             {
13036               /* Oops!  We've got a reference past the defined end of
13037                  the table.  This is probably a bug -- shall we warn?  */
13038               size = addend + file_align;
13039             }
13040         }
13041       size = (size + file_align - 1) & -file_align;
13042
13043       /* Allocate one extra entry for use as a "done" flag for the
13044          consolidation pass.  */
13045       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13046
13047       if (ptr)
13048         {
13049           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13050
13051           if (ptr != NULL)
13052             {
13053               size_t oldbytes;
13054
13055               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13056                           * sizeof (bfd_boolean));
13057               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13058             }
13059         }
13060       else
13061         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13062
13063       if (ptr == NULL)
13064         return FALSE;
13065
13066       /* And arrange for that done flag to be at index -1.  */
13067       h->vtable->used = ptr + 1;
13068       h->vtable->size = size;
13069     }
13070
13071   h->vtable->used[addend >> log_file_align] = TRUE;
13072
13073   return TRUE;
13074 }
13075
13076 /* Map an ELF section header flag to its corresponding string.  */
13077 typedef struct
13078 {
13079   char *flag_name;
13080   flagword flag_value;
13081 } elf_flags_to_name_table;
13082
13083 static elf_flags_to_name_table elf_flags_to_names [] =
13084 {
13085   { "SHF_WRITE", SHF_WRITE },
13086   { "SHF_ALLOC", SHF_ALLOC },
13087   { "SHF_EXECINSTR", SHF_EXECINSTR },
13088   { "SHF_MERGE", SHF_MERGE },
13089   { "SHF_STRINGS", SHF_STRINGS },
13090   { "SHF_INFO_LINK", SHF_INFO_LINK},
13091   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13092   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13093   { "SHF_GROUP", SHF_GROUP },
13094   { "SHF_TLS", SHF_TLS },
13095   { "SHF_MASKOS", SHF_MASKOS },
13096   { "SHF_EXCLUDE", SHF_EXCLUDE },
13097 };
13098
13099 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13100 bfd_boolean
13101 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13102                               struct flag_info *flaginfo,
13103                               asection *section)
13104 {
13105   const bfd_vma sh_flags = elf_section_flags (section);
13106
13107   if (!flaginfo->flags_initialized)
13108     {
13109       bfd *obfd = info->output_bfd;
13110       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13111       struct flag_info_list *tf = flaginfo->flag_list;
13112       int with_hex = 0;
13113       int without_hex = 0;
13114
13115       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13116         {
13117           unsigned i;
13118           flagword (*lookup) (char *);
13119
13120           lookup = bed->elf_backend_lookup_section_flags_hook;
13121           if (lookup != NULL)
13122             {
13123               flagword hexval = (*lookup) ((char *) tf->name);
13124
13125               if (hexval != 0)
13126                 {
13127                   if (tf->with == with_flags)
13128                     with_hex |= hexval;
13129                   else if (tf->with == without_flags)
13130                     without_hex |= hexval;
13131                   tf->valid = TRUE;
13132                   continue;
13133                 }
13134             }
13135           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13136             {
13137               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13138                 {
13139                   if (tf->with == with_flags)
13140                     with_hex |= elf_flags_to_names[i].flag_value;
13141                   else if (tf->with == without_flags)
13142                     without_hex |= elf_flags_to_names[i].flag_value;
13143                   tf->valid = TRUE;
13144                   break;
13145                 }
13146             }
13147           if (!tf->valid)
13148             {
13149               info->callbacks->einfo
13150                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13151               return FALSE;
13152             }
13153         }
13154       flaginfo->flags_initialized = TRUE;
13155       flaginfo->only_with_flags |= with_hex;
13156       flaginfo->not_with_flags |= without_hex;
13157     }
13158
13159   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13160     return FALSE;
13161
13162   if ((flaginfo->not_with_flags & sh_flags) != 0)
13163     return FALSE;
13164
13165   return TRUE;
13166 }
13167
13168 struct alloc_got_off_arg {
13169   bfd_vma gotoff;
13170   struct bfd_link_info *info;
13171 };
13172
13173 /* We need a special top-level link routine to convert got reference counts
13174    to real got offsets.  */
13175
13176 static bfd_boolean
13177 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13178 {
13179   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13180   bfd *obfd = gofarg->info->output_bfd;
13181   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13182
13183   if (h->got.refcount > 0)
13184     {
13185       h->got.offset = gofarg->gotoff;
13186       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13187     }
13188   else
13189     h->got.offset = (bfd_vma) -1;
13190
13191   return TRUE;
13192 }
13193
13194 /* And an accompanying bit to work out final got entry offsets once
13195    we're done.  Should be called from final_link.  */
13196
13197 bfd_boolean
13198 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13199                                         struct bfd_link_info *info)
13200 {
13201   bfd *i;
13202   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13203   bfd_vma gotoff;
13204   struct alloc_got_off_arg gofarg;
13205
13206   BFD_ASSERT (abfd == info->output_bfd);
13207
13208   if (! is_elf_hash_table (info->hash))
13209     return FALSE;
13210
13211   /* The GOT offset is relative to the .got section, but the GOT header is
13212      put into the .got.plt section, if the backend uses it.  */
13213   if (bed->want_got_plt)
13214     gotoff = 0;
13215   else
13216     gotoff = bed->got_header_size;
13217
13218   /* Do the local .got entries first.  */
13219   for (i = info->input_bfds; i; i = i->link.next)
13220     {
13221       bfd_signed_vma *local_got;
13222       bfd_size_type j, locsymcount;
13223       Elf_Internal_Shdr *symtab_hdr;
13224
13225       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13226         continue;
13227
13228       local_got = elf_local_got_refcounts (i);
13229       if (!local_got)
13230         continue;
13231
13232       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13233       if (elf_bad_symtab (i))
13234         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13235       else
13236         locsymcount = symtab_hdr->sh_info;
13237
13238       for (j = 0; j < locsymcount; ++j)
13239         {
13240           if (local_got[j] > 0)
13241             {
13242               local_got[j] = gotoff;
13243               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13244             }
13245           else
13246             local_got[j] = (bfd_vma) -1;
13247         }
13248     }
13249
13250   /* Then the global .got entries.  .plt refcounts are handled by
13251      adjust_dynamic_symbol  */
13252   gofarg.gotoff = gotoff;
13253   gofarg.info = info;
13254   elf_link_hash_traverse (elf_hash_table (info),
13255                           elf_gc_allocate_got_offsets,
13256                           &gofarg);
13257   return TRUE;
13258 }
13259
13260 /* Many folk need no more in the way of final link than this, once
13261    got entry reference counting is enabled.  */
13262
13263 bfd_boolean
13264 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13265 {
13266   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13267     return FALSE;
13268
13269   /* Invoke the regular ELF backend linker to do all the work.  */
13270   return bfd_elf_final_link (abfd, info);
13271 }
13272
13273 bfd_boolean
13274 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13275 {
13276   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13277
13278   if (rcookie->bad_symtab)
13279     rcookie->rel = rcookie->rels;
13280
13281   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13282     {
13283       unsigned long r_symndx;
13284
13285       if (! rcookie->bad_symtab)
13286         if (rcookie->rel->r_offset > offset)
13287           return FALSE;
13288       if (rcookie->rel->r_offset != offset)
13289         continue;
13290
13291       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13292       if (r_symndx == STN_UNDEF)
13293         return TRUE;
13294
13295       if (r_symndx >= rcookie->locsymcount
13296           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13297         {
13298           struct elf_link_hash_entry *h;
13299
13300           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13301
13302           while (h->root.type == bfd_link_hash_indirect
13303                  || h->root.type == bfd_link_hash_warning)
13304             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13305
13306           if ((h->root.type == bfd_link_hash_defined
13307                || h->root.type == bfd_link_hash_defweak)
13308               && (h->root.u.def.section->owner != rcookie->abfd
13309                   || h->root.u.def.section->kept_section != NULL
13310                   || discarded_section (h->root.u.def.section)))
13311             return TRUE;
13312         }
13313       else
13314         {
13315           /* It's not a relocation against a global symbol,
13316              but it could be a relocation against a local
13317              symbol for a discarded section.  */
13318           asection *isec;
13319           Elf_Internal_Sym *isym;
13320
13321           /* Need to: get the symbol; get the section.  */
13322           isym = &rcookie->locsyms[r_symndx];
13323           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13324           if (isec != NULL
13325               && (isec->kept_section != NULL
13326                   || discarded_section (isec)))
13327             return TRUE;
13328         }
13329       return FALSE;
13330     }
13331   return FALSE;
13332 }
13333
13334 /* Discard unneeded references to discarded sections.
13335    Returns -1 on error, 1 if any section's size was changed, 0 if
13336    nothing changed.  This function assumes that the relocations are in
13337    sorted order, which is true for all known assemblers.  */
13338
13339 int
13340 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13341 {
13342   struct elf_reloc_cookie cookie;
13343   asection *o;
13344   bfd *abfd;
13345   int changed = 0;
13346
13347   if (info->traditional_format
13348       || !is_elf_hash_table (info->hash))
13349     return 0;
13350
13351   o = bfd_get_section_by_name (output_bfd, ".stab");
13352   if (o != NULL)
13353     {
13354       asection *i;
13355
13356       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13357         {
13358           if (i->size == 0
13359               || i->reloc_count == 0
13360               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13361             continue;
13362
13363           abfd = i->owner;
13364           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13365             continue;
13366
13367           if (!init_reloc_cookie_for_section (&cookie, info, i))
13368             return -1;
13369
13370           if (_bfd_discard_section_stabs (abfd, i,
13371                                           elf_section_data (i)->sec_info,
13372                                           bfd_elf_reloc_symbol_deleted_p,
13373                                           &cookie))
13374             changed = 1;
13375
13376           fini_reloc_cookie_for_section (&cookie, i);
13377         }
13378     }
13379
13380   o = NULL;
13381   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13382     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13383   if (o != NULL)
13384     {
13385       asection *i;
13386
13387       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13388         {
13389           if (i->size == 0)
13390             continue;
13391
13392           abfd = i->owner;
13393           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13394             continue;
13395
13396           if (!init_reloc_cookie_for_section (&cookie, info, i))
13397             return -1;
13398
13399           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13400           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13401                                                  bfd_elf_reloc_symbol_deleted_p,
13402                                                  &cookie))
13403             changed = 1;
13404
13405           fini_reloc_cookie_for_section (&cookie, i);
13406         }
13407     }
13408
13409   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13410     {
13411       const struct elf_backend_data *bed;
13412
13413       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13414         continue;
13415
13416       bed = get_elf_backend_data (abfd);
13417
13418       if (bed->elf_backend_discard_info != NULL)
13419         {
13420           if (!init_reloc_cookie (&cookie, info, abfd))
13421             return -1;
13422
13423           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13424             changed = 1;
13425
13426           fini_reloc_cookie (&cookie, abfd);
13427         }
13428     }
13429
13430   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13431     _bfd_elf_end_eh_frame_parsing (info);
13432
13433   if (info->eh_frame_hdr_type
13434       && !bfd_link_relocatable (info)
13435       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13436     changed = 1;
13437
13438   return changed;
13439 }
13440
13441 bfd_boolean
13442 _bfd_elf_section_already_linked (bfd *abfd,
13443                                  asection *sec,
13444                                  struct bfd_link_info *info)
13445 {
13446   flagword flags;
13447   const char *name, *key;
13448   struct bfd_section_already_linked *l;
13449   struct bfd_section_already_linked_hash_entry *already_linked_list;
13450
13451   if (sec->output_section == bfd_abs_section_ptr)
13452     return FALSE;
13453
13454   flags = sec->flags;
13455
13456   /* Return if it isn't a linkonce section.  A comdat group section
13457      also has SEC_LINK_ONCE set.  */
13458   if ((flags & SEC_LINK_ONCE) == 0)
13459     return FALSE;
13460
13461   /* Don't put group member sections on our list of already linked
13462      sections.  They are handled as a group via their group section.  */
13463   if (elf_sec_group (sec) != NULL)
13464     return FALSE;
13465
13466   /* For a SHT_GROUP section, use the group signature as the key.  */
13467   name = sec->name;
13468   if ((flags & SEC_GROUP) != 0
13469       && elf_next_in_group (sec) != NULL
13470       && elf_group_name (elf_next_in_group (sec)) != NULL)
13471     key = elf_group_name (elf_next_in_group (sec));
13472   else
13473     {
13474       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13475       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13476           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13477         key++;
13478       else
13479         /* Must be a user linkonce section that doesn't follow gcc's
13480            naming convention.  In this case we won't be matching
13481            single member groups.  */
13482         key = name;
13483     }
13484
13485   already_linked_list = bfd_section_already_linked_table_lookup (key);
13486
13487   for (l = already_linked_list->entry; l != NULL; l = l->next)
13488     {
13489       /* We may have 2 different types of sections on the list: group
13490          sections with a signature of <key> (<key> is some string),
13491          and linkonce sections named .gnu.linkonce.<type>.<key>.
13492          Match like sections.  LTO plugin sections are an exception.
13493          They are always named .gnu.linkonce.t.<key> and match either
13494          type of section.  */
13495       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13496            && ((flags & SEC_GROUP) != 0
13497                || strcmp (name, l->sec->name) == 0))
13498           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13499         {
13500           /* The section has already been linked.  See if we should
13501              issue a warning.  */
13502           if (!_bfd_handle_already_linked (sec, l, info))
13503             return FALSE;
13504
13505           if (flags & SEC_GROUP)
13506             {
13507               asection *first = elf_next_in_group (sec);
13508               asection *s = first;
13509
13510               while (s != NULL)
13511                 {
13512                   s->output_section = bfd_abs_section_ptr;
13513                   /* Record which group discards it.  */
13514                   s->kept_section = l->sec;
13515                   s = elf_next_in_group (s);
13516                   /* These lists are circular.  */
13517                   if (s == first)
13518                     break;
13519                 }
13520             }
13521
13522           return TRUE;
13523         }
13524     }
13525
13526   /* A single member comdat group section may be discarded by a
13527      linkonce section and vice versa.  */
13528   if ((flags & SEC_GROUP) != 0)
13529     {
13530       asection *first = elf_next_in_group (sec);
13531
13532       if (first != NULL && elf_next_in_group (first) == first)
13533         /* Check this single member group against linkonce sections.  */
13534         for (l = already_linked_list->entry; l != NULL; l = l->next)
13535           if ((l->sec->flags & SEC_GROUP) == 0
13536               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13537             {
13538               first->output_section = bfd_abs_section_ptr;
13539               first->kept_section = l->sec;
13540               sec->output_section = bfd_abs_section_ptr;
13541               break;
13542             }
13543     }
13544   else
13545     /* Check this linkonce section against single member groups.  */
13546     for (l = already_linked_list->entry; l != NULL; l = l->next)
13547       if (l->sec->flags & SEC_GROUP)
13548         {
13549           asection *first = elf_next_in_group (l->sec);
13550
13551           if (first != NULL
13552               && elf_next_in_group (first) == first
13553               && bfd_elf_match_symbols_in_sections (first, sec, info))
13554             {
13555               sec->output_section = bfd_abs_section_ptr;
13556               sec->kept_section = first;
13557               break;
13558             }
13559         }
13560
13561   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13562      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13563      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13564      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13565      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13566      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13567      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13568      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13569      The reverse order cannot happen as there is never a bfd with only the
13570      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13571      matter as here were are looking only for cross-bfd sections.  */
13572
13573   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13574     for (l = already_linked_list->entry; l != NULL; l = l->next)
13575       if ((l->sec->flags & SEC_GROUP) == 0
13576           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13577         {
13578           if (abfd != l->sec->owner)
13579             sec->output_section = bfd_abs_section_ptr;
13580           break;
13581         }
13582
13583   /* This is the first section with this name.  Record it.  */
13584   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13585     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13586   return sec->output_section == bfd_abs_section_ptr;
13587 }
13588
13589 bfd_boolean
13590 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13591 {
13592   return sym->st_shndx == SHN_COMMON;
13593 }
13594
13595 unsigned int
13596 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13597 {
13598   return SHN_COMMON;
13599 }
13600
13601 asection *
13602 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13603 {
13604   return bfd_com_section_ptr;
13605 }
13606
13607 bfd_vma
13608 _bfd_elf_default_got_elt_size (bfd *abfd,
13609                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13610                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13611                                bfd *ibfd ATTRIBUTE_UNUSED,
13612                                unsigned long symndx ATTRIBUTE_UNUSED)
13613 {
13614   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13615   return bed->s->arch_size / 8;
13616 }
13617
13618 /* Routines to support the creation of dynamic relocs.  */
13619
13620 /* Returns the name of the dynamic reloc section associated with SEC.  */
13621
13622 static const char *
13623 get_dynamic_reloc_section_name (bfd *       abfd,
13624                                 asection *  sec,
13625                                 bfd_boolean is_rela)
13626 {
13627   char *name;
13628   const char *old_name = bfd_get_section_name (NULL, sec);
13629   const char *prefix = is_rela ? ".rela" : ".rel";
13630
13631   if (old_name == NULL)
13632     return NULL;
13633
13634   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13635   sprintf (name, "%s%s", prefix, old_name);
13636
13637   return name;
13638 }
13639
13640 /* Returns the dynamic reloc section associated with SEC.
13641    If necessary compute the name of the dynamic reloc section based
13642    on SEC's name (looked up in ABFD's string table) and the setting
13643    of IS_RELA.  */
13644
13645 asection *
13646 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13647                                     asection *  sec,
13648                                     bfd_boolean is_rela)
13649 {
13650   asection * reloc_sec = elf_section_data (sec)->sreloc;
13651
13652   if (reloc_sec == NULL)
13653     {
13654       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13655
13656       if (name != NULL)
13657         {
13658           reloc_sec = bfd_get_linker_section (abfd, name);
13659
13660           if (reloc_sec != NULL)
13661             elf_section_data (sec)->sreloc = reloc_sec;
13662         }
13663     }
13664
13665   return reloc_sec;
13666 }
13667
13668 /* Returns the dynamic reloc section associated with SEC.  If the
13669    section does not exist it is created and attached to the DYNOBJ
13670    bfd and stored in the SRELOC field of SEC's elf_section_data
13671    structure.
13672
13673    ALIGNMENT is the alignment for the newly created section and
13674    IS_RELA defines whether the name should be .rela.<SEC's name>
13675    or .rel.<SEC's name>.  The section name is looked up in the
13676    string table associated with ABFD.  */
13677
13678 asection *
13679 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13680                                      bfd *dynobj,
13681                                      unsigned int alignment,
13682                                      bfd *abfd,
13683                                      bfd_boolean is_rela)
13684 {
13685   asection * reloc_sec = elf_section_data (sec)->sreloc;
13686
13687   if (reloc_sec == NULL)
13688     {
13689       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13690
13691       if (name == NULL)
13692         return NULL;
13693
13694       reloc_sec = bfd_get_linker_section (dynobj, name);
13695
13696       if (reloc_sec == NULL)
13697         {
13698           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13699                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13700           if ((sec->flags & SEC_ALLOC) != 0)
13701             flags |= SEC_ALLOC | SEC_LOAD;
13702
13703           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13704           if (reloc_sec != NULL)
13705             {
13706               /* _bfd_elf_get_sec_type_attr chooses a section type by
13707                  name.  Override as it may be wrong, eg. for a user
13708                  section named "auto" we'll get ".relauto" which is
13709                  seen to be a .rela section.  */
13710               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13711               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13712                 reloc_sec = NULL;
13713             }
13714         }
13715
13716       elf_section_data (sec)->sreloc = reloc_sec;
13717     }
13718
13719   return reloc_sec;
13720 }
13721
13722 /* Copy the ELF symbol type and other attributes for a linker script
13723    assignment from HSRC to HDEST.  Generally this should be treated as
13724    if we found a strong non-dynamic definition for HDEST (except that
13725    ld ignores multiple definition errors).  */
13726 void
13727 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13728                                      struct bfd_link_hash_entry *hdest,
13729                                      struct bfd_link_hash_entry *hsrc)
13730 {
13731   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13732   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13733   Elf_Internal_Sym isym;
13734
13735   ehdest->type = ehsrc->type;
13736   ehdest->target_internal = ehsrc->target_internal;
13737
13738   isym.st_other = ehsrc->other;
13739   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13740 }
13741
13742 /* Append a RELA relocation REL to section S in BFD.  */
13743
13744 void
13745 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13746 {
13747   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13748   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13749   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13750   bed->s->swap_reloca_out (abfd, rel, loc);
13751 }
13752
13753 /* Append a REL relocation REL to section S in BFD.  */
13754
13755 void
13756 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13757 {
13758   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13759   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13760   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13761   bed->s->swap_reloc_out (abfd, rel, loc);
13762 }