Add c-format tags to translatable strings with more than one argument-using formattin...
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2016 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31 #if BFD_SUPPORTS_PLUGINS
32 #include "plugin-api.h"
33 #include "plugin.h"
34 #endif
35
36 /* This struct is used to pass information to routines called via
37    elf_link_hash_traverse which must return failure.  */
38
39 struct elf_info_failed
40 {
41   struct bfd_link_info *info;
42   bfd_boolean failed;
43 };
44
45 /* This structure is used to pass information to
46    _bfd_elf_link_find_version_dependencies.  */
47
48 struct elf_find_verdep_info
49 {
50   /* General link information.  */
51   struct bfd_link_info *info;
52   /* The number of dependencies.  */
53   unsigned int vers;
54   /* Whether we had a failure.  */
55   bfd_boolean failed;
56 };
57
58 static bfd_boolean _bfd_elf_fix_symbol_flags
59   (struct elf_link_hash_entry *, struct elf_info_failed *);
60
61 asection *
62 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
63                              unsigned long r_symndx,
64                              bfd_boolean discard)
65 {
66   if (r_symndx >= cookie->locsymcount
67       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
68     {
69       struct elf_link_hash_entry *h;
70
71       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
72
73       while (h->root.type == bfd_link_hash_indirect
74              || h->root.type == bfd_link_hash_warning)
75         h = (struct elf_link_hash_entry *) h->root.u.i.link;
76
77       if ((h->root.type == bfd_link_hash_defined
78            || h->root.type == bfd_link_hash_defweak)
79            && discarded_section (h->root.u.def.section))
80         return h->root.u.def.section;
81       else
82         return NULL;
83     }
84   else
85     {
86       /* It's not a relocation against a global symbol,
87          but it could be a relocation against a local
88          symbol for a discarded section.  */
89       asection *isec;
90       Elf_Internal_Sym *isym;
91
92       /* Need to: get the symbol; get the section.  */
93       isym = &cookie->locsyms[r_symndx];
94       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
95       if (isec != NULL
96           && discard ? discarded_section (isec) : 1)
97         return isec;
98      }
99   return NULL;
100 }
101
102 /* Define a symbol in a dynamic linkage section.  */
103
104 struct elf_link_hash_entry *
105 _bfd_elf_define_linkage_sym (bfd *abfd,
106                              struct bfd_link_info *info,
107                              asection *sec,
108                              const char *name)
109 {
110   struct elf_link_hash_entry *h;
111   struct bfd_link_hash_entry *bh;
112   const struct elf_backend_data *bed;
113
114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
115   if (h != NULL)
116     {
117       /* Zap symbol defined in an as-needed lib that wasn't linked.
118          This is a symptom of a larger problem:  Absolute symbols
119          defined in shared libraries can't be overridden, because we
120          lose the link to the bfd which is via the symbol section.  */
121       h->root.type = bfd_link_hash_new;
122     }
123
124   bh = &h->root;
125   bed = get_elf_backend_data (abfd);
126   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
127                                          sec, 0, NULL, FALSE, bed->collect,
128                                          &bh))
129     return NULL;
130   h = (struct elf_link_hash_entry *) bh;
131   h->def_regular = 1;
132   h->non_elf = 0;
133   h->root.linker_def = 1;
134   h->type = STT_OBJECT;
135   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
136     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
137
138   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
139   return h;
140 }
141
142 bfd_boolean
143 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
144 {
145   flagword flags;
146   asection *s;
147   struct elf_link_hash_entry *h;
148   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
149   struct elf_link_hash_table *htab = elf_hash_table (info);
150
151   /* This function may be called more than once.  */
152   s = bfd_get_linker_section (abfd, ".got");
153   if (s != NULL)
154     return TRUE;
155
156   flags = bed->dynamic_sec_flags;
157
158   s = bfd_make_section_anyway_with_flags (abfd,
159                                           (bed->rela_plts_and_copies_p
160                                            ? ".rela.got" : ".rel.got"),
161                                           (bed->dynamic_sec_flags
162                                            | SEC_READONLY));
163   if (s == NULL
164       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
165     return FALSE;
166   htab->srelgot = s;
167
168   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
169   if (s == NULL
170       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
171     return FALSE;
172   htab->sgot = s;
173
174   if (bed->want_got_plt)
175     {
176       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
177       if (s == NULL
178           || !bfd_set_section_alignment (abfd, s,
179                                          bed->s->log_file_align))
180         return FALSE;
181       htab->sgotplt = s;
182     }
183
184   /* The first bit of the global offset table is the header.  */
185   s->size += bed->got_header_size;
186
187   if (bed->want_got_sym)
188     {
189       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
190          (or .got.plt) section.  We don't do this in the linker script
191          because we don't want to define the symbol if we are not creating
192          a global offset table.  */
193       h = _bfd_elf_define_linkage_sym (abfd, info, s,
194                                        "_GLOBAL_OFFSET_TABLE_");
195       elf_hash_table (info)->hgot = h;
196       if (h == NULL)
197         return FALSE;
198     }
199
200   return TRUE;
201 }
202 \f
203 /* Create a strtab to hold the dynamic symbol names.  */
204 static bfd_boolean
205 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
206 {
207   struct elf_link_hash_table *hash_table;
208
209   hash_table = elf_hash_table (info);
210   if (hash_table->dynobj == NULL)
211     {
212       /* We may not set dynobj, an input file holding linker created
213          dynamic sections to abfd, which may be a dynamic object with
214          its own dynamic sections.  We need to find a normal input file
215          to hold linker created sections if possible.  */
216       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
217         {
218           bfd *ibfd;
219           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
220             if ((ibfd->flags
221                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0)
222               {
223                 abfd = ibfd;
224                 break;
225               }
226         }
227       hash_table->dynobj = abfd;
228     }
229
230   if (hash_table->dynstr == NULL)
231     {
232       hash_table->dynstr = _bfd_elf_strtab_init ();
233       if (hash_table->dynstr == NULL)
234         return FALSE;
235     }
236   return TRUE;
237 }
238
239 /* Create some sections which will be filled in with dynamic linking
240    information.  ABFD is an input file which requires dynamic sections
241    to be created.  The dynamic sections take up virtual memory space
242    when the final executable is run, so we need to create them before
243    addresses are assigned to the output sections.  We work out the
244    actual contents and size of these sections later.  */
245
246 bfd_boolean
247 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
248 {
249   flagword flags;
250   asection *s;
251   const struct elf_backend_data *bed;
252   struct elf_link_hash_entry *h;
253
254   if (! is_elf_hash_table (info->hash))
255     return FALSE;
256
257   if (elf_hash_table (info)->dynamic_sections_created)
258     return TRUE;
259
260   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
261     return FALSE;
262
263   abfd = elf_hash_table (info)->dynobj;
264   bed = get_elf_backend_data (abfd);
265
266   flags = bed->dynamic_sec_flags;
267
268   /* A dynamically linked executable has a .interp section, but a
269      shared library does not.  */
270   if (bfd_link_executable (info) && !info->nointerp)
271     {
272       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
273                                               flags | SEC_READONLY);
274       if (s == NULL)
275         return FALSE;
276     }
277
278   /* Create sections to hold version informations.  These are removed
279      if they are not needed.  */
280   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
281                                           flags | SEC_READONLY);
282   if (s == NULL
283       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
284     return FALSE;
285
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, 1))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303   elf_hash_table (info)->dynsym = s;
304
305   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
306                                           flags | SEC_READONLY);
307   if (s == NULL)
308     return FALSE;
309
310   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
311   if (s == NULL
312       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
313     return FALSE;
314
315   /* The special symbol _DYNAMIC is always set to the start of the
316      .dynamic section.  We could set _DYNAMIC in a linker script, but we
317      only want to define it if we are, in fact, creating a .dynamic
318      section.  We don't want to define it if there is no .dynamic
319      section, since on some ELF platforms the start up code examines it
320      to decide how to initialize the process.  */
321   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
322   elf_hash_table (info)->hdynamic = h;
323   if (h == NULL)
324     return FALSE;
325
326   if (info->emit_hash)
327     {
328       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
329                                               flags | SEC_READONLY);
330       if (s == NULL
331           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
332         return FALSE;
333       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
334     }
335
336   if (info->emit_gnu_hash)
337     {
338       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
339                                               flags | SEC_READONLY);
340       if (s == NULL
341           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
342         return FALSE;
343       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
344          4 32-bit words followed by variable count of 64-bit words, then
345          variable count of 32-bit words.  */
346       if (bed->s->arch_size == 64)
347         elf_section_data (s)->this_hdr.sh_entsize = 0;
348       else
349         elf_section_data (s)->this_hdr.sh_entsize = 4;
350     }
351
352   /* Let the backend create the rest of the sections.  This lets the
353      backend set the right flags.  The backend will normally create
354      the .got and .plt sections.  */
355   if (bed->elf_backend_create_dynamic_sections == NULL
356       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
357     return FALSE;
358
359   elf_hash_table (info)->dynamic_sections_created = TRUE;
360
361   return TRUE;
362 }
363
364 /* Create dynamic sections when linking against a dynamic object.  */
365
366 bfd_boolean
367 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
368 {
369   flagword flags, pltflags;
370   struct elf_link_hash_entry *h;
371   asection *s;
372   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
373   struct elf_link_hash_table *htab = elf_hash_table (info);
374
375   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
376      .rel[a].bss sections.  */
377   flags = bed->dynamic_sec_flags;
378
379   pltflags = flags;
380   if (bed->plt_not_loaded)
381     /* We do not clear SEC_ALLOC here because we still want the OS to
382        allocate space for the section; it's just that there's nothing
383        to read in from the object file.  */
384     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
385   else
386     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
387   if (bed->plt_readonly)
388     pltflags |= SEC_READONLY;
389
390   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
391   if (s == NULL
392       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
393     return FALSE;
394   htab->splt = s;
395
396   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
397      .plt section.  */
398   if (bed->want_plt_sym)
399     {
400       h = _bfd_elf_define_linkage_sym (abfd, info, s,
401                                        "_PROCEDURE_LINKAGE_TABLE_");
402       elf_hash_table (info)->hplt = h;
403       if (h == NULL)
404         return FALSE;
405     }
406
407   s = bfd_make_section_anyway_with_flags (abfd,
408                                           (bed->rela_plts_and_copies_p
409                                            ? ".rela.plt" : ".rel.plt"),
410                                           flags | SEC_READONLY);
411   if (s == NULL
412       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
413     return FALSE;
414   htab->srelplt = s;
415
416   if (! _bfd_elf_create_got_section (abfd, info))
417     return FALSE;
418
419   if (bed->want_dynbss)
420     {
421       /* The .dynbss section is a place to put symbols which are defined
422          by dynamic objects, are referenced by regular objects, and are
423          not functions.  We must allocate space for them in the process
424          image and use a R_*_COPY reloc to tell the dynamic linker to
425          initialize them at run time.  The linker script puts the .dynbss
426          section into the .bss section of the final image.  */
427       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
428                                               (SEC_ALLOC | SEC_LINKER_CREATED));
429       if (s == NULL)
430         return FALSE;
431
432       /* The .rel[a].bss section holds copy relocs.  This section is not
433          normally needed.  We need to create it here, though, so that the
434          linker will map it to an output section.  We can't just create it
435          only if we need it, because we will not know whether we need it
436          until we have seen all the input files, and the first time the
437          main linker code calls BFD after examining all the input files
438          (size_dynamic_sections) the input sections have already been
439          mapped to the output sections.  If the section turns out not to
440          be needed, we can discard it later.  We will never need this
441          section when generating a shared object, since they do not use
442          copy relocs.  */
443       if (! bfd_link_pic (info))
444         {
445           s = bfd_make_section_anyway_with_flags (abfd,
446                                                   (bed->rela_plts_and_copies_p
447                                                    ? ".rela.bss" : ".rel.bss"),
448                                                   flags | SEC_READONLY);
449           if (s == NULL
450               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
451             return FALSE;
452         }
453     }
454
455   return TRUE;
456 }
457 \f
458 /* Record a new dynamic symbol.  We record the dynamic symbols as we
459    read the input files, since we need to have a list of all of them
460    before we can determine the final sizes of the output sections.
461    Note that we may actually call this function even though we are not
462    going to output any dynamic symbols; in some cases we know that a
463    symbol should be in the dynamic symbol table, but only if there is
464    one.  */
465
466 bfd_boolean
467 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
468                                     struct elf_link_hash_entry *h)
469 {
470   if (h->dynindx == -1)
471     {
472       struct elf_strtab_hash *dynstr;
473       char *p;
474       const char *name;
475       size_t indx;
476
477       /* XXX: The ABI draft says the linker must turn hidden and
478          internal symbols into STB_LOCAL symbols when producing the
479          DSO. However, if ld.so honors st_other in the dynamic table,
480          this would not be necessary.  */
481       switch (ELF_ST_VISIBILITY (h->other))
482         {
483         case STV_INTERNAL:
484         case STV_HIDDEN:
485           if (h->root.type != bfd_link_hash_undefined
486               && h->root.type != bfd_link_hash_undefweak)
487             {
488               h->forced_local = 1;
489               if (!elf_hash_table (info)->is_relocatable_executable)
490                 return TRUE;
491             }
492
493         default:
494           break;
495         }
496
497       h->dynindx = elf_hash_table (info)->dynsymcount;
498       ++elf_hash_table (info)->dynsymcount;
499
500       dynstr = elf_hash_table (info)->dynstr;
501       if (dynstr == NULL)
502         {
503           /* Create a strtab to hold the dynamic symbol names.  */
504           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
505           if (dynstr == NULL)
506             return FALSE;
507         }
508
509       /* We don't put any version information in the dynamic string
510          table.  */
511       name = h->root.root.string;
512       p = strchr (name, ELF_VER_CHR);
513       if (p != NULL)
514         /* We know that the p points into writable memory.  In fact,
515            there are only a few symbols that have read-only names, being
516            those like _GLOBAL_OFFSET_TABLE_ that are created specially
517            by the backends.  Most symbols will have names pointing into
518            an ELF string table read from a file, or to objalloc memory.  */
519         *p = 0;
520
521       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
522
523       if (p != NULL)
524         *p = ELF_VER_CHR;
525
526       if (indx == (size_t) -1)
527         return FALSE;
528       h->dynstr_index = indx;
529     }
530
531   return TRUE;
532 }
533 \f
534 /* Mark a symbol dynamic.  */
535
536 static void
537 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
538                                   struct elf_link_hash_entry *h,
539                                   Elf_Internal_Sym *sym)
540 {
541   struct bfd_elf_dynamic_list *d = info->dynamic_list;
542
543   /* It may be called more than once on the same H.  */
544   if(h->dynamic || bfd_link_relocatable (info))
545     return;
546
547   if ((info->dynamic_data
548        && (h->type == STT_OBJECT
549            || h->type == STT_COMMON
550            || (sym != NULL
551                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
552                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
553       || (d != NULL
554           && h->root.type == bfd_link_hash_new
555           && (*d->match) (&d->head, NULL, h->root.root.string)))
556     h->dynamic = 1;
557 }
558
559 /* Record an assignment to a symbol made by a linker script.  We need
560    this in case some dynamic object refers to this symbol.  */
561
562 bfd_boolean
563 bfd_elf_record_link_assignment (bfd *output_bfd,
564                                 struct bfd_link_info *info,
565                                 const char *name,
566                                 bfd_boolean provide,
567                                 bfd_boolean hidden)
568 {
569   struct elf_link_hash_entry *h, *hv;
570   struct elf_link_hash_table *htab;
571   const struct elf_backend_data *bed;
572
573   if (!is_elf_hash_table (info->hash))
574     return TRUE;
575
576   htab = elf_hash_table (info);
577   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
578   if (h == NULL)
579     return provide;
580
581   if (h->versioned == unknown)
582     {
583       /* Set versioned if symbol version is unknown.  */
584       char *version = strrchr (name, ELF_VER_CHR);
585       if (version)
586         {
587           if (version > name && version[-1] != ELF_VER_CHR)
588             h->versioned = versioned_hidden;
589           else
590             h->versioned = versioned;
591         }
592     }
593
594   switch (h->root.type)
595     {
596     case bfd_link_hash_defined:
597     case bfd_link_hash_defweak:
598     case bfd_link_hash_common:
599       break;
600     case bfd_link_hash_undefweak:
601     case bfd_link_hash_undefined:
602       /* Since we're defining the symbol, don't let it seem to have not
603          been defined.  record_dynamic_symbol and size_dynamic_sections
604          may depend on this.  */
605       h->root.type = bfd_link_hash_new;
606       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
607         bfd_link_repair_undef_list (&htab->root);
608       break;
609     case bfd_link_hash_new:
610       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
611       h->non_elf = 0;
612       break;
613     case bfd_link_hash_indirect:
614       /* We had a versioned symbol in a dynamic library.  We make the
615          the versioned symbol point to this one.  */
616       bed = get_elf_backend_data (output_bfd);
617       hv = h;
618       while (hv->root.type == bfd_link_hash_indirect
619              || hv->root.type == bfd_link_hash_warning)
620         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
621       /* We don't need to update h->root.u since linker will set them
622          later.  */
623       h->root.type = bfd_link_hash_undefined;
624       hv->root.type = bfd_link_hash_indirect;
625       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
626       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
627       break;
628     case bfd_link_hash_warning:
629       abort ();
630       break;
631     }
632
633   /* If this symbol is being provided by the linker script, and it is
634      currently defined by a dynamic object, but not by a regular
635      object, then mark it as undefined so that the generic linker will
636      force the correct value.  */
637   if (provide
638       && h->def_dynamic
639       && !h->def_regular)
640     h->root.type = bfd_link_hash_undefined;
641
642   /* If this symbol is not being provided by the linker script, and it is
643      currently defined by a dynamic object, but not by a regular object,
644      then clear out any version information because the symbol will not be
645      associated with the dynamic object any more.  */
646   if (!provide
647       && h->def_dynamic
648       && !h->def_regular)
649     h->verinfo.verdef = NULL;
650
651   h->def_regular = 1;
652
653   if (hidden)
654     {
655       bed = get_elf_backend_data (output_bfd);
656       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
657         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
658       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
659     }
660
661   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
662      and executables.  */
663   if (!bfd_link_relocatable (info)
664       && h->dynindx != -1
665       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
666           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
667     h->forced_local = 1;
668
669   if ((h->def_dynamic
670        || h->ref_dynamic
671        || bfd_link_dll (info)
672        || elf_hash_table (info)->is_relocatable_executable)
673       && h->dynindx == -1)
674     {
675       if (! bfd_elf_link_record_dynamic_symbol (info, h))
676         return FALSE;
677
678       /* If this is a weak defined symbol, and we know a corresponding
679          real symbol from the same dynamic object, make sure the real
680          symbol is also made into a dynamic symbol.  */
681       if (h->u.weakdef != NULL
682           && h->u.weakdef->dynindx == -1)
683         {
684           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
685             return FALSE;
686         }
687     }
688
689   return TRUE;
690 }
691
692 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
693    success, and 2 on a failure caused by attempting to record a symbol
694    in a discarded section, eg. a discarded link-once section symbol.  */
695
696 int
697 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
698                                           bfd *input_bfd,
699                                           long input_indx)
700 {
701   bfd_size_type amt;
702   struct elf_link_local_dynamic_entry *entry;
703   struct elf_link_hash_table *eht;
704   struct elf_strtab_hash *dynstr;
705   size_t dynstr_index;
706   char *name;
707   Elf_External_Sym_Shndx eshndx;
708   char esym[sizeof (Elf64_External_Sym)];
709
710   if (! is_elf_hash_table (info->hash))
711     return 0;
712
713   /* See if the entry exists already.  */
714   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
715     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
716       return 1;
717
718   amt = sizeof (*entry);
719   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
720   if (entry == NULL)
721     return 0;
722
723   /* Go find the symbol, so that we can find it's name.  */
724   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
725                              1, input_indx, &entry->isym, esym, &eshndx))
726     {
727       bfd_release (input_bfd, entry);
728       return 0;
729     }
730
731   if (entry->isym.st_shndx != SHN_UNDEF
732       && entry->isym.st_shndx < SHN_LORESERVE)
733     {
734       asection *s;
735
736       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
737       if (s == NULL || bfd_is_abs_section (s->output_section))
738         {
739           /* We can still bfd_release here as nothing has done another
740              bfd_alloc.  We can't do this later in this function.  */
741           bfd_release (input_bfd, entry);
742           return 2;
743         }
744     }
745
746   name = (bfd_elf_string_from_elf_section
747           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
748            entry->isym.st_name));
749
750   dynstr = elf_hash_table (info)->dynstr;
751   if (dynstr == NULL)
752     {
753       /* Create a strtab to hold the dynamic symbol names.  */
754       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
755       if (dynstr == NULL)
756         return 0;
757     }
758
759   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
760   if (dynstr_index == (size_t) -1)
761     return 0;
762   entry->isym.st_name = dynstr_index;
763
764   eht = elf_hash_table (info);
765
766   entry->next = eht->dynlocal;
767   eht->dynlocal = entry;
768   entry->input_bfd = input_bfd;
769   entry->input_indx = input_indx;
770   eht->dynsymcount++;
771
772   /* Whatever binding the symbol had before, it's now local.  */
773   entry->isym.st_info
774     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
775
776   /* The dynindx will be set at the end of size_dynamic_sections.  */
777
778   return 1;
779 }
780
781 /* Return the dynindex of a local dynamic symbol.  */
782
783 long
784 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
785                                     bfd *input_bfd,
786                                     long input_indx)
787 {
788   struct elf_link_local_dynamic_entry *e;
789
790   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
791     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
792       return e->dynindx;
793   return -1;
794 }
795
796 /* This function is used to renumber the dynamic symbols, if some of
797    them are removed because they are marked as local.  This is called
798    via elf_link_hash_traverse.  */
799
800 static bfd_boolean
801 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
802                                       void *data)
803 {
804   size_t *count = (size_t *) data;
805
806   if (h->forced_local)
807     return TRUE;
808
809   if (h->dynindx != -1)
810     h->dynindx = ++(*count);
811
812   return TRUE;
813 }
814
815
816 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
817    STB_LOCAL binding.  */
818
819 static bfd_boolean
820 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
821                                             void *data)
822 {
823   size_t *count = (size_t *) data;
824
825   if (!h->forced_local)
826     return TRUE;
827
828   if (h->dynindx != -1)
829     h->dynindx = ++(*count);
830
831   return TRUE;
832 }
833
834 /* Return true if the dynamic symbol for a given section should be
835    omitted when creating a shared library.  */
836 bfd_boolean
837 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
838                                    struct bfd_link_info *info,
839                                    asection *p)
840 {
841   struct elf_link_hash_table *htab;
842   asection *ip;
843
844   switch (elf_section_data (p)->this_hdr.sh_type)
845     {
846     case SHT_PROGBITS:
847     case SHT_NOBITS:
848       /* If sh_type is yet undecided, assume it could be
849          SHT_PROGBITS/SHT_NOBITS.  */
850     case SHT_NULL:
851       htab = elf_hash_table (info);
852       if (p == htab->tls_sec)
853         return FALSE;
854
855       if (htab->text_index_section != NULL)
856         return p != htab->text_index_section && p != htab->data_index_section;
857
858       return (htab->dynobj != NULL
859               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
860               && ip->output_section == p);
861
862       /* There shouldn't be section relative relocations
863          against any other section.  */
864     default:
865       return TRUE;
866     }
867 }
868
869 /* Assign dynsym indices.  In a shared library we generate a section
870    symbol for each output section, which come first.  Next come symbols
871    which have been forced to local binding.  Then all of the back-end
872    allocated local dynamic syms, followed by the rest of the global
873    symbols.  */
874
875 static unsigned long
876 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
877                                 struct bfd_link_info *info,
878                                 unsigned long *section_sym_count)
879 {
880   unsigned long dynsymcount = 0;
881
882   if (bfd_link_pic (info)
883       || elf_hash_table (info)->is_relocatable_executable)
884     {
885       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
886       asection *p;
887       for (p = output_bfd->sections; p ; p = p->next)
888         if ((p->flags & SEC_EXCLUDE) == 0
889             && (p->flags & SEC_ALLOC) != 0
890             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
891           elf_section_data (p)->dynindx = ++dynsymcount;
892         else
893           elf_section_data (p)->dynindx = 0;
894     }
895   *section_sym_count = dynsymcount;
896
897   elf_link_hash_traverse (elf_hash_table (info),
898                           elf_link_renumber_local_hash_table_dynsyms,
899                           &dynsymcount);
900
901   if (elf_hash_table (info)->dynlocal)
902     {
903       struct elf_link_local_dynamic_entry *p;
904       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
905         p->dynindx = ++dynsymcount;
906     }
907   elf_hash_table (info)->local_dynsymcount = dynsymcount;
908
909   elf_link_hash_traverse (elf_hash_table (info),
910                           elf_link_renumber_hash_table_dynsyms,
911                           &dynsymcount);
912
913   /* There is an unused NULL entry at the head of the table which we
914      must account for in our count even if the table is empty since it
915      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
916      .dynamic section.  */
917   dynsymcount++;
918
919   elf_hash_table (info)->dynsymcount = dynsymcount;
920   return dynsymcount;
921 }
922
923 /* Merge st_other field.  */
924
925 static void
926 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
927                     const Elf_Internal_Sym *isym, asection *sec,
928                     bfd_boolean definition, bfd_boolean dynamic)
929 {
930   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
931
932   /* If st_other has a processor-specific meaning, specific
933      code might be needed here.  */
934   if (bed->elf_backend_merge_symbol_attribute)
935     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
936                                                 dynamic);
937
938   if (!dynamic)
939     {
940       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
941       unsigned hvis = ELF_ST_VISIBILITY (h->other);
942
943       /* Keep the most constraining visibility.  Leave the remainder
944          of the st_other field to elf_backend_merge_symbol_attribute.  */
945       if (symvis - 1 < hvis - 1)
946         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
947     }
948   else if (definition
949            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
950            && (sec->flags & SEC_READONLY) == 0)
951     h->protected_def = 1;
952 }
953
954 /* This function is called when we want to merge a new symbol with an
955    existing symbol.  It handles the various cases which arise when we
956    find a definition in a dynamic object, or when there is already a
957    definition in a dynamic object.  The new symbol is described by
958    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
959    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
960    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
961    of an old common symbol.  We set OVERRIDE if the old symbol is
962    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
963    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
964    to change.  By OK to change, we mean that we shouldn't warn if the
965    type or size does change.  */
966
967 static bfd_boolean
968 _bfd_elf_merge_symbol (bfd *abfd,
969                        struct bfd_link_info *info,
970                        const char *name,
971                        Elf_Internal_Sym *sym,
972                        asection **psec,
973                        bfd_vma *pvalue,
974                        struct elf_link_hash_entry **sym_hash,
975                        bfd **poldbfd,
976                        bfd_boolean *pold_weak,
977                        unsigned int *pold_alignment,
978                        bfd_boolean *skip,
979                        bfd_boolean *override,
980                        bfd_boolean *type_change_ok,
981                        bfd_boolean *size_change_ok,
982                        bfd_boolean *matched)
983 {
984   asection *sec, *oldsec;
985   struct elf_link_hash_entry *h;
986   struct elf_link_hash_entry *hi;
987   struct elf_link_hash_entry *flip;
988   int bind;
989   bfd *oldbfd;
990   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
991   bfd_boolean newweak, oldweak, newfunc, oldfunc;
992   const struct elf_backend_data *bed;
993   char *new_version;
994
995   *skip = FALSE;
996   *override = FALSE;
997
998   sec = *psec;
999   bind = ELF_ST_BIND (sym->st_info);
1000
1001   if (! bfd_is_und_section (sec))
1002     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1003   else
1004     h = ((struct elf_link_hash_entry *)
1005          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1006   if (h == NULL)
1007     return FALSE;
1008   *sym_hash = h;
1009
1010   bed = get_elf_backend_data (abfd);
1011
1012   /* NEW_VERSION is the symbol version of the new symbol.  */
1013   if (h->versioned != unversioned)
1014     {
1015       /* Symbol version is unknown or versioned.  */
1016       new_version = strrchr (name, ELF_VER_CHR);
1017       if (new_version)
1018         {
1019           if (h->versioned == unknown)
1020             {
1021               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1022                 h->versioned = versioned_hidden;
1023               else
1024                 h->versioned = versioned;
1025             }
1026           new_version += 1;
1027           if (new_version[0] == '\0')
1028             new_version = NULL;
1029         }
1030       else
1031         h->versioned = unversioned;
1032     }
1033   else
1034     new_version = NULL;
1035
1036   /* For merging, we only care about real symbols.  But we need to make
1037      sure that indirect symbol dynamic flags are updated.  */
1038   hi = h;
1039   while (h->root.type == bfd_link_hash_indirect
1040          || h->root.type == bfd_link_hash_warning)
1041     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1042
1043   if (!*matched)
1044     {
1045       if (hi == h || h->root.type == bfd_link_hash_new)
1046         *matched = TRUE;
1047       else
1048         {
1049           /* OLD_HIDDEN is true if the existing symbol is only visible
1050              to the symbol with the same symbol version.  NEW_HIDDEN is
1051              true if the new symbol is only visible to the symbol with
1052              the same symbol version.  */
1053           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1054           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1055           if (!old_hidden && !new_hidden)
1056             /* The new symbol matches the existing symbol if both
1057                aren't hidden.  */
1058             *matched = TRUE;
1059           else
1060             {
1061               /* OLD_VERSION is the symbol version of the existing
1062                  symbol. */
1063               char *old_version;
1064
1065               if (h->versioned >= versioned)
1066                 old_version = strrchr (h->root.root.string,
1067                                        ELF_VER_CHR) + 1;
1068               else
1069                  old_version = NULL;
1070
1071               /* The new symbol matches the existing symbol if they
1072                  have the same symbol version.  */
1073               *matched = (old_version == new_version
1074                           || (old_version != NULL
1075                               && new_version != NULL
1076                               && strcmp (old_version, new_version) == 0));
1077             }
1078         }
1079     }
1080
1081   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1082      existing symbol.  */
1083
1084   oldbfd = NULL;
1085   oldsec = NULL;
1086   switch (h->root.type)
1087     {
1088     default:
1089       break;
1090
1091     case bfd_link_hash_undefined:
1092     case bfd_link_hash_undefweak:
1093       oldbfd = h->root.u.undef.abfd;
1094       break;
1095
1096     case bfd_link_hash_defined:
1097     case bfd_link_hash_defweak:
1098       oldbfd = h->root.u.def.section->owner;
1099       oldsec = h->root.u.def.section;
1100       break;
1101
1102     case bfd_link_hash_common:
1103       oldbfd = h->root.u.c.p->section->owner;
1104       oldsec = h->root.u.c.p->section;
1105       if (pold_alignment)
1106         *pold_alignment = h->root.u.c.p->alignment_power;
1107       break;
1108     }
1109   if (poldbfd && *poldbfd == NULL)
1110     *poldbfd = oldbfd;
1111
1112   /* Differentiate strong and weak symbols.  */
1113   newweak = bind == STB_WEAK;
1114   oldweak = (h->root.type == bfd_link_hash_defweak
1115              || h->root.type == bfd_link_hash_undefweak);
1116   if (pold_weak)
1117     *pold_weak = oldweak;
1118
1119   /* This code is for coping with dynamic objects, and is only useful
1120      if we are doing an ELF link.  */
1121   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1122     return TRUE;
1123
1124   /* We have to check it for every instance since the first few may be
1125      references and not all compilers emit symbol type for undefined
1126      symbols.  */
1127   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1128
1129   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1130      respectively, is from a dynamic object.  */
1131
1132   newdyn = (abfd->flags & DYNAMIC) != 0;
1133
1134   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1135      syms and defined syms in dynamic libraries respectively.
1136      ref_dynamic on the other hand can be set for a symbol defined in
1137      a dynamic library, and def_dynamic may not be set;  When the
1138      definition in a dynamic lib is overridden by a definition in the
1139      executable use of the symbol in the dynamic lib becomes a
1140      reference to the executable symbol.  */
1141   if (newdyn)
1142     {
1143       if (bfd_is_und_section (sec))
1144         {
1145           if (bind != STB_WEAK)
1146             {
1147               h->ref_dynamic_nonweak = 1;
1148               hi->ref_dynamic_nonweak = 1;
1149             }
1150         }
1151       else
1152         {
1153           /* Update the existing symbol only if they match. */
1154           if (*matched)
1155             h->dynamic_def = 1;
1156           hi->dynamic_def = 1;
1157         }
1158     }
1159
1160   /* If we just created the symbol, mark it as being an ELF symbol.
1161      Other than that, there is nothing to do--there is no merge issue
1162      with a newly defined symbol--so we just return.  */
1163
1164   if (h->root.type == bfd_link_hash_new)
1165     {
1166       h->non_elf = 0;
1167       return TRUE;
1168     }
1169
1170   /* In cases involving weak versioned symbols, we may wind up trying
1171      to merge a symbol with itself.  Catch that here, to avoid the
1172      confusion that results if we try to override a symbol with
1173      itself.  The additional tests catch cases like
1174      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1175      dynamic object, which we do want to handle here.  */
1176   if (abfd == oldbfd
1177       && (newweak || oldweak)
1178       && ((abfd->flags & DYNAMIC) == 0
1179           || !h->def_regular))
1180     return TRUE;
1181
1182   olddyn = FALSE;
1183   if (oldbfd != NULL)
1184     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1185   else if (oldsec != NULL)
1186     {
1187       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1188          indices used by MIPS ELF.  */
1189       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1190     }
1191
1192   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1193      respectively, appear to be a definition rather than reference.  */
1194
1195   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1196
1197   olddef = (h->root.type != bfd_link_hash_undefined
1198             && h->root.type != bfd_link_hash_undefweak
1199             && h->root.type != bfd_link_hash_common);
1200
1201   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1202      respectively, appear to be a function.  */
1203
1204   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1205              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1206
1207   oldfunc = (h->type != STT_NOTYPE
1208              && bed->is_function_type (h->type));
1209
1210   /* If creating a default indirect symbol ("foo" or "foo@") from a
1211      dynamic versioned definition ("foo@@") skip doing so if there is
1212      an existing regular definition with a different type.  We don't
1213      want, for example, a "time" variable in the executable overriding
1214      a "time" function in a shared library.  */
1215   if (pold_alignment == NULL
1216       && newdyn
1217       && newdef
1218       && !olddyn
1219       && (olddef || h->root.type == bfd_link_hash_common)
1220       && ELF_ST_TYPE (sym->st_info) != h->type
1221       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1222       && h->type != STT_NOTYPE
1223       && !(newfunc && oldfunc))
1224     {
1225       *skip = TRUE;
1226       return TRUE;
1227     }
1228
1229   /* Check TLS symbols.  We don't check undefined symbols introduced
1230      by "ld -u" which have no type (and oldbfd NULL), and we don't
1231      check symbols from plugins because they also have no type.  */
1232   if (oldbfd != NULL
1233       && (oldbfd->flags & BFD_PLUGIN) == 0
1234       && (abfd->flags & BFD_PLUGIN) == 0
1235       && ELF_ST_TYPE (sym->st_info) != h->type
1236       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1237     {
1238       bfd *ntbfd, *tbfd;
1239       bfd_boolean ntdef, tdef;
1240       asection *ntsec, *tsec;
1241
1242       if (h->type == STT_TLS)
1243         {
1244           ntbfd = abfd;
1245           ntsec = sec;
1246           ntdef = newdef;
1247           tbfd = oldbfd;
1248           tsec = oldsec;
1249           tdef = olddef;
1250         }
1251       else
1252         {
1253           ntbfd = oldbfd;
1254           ntsec = oldsec;
1255           ntdef = olddef;
1256           tbfd = abfd;
1257           tsec = sec;
1258           tdef = newdef;
1259         }
1260
1261       if (tdef && ntdef)
1262         _bfd_error_handler
1263           /* xgettext:c-format */
1264           (_("%s: TLS definition in %B section %A "
1265              "mismatches non-TLS definition in %B section %A"),
1266            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1267       else if (!tdef && !ntdef)
1268         _bfd_error_handler
1269           /* xgettext:c-format */
1270           (_("%s: TLS reference in %B "
1271              "mismatches non-TLS reference in %B"),
1272            tbfd, ntbfd, h->root.root.string);
1273       else if (tdef)
1274         _bfd_error_handler
1275           /* xgettext:c-format */
1276           (_("%s: TLS definition in %B section %A "
1277              "mismatches non-TLS reference in %B"),
1278            tbfd, tsec, ntbfd, h->root.root.string);
1279       else
1280         _bfd_error_handler
1281           /* xgettext:c-format */
1282           (_("%s: TLS reference in %B "
1283              "mismatches non-TLS definition in %B section %A"),
1284            tbfd, ntbfd, ntsec, h->root.root.string);
1285
1286       bfd_set_error (bfd_error_bad_value);
1287       return FALSE;
1288     }
1289
1290   /* If the old symbol has non-default visibility, we ignore the new
1291      definition from a dynamic object.  */
1292   if (newdyn
1293       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1294       && !bfd_is_und_section (sec))
1295     {
1296       *skip = TRUE;
1297       /* Make sure this symbol is dynamic.  */
1298       h->ref_dynamic = 1;
1299       hi->ref_dynamic = 1;
1300       /* A protected symbol has external availability. Make sure it is
1301          recorded as dynamic.
1302
1303          FIXME: Should we check type and size for protected symbol?  */
1304       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1305         return bfd_elf_link_record_dynamic_symbol (info, h);
1306       else
1307         return TRUE;
1308     }
1309   else if (!newdyn
1310            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1311            && h->def_dynamic)
1312     {
1313       /* If the new symbol with non-default visibility comes from a
1314          relocatable file and the old definition comes from a dynamic
1315          object, we remove the old definition.  */
1316       if (hi->root.type == bfd_link_hash_indirect)
1317         {
1318           /* Handle the case where the old dynamic definition is
1319              default versioned.  We need to copy the symbol info from
1320              the symbol with default version to the normal one if it
1321              was referenced before.  */
1322           if (h->ref_regular)
1323             {
1324               hi->root.type = h->root.type;
1325               h->root.type = bfd_link_hash_indirect;
1326               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1327
1328               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1329               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1330                 {
1331                   /* If the new symbol is hidden or internal, completely undo
1332                      any dynamic link state.  */
1333                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1334                   h->forced_local = 0;
1335                   h->ref_dynamic = 0;
1336                 }
1337               else
1338                 h->ref_dynamic = 1;
1339
1340               h->def_dynamic = 0;
1341               /* FIXME: Should we check type and size for protected symbol?  */
1342               h->size = 0;
1343               h->type = 0;
1344
1345               h = hi;
1346             }
1347           else
1348             h = hi;
1349         }
1350
1351       /* If the old symbol was undefined before, then it will still be
1352          on the undefs list.  If the new symbol is undefined or
1353          common, we can't make it bfd_link_hash_new here, because new
1354          undefined or common symbols will be added to the undefs list
1355          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1356          added twice to the undefs list.  Also, if the new symbol is
1357          undefweak then we don't want to lose the strong undef.  */
1358       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1359         {
1360           h->root.type = bfd_link_hash_undefined;
1361           h->root.u.undef.abfd = abfd;
1362         }
1363       else
1364         {
1365           h->root.type = bfd_link_hash_new;
1366           h->root.u.undef.abfd = NULL;
1367         }
1368
1369       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1370         {
1371           /* If the new symbol is hidden or internal, completely undo
1372              any dynamic link state.  */
1373           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1374           h->forced_local = 0;
1375           h->ref_dynamic = 0;
1376         }
1377       else
1378         h->ref_dynamic = 1;
1379       h->def_dynamic = 0;
1380       /* FIXME: Should we check type and size for protected symbol?  */
1381       h->size = 0;
1382       h->type = 0;
1383       return TRUE;
1384     }
1385
1386   /* If a new weak symbol definition comes from a regular file and the
1387      old symbol comes from a dynamic library, we treat the new one as
1388      strong.  Similarly, an old weak symbol definition from a regular
1389      file is treated as strong when the new symbol comes from a dynamic
1390      library.  Further, an old weak symbol from a dynamic library is
1391      treated as strong if the new symbol is from a dynamic library.
1392      This reflects the way glibc's ld.so works.
1393
1394      Do this before setting *type_change_ok or *size_change_ok so that
1395      we warn properly when dynamic library symbols are overridden.  */
1396
1397   if (newdef && !newdyn && olddyn)
1398     newweak = FALSE;
1399   if (olddef && newdyn)
1400     oldweak = FALSE;
1401
1402   /* Allow changes between different types of function symbol.  */
1403   if (newfunc && oldfunc)
1404     *type_change_ok = TRUE;
1405
1406   /* It's OK to change the type if either the existing symbol or the
1407      new symbol is weak.  A type change is also OK if the old symbol
1408      is undefined and the new symbol is defined.  */
1409
1410   if (oldweak
1411       || newweak
1412       || (newdef
1413           && h->root.type == bfd_link_hash_undefined))
1414     *type_change_ok = TRUE;
1415
1416   /* It's OK to change the size if either the existing symbol or the
1417      new symbol is weak, or if the old symbol is undefined.  */
1418
1419   if (*type_change_ok
1420       || h->root.type == bfd_link_hash_undefined)
1421     *size_change_ok = TRUE;
1422
1423   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1424      symbol, respectively, appears to be a common symbol in a dynamic
1425      object.  If a symbol appears in an uninitialized section, and is
1426      not weak, and is not a function, then it may be a common symbol
1427      which was resolved when the dynamic object was created.  We want
1428      to treat such symbols specially, because they raise special
1429      considerations when setting the symbol size: if the symbol
1430      appears as a common symbol in a regular object, and the size in
1431      the regular object is larger, we must make sure that we use the
1432      larger size.  This problematic case can always be avoided in C,
1433      but it must be handled correctly when using Fortran shared
1434      libraries.
1435
1436      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1437      likewise for OLDDYNCOMMON and OLDDEF.
1438
1439      Note that this test is just a heuristic, and that it is quite
1440      possible to have an uninitialized symbol in a shared object which
1441      is really a definition, rather than a common symbol.  This could
1442      lead to some minor confusion when the symbol really is a common
1443      symbol in some regular object.  However, I think it will be
1444      harmless.  */
1445
1446   if (newdyn
1447       && newdef
1448       && !newweak
1449       && (sec->flags & SEC_ALLOC) != 0
1450       && (sec->flags & SEC_LOAD) == 0
1451       && sym->st_size > 0
1452       && !newfunc)
1453     newdyncommon = TRUE;
1454   else
1455     newdyncommon = FALSE;
1456
1457   if (olddyn
1458       && olddef
1459       && h->root.type == bfd_link_hash_defined
1460       && h->def_dynamic
1461       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1462       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1463       && h->size > 0
1464       && !oldfunc)
1465     olddyncommon = TRUE;
1466   else
1467     olddyncommon = FALSE;
1468
1469   /* We now know everything about the old and new symbols.  We ask the
1470      backend to check if we can merge them.  */
1471   if (bed->merge_symbol != NULL)
1472     {
1473       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1474         return FALSE;
1475       sec = *psec;
1476     }
1477
1478   /* If both the old and the new symbols look like common symbols in a
1479      dynamic object, set the size of the symbol to the larger of the
1480      two.  */
1481
1482   if (olddyncommon
1483       && newdyncommon
1484       && sym->st_size != h->size)
1485     {
1486       /* Since we think we have two common symbols, issue a multiple
1487          common warning if desired.  Note that we only warn if the
1488          size is different.  If the size is the same, we simply let
1489          the old symbol override the new one as normally happens with
1490          symbols defined in dynamic objects.  */
1491
1492       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1493                                            bfd_link_hash_common, sym->st_size);
1494       if (sym->st_size > h->size)
1495         h->size = sym->st_size;
1496
1497       *size_change_ok = TRUE;
1498     }
1499
1500   /* If we are looking at a dynamic object, and we have found a
1501      definition, we need to see if the symbol was already defined by
1502      some other object.  If so, we want to use the existing
1503      definition, and we do not want to report a multiple symbol
1504      definition error; we do this by clobbering *PSEC to be
1505      bfd_und_section_ptr.
1506
1507      We treat a common symbol as a definition if the symbol in the
1508      shared library is a function, since common symbols always
1509      represent variables; this can cause confusion in principle, but
1510      any such confusion would seem to indicate an erroneous program or
1511      shared library.  We also permit a common symbol in a regular
1512      object to override a weak symbol in a shared object.  A common
1513      symbol in executable also overrides a symbol in a shared object.  */
1514
1515   if (newdyn
1516       && newdef
1517       && (olddef
1518           || (h->root.type == bfd_link_hash_common
1519               && (newweak
1520                   || newfunc
1521                   || (!olddyn && bfd_link_executable (info))))))
1522     {
1523       *override = TRUE;
1524       newdef = FALSE;
1525       newdyncommon = FALSE;
1526
1527       *psec = sec = bfd_und_section_ptr;
1528       *size_change_ok = TRUE;
1529
1530       /* If we get here when the old symbol is a common symbol, then
1531          we are explicitly letting it override a weak symbol or
1532          function in a dynamic object, and we don't want to warn about
1533          a type change.  If the old symbol is a defined symbol, a type
1534          change warning may still be appropriate.  */
1535
1536       if (h->root.type == bfd_link_hash_common)
1537         *type_change_ok = TRUE;
1538     }
1539
1540   /* Handle the special case of an old common symbol merging with a
1541      new symbol which looks like a common symbol in a shared object.
1542      We change *PSEC and *PVALUE to make the new symbol look like a
1543      common symbol, and let _bfd_generic_link_add_one_symbol do the
1544      right thing.  */
1545
1546   if (newdyncommon
1547       && h->root.type == bfd_link_hash_common)
1548     {
1549       *override = TRUE;
1550       newdef = FALSE;
1551       newdyncommon = FALSE;
1552       *pvalue = sym->st_size;
1553       *psec = sec = bed->common_section (oldsec);
1554       *size_change_ok = TRUE;
1555     }
1556
1557   /* Skip weak definitions of symbols that are already defined.  */
1558   if (newdef && olddef && newweak)
1559     {
1560       /* Don't skip new non-IR weak syms.  */
1561       if (!(oldbfd != NULL
1562             && (oldbfd->flags & BFD_PLUGIN) != 0
1563             && (abfd->flags & BFD_PLUGIN) == 0))
1564         {
1565           newdef = FALSE;
1566           *skip = TRUE;
1567         }
1568
1569       /* Merge st_other.  If the symbol already has a dynamic index,
1570          but visibility says it should not be visible, turn it into a
1571          local symbol.  */
1572       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1573       if (h->dynindx != -1)
1574         switch (ELF_ST_VISIBILITY (h->other))
1575           {
1576           case STV_INTERNAL:
1577           case STV_HIDDEN:
1578             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1579             break;
1580           }
1581     }
1582
1583   /* If the old symbol is from a dynamic object, and the new symbol is
1584      a definition which is not from a dynamic object, then the new
1585      symbol overrides the old symbol.  Symbols from regular files
1586      always take precedence over symbols from dynamic objects, even if
1587      they are defined after the dynamic object in the link.
1588
1589      As above, we again permit a common symbol in a regular object to
1590      override a definition in a shared object if the shared object
1591      symbol is a function or is weak.  */
1592
1593   flip = NULL;
1594   if (!newdyn
1595       && (newdef
1596           || (bfd_is_com_section (sec)
1597               && (oldweak || oldfunc)))
1598       && olddyn
1599       && olddef
1600       && h->def_dynamic)
1601     {
1602       /* Change the hash table entry to undefined, and let
1603          _bfd_generic_link_add_one_symbol do the right thing with the
1604          new definition.  */
1605
1606       h->root.type = bfd_link_hash_undefined;
1607       h->root.u.undef.abfd = h->root.u.def.section->owner;
1608       *size_change_ok = TRUE;
1609
1610       olddef = FALSE;
1611       olddyncommon = FALSE;
1612
1613       /* We again permit a type change when a common symbol may be
1614          overriding a function.  */
1615
1616       if (bfd_is_com_section (sec))
1617         {
1618           if (oldfunc)
1619             {
1620               /* If a common symbol overrides a function, make sure
1621                  that it isn't defined dynamically nor has type
1622                  function.  */
1623               h->def_dynamic = 0;
1624               h->type = STT_NOTYPE;
1625             }
1626           *type_change_ok = TRUE;
1627         }
1628
1629       if (hi->root.type == bfd_link_hash_indirect)
1630         flip = hi;
1631       else
1632         /* This union may have been set to be non-NULL when this symbol
1633            was seen in a dynamic object.  We must force the union to be
1634            NULL, so that it is correct for a regular symbol.  */
1635         h->verinfo.vertree = NULL;
1636     }
1637
1638   /* Handle the special case of a new common symbol merging with an
1639      old symbol that looks like it might be a common symbol defined in
1640      a shared object.  Note that we have already handled the case in
1641      which a new common symbol should simply override the definition
1642      in the shared library.  */
1643
1644   if (! newdyn
1645       && bfd_is_com_section (sec)
1646       && olddyncommon)
1647     {
1648       /* It would be best if we could set the hash table entry to a
1649          common symbol, but we don't know what to use for the section
1650          or the alignment.  */
1651       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1652                                            bfd_link_hash_common, sym->st_size);
1653
1654       /* If the presumed common symbol in the dynamic object is
1655          larger, pretend that the new symbol has its size.  */
1656
1657       if (h->size > *pvalue)
1658         *pvalue = h->size;
1659
1660       /* We need to remember the alignment required by the symbol
1661          in the dynamic object.  */
1662       BFD_ASSERT (pold_alignment);
1663       *pold_alignment = h->root.u.def.section->alignment_power;
1664
1665       olddef = FALSE;
1666       olddyncommon = FALSE;
1667
1668       h->root.type = bfd_link_hash_undefined;
1669       h->root.u.undef.abfd = h->root.u.def.section->owner;
1670
1671       *size_change_ok = TRUE;
1672       *type_change_ok = TRUE;
1673
1674       if (hi->root.type == bfd_link_hash_indirect)
1675         flip = hi;
1676       else
1677         h->verinfo.vertree = NULL;
1678     }
1679
1680   if (flip != NULL)
1681     {
1682       /* Handle the case where we had a versioned symbol in a dynamic
1683          library and now find a definition in a normal object.  In this
1684          case, we make the versioned symbol point to the normal one.  */
1685       flip->root.type = h->root.type;
1686       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1687       h->root.type = bfd_link_hash_indirect;
1688       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1689       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1690       if (h->def_dynamic)
1691         {
1692           h->def_dynamic = 0;
1693           flip->ref_dynamic = 1;
1694         }
1695     }
1696
1697   return TRUE;
1698 }
1699
1700 /* This function is called to create an indirect symbol from the
1701    default for the symbol with the default version if needed. The
1702    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1703    set DYNSYM if the new indirect symbol is dynamic.  */
1704
1705 static bfd_boolean
1706 _bfd_elf_add_default_symbol (bfd *abfd,
1707                              struct bfd_link_info *info,
1708                              struct elf_link_hash_entry *h,
1709                              const char *name,
1710                              Elf_Internal_Sym *sym,
1711                              asection *sec,
1712                              bfd_vma value,
1713                              bfd **poldbfd,
1714                              bfd_boolean *dynsym)
1715 {
1716   bfd_boolean type_change_ok;
1717   bfd_boolean size_change_ok;
1718   bfd_boolean skip;
1719   char *shortname;
1720   struct elf_link_hash_entry *hi;
1721   struct bfd_link_hash_entry *bh;
1722   const struct elf_backend_data *bed;
1723   bfd_boolean collect;
1724   bfd_boolean dynamic;
1725   bfd_boolean override;
1726   char *p;
1727   size_t len, shortlen;
1728   asection *tmp_sec;
1729   bfd_boolean matched;
1730
1731   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1732     return TRUE;
1733
1734   /* If this symbol has a version, and it is the default version, we
1735      create an indirect symbol from the default name to the fully
1736      decorated name.  This will cause external references which do not
1737      specify a version to be bound to this version of the symbol.  */
1738   p = strchr (name, ELF_VER_CHR);
1739   if (h->versioned == unknown)
1740     {
1741       if (p == NULL)
1742         {
1743           h->versioned = unversioned;
1744           return TRUE;
1745         }
1746       else
1747         {
1748           if (p[1] != ELF_VER_CHR)
1749             {
1750               h->versioned = versioned_hidden;
1751               return TRUE;
1752             }
1753           else
1754             h->versioned = versioned;
1755         }
1756     }
1757   else
1758     {
1759       /* PR ld/19073: We may see an unversioned definition after the
1760          default version.  */
1761       if (p == NULL)
1762         return TRUE;
1763     }
1764
1765   bed = get_elf_backend_data (abfd);
1766   collect = bed->collect;
1767   dynamic = (abfd->flags & DYNAMIC) != 0;
1768
1769   shortlen = p - name;
1770   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1771   if (shortname == NULL)
1772     return FALSE;
1773   memcpy (shortname, name, shortlen);
1774   shortname[shortlen] = '\0';
1775
1776   /* We are going to create a new symbol.  Merge it with any existing
1777      symbol with this name.  For the purposes of the merge, act as
1778      though we were defining the symbol we just defined, although we
1779      actually going to define an indirect symbol.  */
1780   type_change_ok = FALSE;
1781   size_change_ok = FALSE;
1782   matched = TRUE;
1783   tmp_sec = sec;
1784   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1785                               &hi, poldbfd, NULL, NULL, &skip, &override,
1786                               &type_change_ok, &size_change_ok, &matched))
1787     return FALSE;
1788
1789   if (skip)
1790     goto nondefault;
1791
1792   if (hi->def_regular)
1793     {
1794       /* If the undecorated symbol will have a version added by a
1795          script different to H, then don't indirect to/from the
1796          undecorated symbol.  This isn't ideal because we may not yet
1797          have seen symbol versions, if given by a script on the
1798          command line rather than via --version-script.  */
1799       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1800         {
1801           bfd_boolean hide;
1802
1803           hi->verinfo.vertree
1804             = bfd_find_version_for_sym (info->version_info,
1805                                         hi->root.root.string, &hide);
1806           if (hi->verinfo.vertree != NULL && hide)
1807             {
1808               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1809               goto nondefault;
1810             }
1811         }
1812       if (hi->verinfo.vertree != NULL
1813           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1814         goto nondefault;
1815     }
1816
1817   if (! override)
1818     {
1819       /* Add the default symbol if not performing a relocatable link.  */
1820       if (! bfd_link_relocatable (info))
1821         {
1822           bh = &hi->root;
1823           if (! (_bfd_generic_link_add_one_symbol
1824                  (info, abfd, shortname, BSF_INDIRECT,
1825                   bfd_ind_section_ptr,
1826                   0, name, FALSE, collect, &bh)))
1827             return FALSE;
1828           hi = (struct elf_link_hash_entry *) bh;
1829         }
1830     }
1831   else
1832     {
1833       /* In this case the symbol named SHORTNAME is overriding the
1834          indirect symbol we want to add.  We were planning on making
1835          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1836          is the name without a version.  NAME is the fully versioned
1837          name, and it is the default version.
1838
1839          Overriding means that we already saw a definition for the
1840          symbol SHORTNAME in a regular object, and it is overriding
1841          the symbol defined in the dynamic object.
1842
1843          When this happens, we actually want to change NAME, the
1844          symbol we just added, to refer to SHORTNAME.  This will cause
1845          references to NAME in the shared object to become references
1846          to SHORTNAME in the regular object.  This is what we expect
1847          when we override a function in a shared object: that the
1848          references in the shared object will be mapped to the
1849          definition in the regular object.  */
1850
1851       while (hi->root.type == bfd_link_hash_indirect
1852              || hi->root.type == bfd_link_hash_warning)
1853         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1854
1855       h->root.type = bfd_link_hash_indirect;
1856       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1857       if (h->def_dynamic)
1858         {
1859           h->def_dynamic = 0;
1860           hi->ref_dynamic = 1;
1861           if (hi->ref_regular
1862               || hi->def_regular)
1863             {
1864               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1865                 return FALSE;
1866             }
1867         }
1868
1869       /* Now set HI to H, so that the following code will set the
1870          other fields correctly.  */
1871       hi = h;
1872     }
1873
1874   /* Check if HI is a warning symbol.  */
1875   if (hi->root.type == bfd_link_hash_warning)
1876     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1877
1878   /* If there is a duplicate definition somewhere, then HI may not
1879      point to an indirect symbol.  We will have reported an error to
1880      the user in that case.  */
1881
1882   if (hi->root.type == bfd_link_hash_indirect)
1883     {
1884       struct elf_link_hash_entry *ht;
1885
1886       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1887       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1888
1889       /* A reference to the SHORTNAME symbol from a dynamic library
1890          will be satisfied by the versioned symbol at runtime.  In
1891          effect, we have a reference to the versioned symbol.  */
1892       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1893       hi->dynamic_def |= ht->dynamic_def;
1894
1895       /* See if the new flags lead us to realize that the symbol must
1896          be dynamic.  */
1897       if (! *dynsym)
1898         {
1899           if (! dynamic)
1900             {
1901               if (! bfd_link_executable (info)
1902                   || hi->def_dynamic
1903                   || hi->ref_dynamic)
1904                 *dynsym = TRUE;
1905             }
1906           else
1907             {
1908               if (hi->ref_regular)
1909                 *dynsym = TRUE;
1910             }
1911         }
1912     }
1913
1914   /* We also need to define an indirection from the nondefault version
1915      of the symbol.  */
1916
1917 nondefault:
1918   len = strlen (name);
1919   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1920   if (shortname == NULL)
1921     return FALSE;
1922   memcpy (shortname, name, shortlen);
1923   memcpy (shortname + shortlen, p + 1, len - shortlen);
1924
1925   /* Once again, merge with any existing symbol.  */
1926   type_change_ok = FALSE;
1927   size_change_ok = FALSE;
1928   tmp_sec = sec;
1929   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1930                               &hi, poldbfd, NULL, NULL, &skip, &override,
1931                               &type_change_ok, &size_change_ok, &matched))
1932     return FALSE;
1933
1934   if (skip)
1935     return TRUE;
1936
1937   if (override)
1938     {
1939       /* Here SHORTNAME is a versioned name, so we don't expect to see
1940          the type of override we do in the case above unless it is
1941          overridden by a versioned definition.  */
1942       if (hi->root.type != bfd_link_hash_defined
1943           && hi->root.type != bfd_link_hash_defweak)
1944         _bfd_error_handler
1945           /* xgettext:c-format */
1946           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1947            abfd, shortname);
1948     }
1949   else
1950     {
1951       bh = &hi->root;
1952       if (! (_bfd_generic_link_add_one_symbol
1953              (info, abfd, shortname, BSF_INDIRECT,
1954               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1955         return FALSE;
1956       hi = (struct elf_link_hash_entry *) bh;
1957
1958       /* If there is a duplicate definition somewhere, then HI may not
1959          point to an indirect symbol.  We will have reported an error
1960          to the user in that case.  */
1961
1962       if (hi->root.type == bfd_link_hash_indirect)
1963         {
1964           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1965           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1966           hi->dynamic_def |= h->dynamic_def;
1967
1968           /* See if the new flags lead us to realize that the symbol
1969              must be dynamic.  */
1970           if (! *dynsym)
1971             {
1972               if (! dynamic)
1973                 {
1974                   if (! bfd_link_executable (info)
1975                       || hi->ref_dynamic)
1976                     *dynsym = TRUE;
1977                 }
1978               else
1979                 {
1980                   if (hi->ref_regular)
1981                     *dynsym = TRUE;
1982                 }
1983             }
1984         }
1985     }
1986
1987   return TRUE;
1988 }
1989 \f
1990 /* This routine is used to export all defined symbols into the dynamic
1991    symbol table.  It is called via elf_link_hash_traverse.  */
1992
1993 static bfd_boolean
1994 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1995 {
1996   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1997
1998   /* Ignore indirect symbols.  These are added by the versioning code.  */
1999   if (h->root.type == bfd_link_hash_indirect)
2000     return TRUE;
2001
2002   /* Ignore this if we won't export it.  */
2003   if (!eif->info->export_dynamic && !h->dynamic)
2004     return TRUE;
2005
2006   if (h->dynindx == -1
2007       && (h->def_regular || h->ref_regular)
2008       && ! bfd_hide_sym_by_version (eif->info->version_info,
2009                                     h->root.root.string))
2010     {
2011       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2012         {
2013           eif->failed = TRUE;
2014           return FALSE;
2015         }
2016     }
2017
2018   return TRUE;
2019 }
2020 \f
2021 /* Look through the symbols which are defined in other shared
2022    libraries and referenced here.  Update the list of version
2023    dependencies.  This will be put into the .gnu.version_r section.
2024    This function is called via elf_link_hash_traverse.  */
2025
2026 static bfd_boolean
2027 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2028                                          void *data)
2029 {
2030   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2031   Elf_Internal_Verneed *t;
2032   Elf_Internal_Vernaux *a;
2033   bfd_size_type amt;
2034
2035   /* We only care about symbols defined in shared objects with version
2036      information.  */
2037   if (!h->def_dynamic
2038       || h->def_regular
2039       || h->dynindx == -1
2040       || h->verinfo.verdef == NULL
2041       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2042           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2043     return TRUE;
2044
2045   /* See if we already know about this version.  */
2046   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2047        t != NULL;
2048        t = t->vn_nextref)
2049     {
2050       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2051         continue;
2052
2053       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2054         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2055           return TRUE;
2056
2057       break;
2058     }
2059
2060   /* This is a new version.  Add it to tree we are building.  */
2061
2062   if (t == NULL)
2063     {
2064       amt = sizeof *t;
2065       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2066       if (t == NULL)
2067         {
2068           rinfo->failed = TRUE;
2069           return FALSE;
2070         }
2071
2072       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2073       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2074       elf_tdata (rinfo->info->output_bfd)->verref = t;
2075     }
2076
2077   amt = sizeof *a;
2078   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2079   if (a == NULL)
2080     {
2081       rinfo->failed = TRUE;
2082       return FALSE;
2083     }
2084
2085   /* Note that we are copying a string pointer here, and testing it
2086      above.  If bfd_elf_string_from_elf_section is ever changed to
2087      discard the string data when low in memory, this will have to be
2088      fixed.  */
2089   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2090
2091   a->vna_flags = h->verinfo.verdef->vd_flags;
2092   a->vna_nextptr = t->vn_auxptr;
2093
2094   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2095   ++rinfo->vers;
2096
2097   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2098
2099   t->vn_auxptr = a;
2100
2101   return TRUE;
2102 }
2103
2104 /* Figure out appropriate versions for all the symbols.  We may not
2105    have the version number script until we have read all of the input
2106    files, so until that point we don't know which symbols should be
2107    local.  This function is called via elf_link_hash_traverse.  */
2108
2109 static bfd_boolean
2110 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2111 {
2112   struct elf_info_failed *sinfo;
2113   struct bfd_link_info *info;
2114   const struct elf_backend_data *bed;
2115   struct elf_info_failed eif;
2116   char *p;
2117
2118   sinfo = (struct elf_info_failed *) data;
2119   info = sinfo->info;
2120
2121   /* Fix the symbol flags.  */
2122   eif.failed = FALSE;
2123   eif.info = info;
2124   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2125     {
2126       if (eif.failed)
2127         sinfo->failed = TRUE;
2128       return FALSE;
2129     }
2130
2131   /* We only need version numbers for symbols defined in regular
2132      objects.  */
2133   if (!h->def_regular)
2134     return TRUE;
2135
2136   bed = get_elf_backend_data (info->output_bfd);
2137   p = strchr (h->root.root.string, ELF_VER_CHR);
2138   if (p != NULL && h->verinfo.vertree == NULL)
2139     {
2140       struct bfd_elf_version_tree *t;
2141
2142       ++p;
2143       if (*p == ELF_VER_CHR)
2144         ++p;
2145
2146       /* If there is no version string, we can just return out.  */
2147       if (*p == '\0')
2148         return TRUE;
2149
2150       /* Look for the version.  If we find it, it is no longer weak.  */
2151       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2152         {
2153           if (strcmp (t->name, p) == 0)
2154             {
2155               size_t len;
2156               char *alc;
2157               struct bfd_elf_version_expr *d;
2158
2159               len = p - h->root.root.string;
2160               alc = (char *) bfd_malloc (len);
2161               if (alc == NULL)
2162                 {
2163                   sinfo->failed = TRUE;
2164                   return FALSE;
2165                 }
2166               memcpy (alc, h->root.root.string, len - 1);
2167               alc[len - 1] = '\0';
2168               if (alc[len - 2] == ELF_VER_CHR)
2169                 alc[len - 2] = '\0';
2170
2171               h->verinfo.vertree = t;
2172               t->used = TRUE;
2173               d = NULL;
2174
2175               if (t->globals.list != NULL)
2176                 d = (*t->match) (&t->globals, NULL, alc);
2177
2178               /* See if there is anything to force this symbol to
2179                  local scope.  */
2180               if (d == NULL && t->locals.list != NULL)
2181                 {
2182                   d = (*t->match) (&t->locals, NULL, alc);
2183                   if (d != NULL
2184                       && h->dynindx != -1
2185                       && ! info->export_dynamic)
2186                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2187                 }
2188
2189               free (alc);
2190               break;
2191             }
2192         }
2193
2194       /* If we are building an application, we need to create a
2195          version node for this version.  */
2196       if (t == NULL && bfd_link_executable (info))
2197         {
2198           struct bfd_elf_version_tree **pp;
2199           int version_index;
2200
2201           /* If we aren't going to export this symbol, we don't need
2202              to worry about it.  */
2203           if (h->dynindx == -1)
2204             return TRUE;
2205
2206           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2207                                                           sizeof *t);
2208           if (t == NULL)
2209             {
2210               sinfo->failed = TRUE;
2211               return FALSE;
2212             }
2213
2214           t->name = p;
2215           t->name_indx = (unsigned int) -1;
2216           t->used = TRUE;
2217
2218           version_index = 1;
2219           /* Don't count anonymous version tag.  */
2220           if (sinfo->info->version_info != NULL
2221               && sinfo->info->version_info->vernum == 0)
2222             version_index = 0;
2223           for (pp = &sinfo->info->version_info;
2224                *pp != NULL;
2225                pp = &(*pp)->next)
2226             ++version_index;
2227           t->vernum = version_index;
2228
2229           *pp = t;
2230
2231           h->verinfo.vertree = t;
2232         }
2233       else if (t == NULL)
2234         {
2235           /* We could not find the version for a symbol when
2236              generating a shared archive.  Return an error.  */
2237           _bfd_error_handler
2238             /* xgettext:c-format */
2239             (_("%B: version node not found for symbol %s"),
2240              info->output_bfd, h->root.root.string);
2241           bfd_set_error (bfd_error_bad_value);
2242           sinfo->failed = TRUE;
2243           return FALSE;
2244         }
2245     }
2246
2247   /* If we don't have a version for this symbol, see if we can find
2248      something.  */
2249   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2250     {
2251       bfd_boolean hide;
2252
2253       h->verinfo.vertree
2254         = bfd_find_version_for_sym (sinfo->info->version_info,
2255                                     h->root.root.string, &hide);
2256       if (h->verinfo.vertree != NULL && hide)
2257         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2258     }
2259
2260   return TRUE;
2261 }
2262 \f
2263 /* Read and swap the relocs from the section indicated by SHDR.  This
2264    may be either a REL or a RELA section.  The relocations are
2265    translated into RELA relocations and stored in INTERNAL_RELOCS,
2266    which should have already been allocated to contain enough space.
2267    The EXTERNAL_RELOCS are a buffer where the external form of the
2268    relocations should be stored.
2269
2270    Returns FALSE if something goes wrong.  */
2271
2272 static bfd_boolean
2273 elf_link_read_relocs_from_section (bfd *abfd,
2274                                    asection *sec,
2275                                    Elf_Internal_Shdr *shdr,
2276                                    void *external_relocs,
2277                                    Elf_Internal_Rela *internal_relocs)
2278 {
2279   const struct elf_backend_data *bed;
2280   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2281   const bfd_byte *erela;
2282   const bfd_byte *erelaend;
2283   Elf_Internal_Rela *irela;
2284   Elf_Internal_Shdr *symtab_hdr;
2285   size_t nsyms;
2286
2287   /* Position ourselves at the start of the section.  */
2288   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2289     return FALSE;
2290
2291   /* Read the relocations.  */
2292   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2293     return FALSE;
2294
2295   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2296   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2297
2298   bed = get_elf_backend_data (abfd);
2299
2300   /* Convert the external relocations to the internal format.  */
2301   if (shdr->sh_entsize == bed->s->sizeof_rel)
2302     swap_in = bed->s->swap_reloc_in;
2303   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2304     swap_in = bed->s->swap_reloca_in;
2305   else
2306     {
2307       bfd_set_error (bfd_error_wrong_format);
2308       return FALSE;
2309     }
2310
2311   erela = (const bfd_byte *) external_relocs;
2312   erelaend = erela + shdr->sh_size;
2313   irela = internal_relocs;
2314   while (erela < erelaend)
2315     {
2316       bfd_vma r_symndx;
2317
2318       (*swap_in) (abfd, erela, irela);
2319       r_symndx = ELF32_R_SYM (irela->r_info);
2320       if (bed->s->arch_size == 64)
2321         r_symndx >>= 24;
2322       if (nsyms > 0)
2323         {
2324           if ((size_t) r_symndx >= nsyms)
2325             {
2326               _bfd_error_handler
2327                 /* xgettext:c-format */
2328                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2329                    " for offset 0x%lx in section `%A'"),
2330                  abfd, sec,
2331                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2332               bfd_set_error (bfd_error_bad_value);
2333               return FALSE;
2334             }
2335         }
2336       else if (r_symndx != STN_UNDEF)
2337         {
2338           _bfd_error_handler
2339             /* xgettext:c-format */
2340             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2341                " when the object file has no symbol table"),
2342              abfd, sec,
2343              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2344           bfd_set_error (bfd_error_bad_value);
2345           return FALSE;
2346         }
2347       irela += bed->s->int_rels_per_ext_rel;
2348       erela += shdr->sh_entsize;
2349     }
2350
2351   return TRUE;
2352 }
2353
2354 /* Read and swap the relocs for a section O.  They may have been
2355    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2356    not NULL, they are used as buffers to read into.  They are known to
2357    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2358    the return value is allocated using either malloc or bfd_alloc,
2359    according to the KEEP_MEMORY argument.  If O has two relocation
2360    sections (both REL and RELA relocations), then the REL_HDR
2361    relocations will appear first in INTERNAL_RELOCS, followed by the
2362    RELA_HDR relocations.  */
2363
2364 Elf_Internal_Rela *
2365 _bfd_elf_link_read_relocs (bfd *abfd,
2366                            asection *o,
2367                            void *external_relocs,
2368                            Elf_Internal_Rela *internal_relocs,
2369                            bfd_boolean keep_memory)
2370 {
2371   void *alloc1 = NULL;
2372   Elf_Internal_Rela *alloc2 = NULL;
2373   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2374   struct bfd_elf_section_data *esdo = elf_section_data (o);
2375   Elf_Internal_Rela *internal_rela_relocs;
2376
2377   if (esdo->relocs != NULL)
2378     return esdo->relocs;
2379
2380   if (o->reloc_count == 0)
2381     return NULL;
2382
2383   if (internal_relocs == NULL)
2384     {
2385       bfd_size_type size;
2386
2387       size = o->reloc_count;
2388       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2389       if (keep_memory)
2390         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2391       else
2392         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2393       if (internal_relocs == NULL)
2394         goto error_return;
2395     }
2396
2397   if (external_relocs == NULL)
2398     {
2399       bfd_size_type size = 0;
2400
2401       if (esdo->rel.hdr)
2402         size += esdo->rel.hdr->sh_size;
2403       if (esdo->rela.hdr)
2404         size += esdo->rela.hdr->sh_size;
2405
2406       alloc1 = bfd_malloc (size);
2407       if (alloc1 == NULL)
2408         goto error_return;
2409       external_relocs = alloc1;
2410     }
2411
2412   internal_rela_relocs = internal_relocs;
2413   if (esdo->rel.hdr)
2414     {
2415       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2416                                               external_relocs,
2417                                               internal_relocs))
2418         goto error_return;
2419       external_relocs = (((bfd_byte *) external_relocs)
2420                          + esdo->rel.hdr->sh_size);
2421       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2422                                * bed->s->int_rels_per_ext_rel);
2423     }
2424
2425   if (esdo->rela.hdr
2426       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2427                                               external_relocs,
2428                                               internal_rela_relocs)))
2429     goto error_return;
2430
2431   /* Cache the results for next time, if we can.  */
2432   if (keep_memory)
2433     esdo->relocs = internal_relocs;
2434
2435   if (alloc1 != NULL)
2436     free (alloc1);
2437
2438   /* Don't free alloc2, since if it was allocated we are passing it
2439      back (under the name of internal_relocs).  */
2440
2441   return internal_relocs;
2442
2443  error_return:
2444   if (alloc1 != NULL)
2445     free (alloc1);
2446   if (alloc2 != NULL)
2447     {
2448       if (keep_memory)
2449         bfd_release (abfd, alloc2);
2450       else
2451         free (alloc2);
2452     }
2453   return NULL;
2454 }
2455
2456 /* Compute the size of, and allocate space for, REL_HDR which is the
2457    section header for a section containing relocations for O.  */
2458
2459 static bfd_boolean
2460 _bfd_elf_link_size_reloc_section (bfd *abfd,
2461                                   struct bfd_elf_section_reloc_data *reldata)
2462 {
2463   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2464
2465   /* That allows us to calculate the size of the section.  */
2466   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2467
2468   /* The contents field must last into write_object_contents, so we
2469      allocate it with bfd_alloc rather than malloc.  Also since we
2470      cannot be sure that the contents will actually be filled in,
2471      we zero the allocated space.  */
2472   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2473   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2474     return FALSE;
2475
2476   if (reldata->hashes == NULL && reldata->count)
2477     {
2478       struct elf_link_hash_entry **p;
2479
2480       p = ((struct elf_link_hash_entry **)
2481            bfd_zmalloc (reldata->count * sizeof (*p)));
2482       if (p == NULL)
2483         return FALSE;
2484
2485       reldata->hashes = p;
2486     }
2487
2488   return TRUE;
2489 }
2490
2491 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2492    originated from the section given by INPUT_REL_HDR) to the
2493    OUTPUT_BFD.  */
2494
2495 bfd_boolean
2496 _bfd_elf_link_output_relocs (bfd *output_bfd,
2497                              asection *input_section,
2498                              Elf_Internal_Shdr *input_rel_hdr,
2499                              Elf_Internal_Rela *internal_relocs,
2500                              struct elf_link_hash_entry **rel_hash
2501                                ATTRIBUTE_UNUSED)
2502 {
2503   Elf_Internal_Rela *irela;
2504   Elf_Internal_Rela *irelaend;
2505   bfd_byte *erel;
2506   struct bfd_elf_section_reloc_data *output_reldata;
2507   asection *output_section;
2508   const struct elf_backend_data *bed;
2509   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2510   struct bfd_elf_section_data *esdo;
2511
2512   output_section = input_section->output_section;
2513
2514   bed = get_elf_backend_data (output_bfd);
2515   esdo = elf_section_data (output_section);
2516   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2517     {
2518       output_reldata = &esdo->rel;
2519       swap_out = bed->s->swap_reloc_out;
2520     }
2521   else if (esdo->rela.hdr
2522            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2523     {
2524       output_reldata = &esdo->rela;
2525       swap_out = bed->s->swap_reloca_out;
2526     }
2527   else
2528     {
2529       _bfd_error_handler
2530         /* xgettext:c-format */
2531         (_("%B: relocation size mismatch in %B section %A"),
2532          output_bfd, input_section->owner, input_section);
2533       bfd_set_error (bfd_error_wrong_format);
2534       return FALSE;
2535     }
2536
2537   erel = output_reldata->hdr->contents;
2538   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2539   irela = internal_relocs;
2540   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2541                       * bed->s->int_rels_per_ext_rel);
2542   while (irela < irelaend)
2543     {
2544       (*swap_out) (output_bfd, irela, erel);
2545       irela += bed->s->int_rels_per_ext_rel;
2546       erel += input_rel_hdr->sh_entsize;
2547     }
2548
2549   /* Bump the counter, so that we know where to add the next set of
2550      relocations.  */
2551   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2552
2553   return TRUE;
2554 }
2555 \f
2556 /* Make weak undefined symbols in PIE dynamic.  */
2557
2558 bfd_boolean
2559 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2560                                  struct elf_link_hash_entry *h)
2561 {
2562   if (bfd_link_pie (info)
2563       && h->dynindx == -1
2564       && h->root.type == bfd_link_hash_undefweak)
2565     return bfd_elf_link_record_dynamic_symbol (info, h);
2566
2567   return TRUE;
2568 }
2569
2570 /* Fix up the flags for a symbol.  This handles various cases which
2571    can only be fixed after all the input files are seen.  This is
2572    currently called by both adjust_dynamic_symbol and
2573    assign_sym_version, which is unnecessary but perhaps more robust in
2574    the face of future changes.  */
2575
2576 static bfd_boolean
2577 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2578                            struct elf_info_failed *eif)
2579 {
2580   const struct elf_backend_data *bed;
2581
2582   /* If this symbol was mentioned in a non-ELF file, try to set
2583      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2584      permit a non-ELF file to correctly refer to a symbol defined in
2585      an ELF dynamic object.  */
2586   if (h->non_elf)
2587     {
2588       while (h->root.type == bfd_link_hash_indirect)
2589         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2590
2591       if (h->root.type != bfd_link_hash_defined
2592           && h->root.type != bfd_link_hash_defweak)
2593         {
2594           h->ref_regular = 1;
2595           h->ref_regular_nonweak = 1;
2596         }
2597       else
2598         {
2599           if (h->root.u.def.section->owner != NULL
2600               && (bfd_get_flavour (h->root.u.def.section->owner)
2601                   == bfd_target_elf_flavour))
2602             {
2603               h->ref_regular = 1;
2604               h->ref_regular_nonweak = 1;
2605             }
2606           else
2607             h->def_regular = 1;
2608         }
2609
2610       if (h->dynindx == -1
2611           && (h->def_dynamic
2612               || h->ref_dynamic))
2613         {
2614           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2615             {
2616               eif->failed = TRUE;
2617               return FALSE;
2618             }
2619         }
2620     }
2621   else
2622     {
2623       /* Unfortunately, NON_ELF is only correct if the symbol
2624          was first seen in a non-ELF file.  Fortunately, if the symbol
2625          was first seen in an ELF file, we're probably OK unless the
2626          symbol was defined in a non-ELF file.  Catch that case here.
2627          FIXME: We're still in trouble if the symbol was first seen in
2628          a dynamic object, and then later in a non-ELF regular object.  */
2629       if ((h->root.type == bfd_link_hash_defined
2630            || h->root.type == bfd_link_hash_defweak)
2631           && !h->def_regular
2632           && (h->root.u.def.section->owner != NULL
2633               ? (bfd_get_flavour (h->root.u.def.section->owner)
2634                  != bfd_target_elf_flavour)
2635               : (bfd_is_abs_section (h->root.u.def.section)
2636                  && !h->def_dynamic)))
2637         h->def_regular = 1;
2638     }
2639
2640   /* Backend specific symbol fixup.  */
2641   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2642   if (bed->elf_backend_fixup_symbol
2643       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2644     return FALSE;
2645
2646   /* If this is a final link, and the symbol was defined as a common
2647      symbol in a regular object file, and there was no definition in
2648      any dynamic object, then the linker will have allocated space for
2649      the symbol in a common section but the DEF_REGULAR
2650      flag will not have been set.  */
2651   if (h->root.type == bfd_link_hash_defined
2652       && !h->def_regular
2653       && h->ref_regular
2654       && !h->def_dynamic
2655       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2656     h->def_regular = 1;
2657
2658   /* If -Bsymbolic was used (which means to bind references to global
2659      symbols to the definition within the shared object), and this
2660      symbol was defined in a regular object, then it actually doesn't
2661      need a PLT entry.  Likewise, if the symbol has non-default
2662      visibility.  If the symbol has hidden or internal visibility, we
2663      will force it local.  */
2664   if (h->needs_plt
2665       && bfd_link_pic (eif->info)
2666       && is_elf_hash_table (eif->info->hash)
2667       && (SYMBOLIC_BIND (eif->info, h)
2668           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2669       && h->def_regular)
2670     {
2671       bfd_boolean force_local;
2672
2673       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2674                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2675       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2676     }
2677
2678   /* If a weak undefined symbol has non-default visibility, we also
2679      hide it from the dynamic linker.  */
2680   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2681       && h->root.type == bfd_link_hash_undefweak)
2682     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2683
2684   /* If this is a weak defined symbol in a dynamic object, and we know
2685      the real definition in the dynamic object, copy interesting flags
2686      over to the real definition.  */
2687   if (h->u.weakdef != NULL)
2688     {
2689       /* If the real definition is defined by a regular object file,
2690          don't do anything special.  See the longer description in
2691          _bfd_elf_adjust_dynamic_symbol, below.  */
2692       if (h->u.weakdef->def_regular)
2693         h->u.weakdef = NULL;
2694       else
2695         {
2696           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2697
2698           while (h->root.type == bfd_link_hash_indirect)
2699             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2700
2701           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2702                       || h->root.type == bfd_link_hash_defweak);
2703           BFD_ASSERT (weakdef->def_dynamic);
2704           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2705                       || weakdef->root.type == bfd_link_hash_defweak);
2706           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2707         }
2708     }
2709
2710   return TRUE;
2711 }
2712
2713 /* Make the backend pick a good value for a dynamic symbol.  This is
2714    called via elf_link_hash_traverse, and also calls itself
2715    recursively.  */
2716
2717 static bfd_boolean
2718 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2719 {
2720   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2721   bfd *dynobj;
2722   const struct elf_backend_data *bed;
2723
2724   if (! is_elf_hash_table (eif->info->hash))
2725     return FALSE;
2726
2727   /* Ignore indirect symbols.  These are added by the versioning code.  */
2728   if (h->root.type == bfd_link_hash_indirect)
2729     return TRUE;
2730
2731   /* Fix the symbol flags.  */
2732   if (! _bfd_elf_fix_symbol_flags (h, eif))
2733     return FALSE;
2734
2735   /* If this symbol does not require a PLT entry, and it is not
2736      defined by a dynamic object, or is not referenced by a regular
2737      object, ignore it.  We do have to handle a weak defined symbol,
2738      even if no regular object refers to it, if we decided to add it
2739      to the dynamic symbol table.  FIXME: Do we normally need to worry
2740      about symbols which are defined by one dynamic object and
2741      referenced by another one?  */
2742   if (!h->needs_plt
2743       && h->type != STT_GNU_IFUNC
2744       && (h->def_regular
2745           || !h->def_dynamic
2746           || (!h->ref_regular
2747               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2748     {
2749       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2750       return TRUE;
2751     }
2752
2753   /* If we've already adjusted this symbol, don't do it again.  This
2754      can happen via a recursive call.  */
2755   if (h->dynamic_adjusted)
2756     return TRUE;
2757
2758   /* Don't look at this symbol again.  Note that we must set this
2759      after checking the above conditions, because we may look at a
2760      symbol once, decide not to do anything, and then get called
2761      recursively later after REF_REGULAR is set below.  */
2762   h->dynamic_adjusted = 1;
2763
2764   /* If this is a weak definition, and we know a real definition, and
2765      the real symbol is not itself defined by a regular object file,
2766      then get a good value for the real definition.  We handle the
2767      real symbol first, for the convenience of the backend routine.
2768
2769      Note that there is a confusing case here.  If the real definition
2770      is defined by a regular object file, we don't get the real symbol
2771      from the dynamic object, but we do get the weak symbol.  If the
2772      processor backend uses a COPY reloc, then if some routine in the
2773      dynamic object changes the real symbol, we will not see that
2774      change in the corresponding weak symbol.  This is the way other
2775      ELF linkers work as well, and seems to be a result of the shared
2776      library model.
2777
2778      I will clarify this issue.  Most SVR4 shared libraries define the
2779      variable _timezone and define timezone as a weak synonym.  The
2780      tzset call changes _timezone.  If you write
2781        extern int timezone;
2782        int _timezone = 5;
2783        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2784      you might expect that, since timezone is a synonym for _timezone,
2785      the same number will print both times.  However, if the processor
2786      backend uses a COPY reloc, then actually timezone will be copied
2787      into your process image, and, since you define _timezone
2788      yourself, _timezone will not.  Thus timezone and _timezone will
2789      wind up at different memory locations.  The tzset call will set
2790      _timezone, leaving timezone unchanged.  */
2791
2792   if (h->u.weakdef != NULL)
2793     {
2794       /* If we get to this point, there is an implicit reference to
2795          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2796       h->u.weakdef->ref_regular = 1;
2797
2798       /* Ensure that the backend adjust_dynamic_symbol function sees
2799          H->U.WEAKDEF before H by recursively calling ourselves.  */
2800       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2801         return FALSE;
2802     }
2803
2804   /* If a symbol has no type and no size and does not require a PLT
2805      entry, then we are probably about to do the wrong thing here: we
2806      are probably going to create a COPY reloc for an empty object.
2807      This case can arise when a shared object is built with assembly
2808      code, and the assembly code fails to set the symbol type.  */
2809   if (h->size == 0
2810       && h->type == STT_NOTYPE
2811       && !h->needs_plt)
2812     _bfd_error_handler
2813       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2814        h->root.root.string);
2815
2816   dynobj = elf_hash_table (eif->info)->dynobj;
2817   bed = get_elf_backend_data (dynobj);
2818
2819   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2820     {
2821       eif->failed = TRUE;
2822       return FALSE;
2823     }
2824
2825   return TRUE;
2826 }
2827
2828 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2829    DYNBSS.  */
2830
2831 bfd_boolean
2832 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2833                               struct elf_link_hash_entry *h,
2834                               asection *dynbss)
2835 {
2836   unsigned int power_of_two;
2837   bfd_vma mask;
2838   asection *sec = h->root.u.def.section;
2839
2840   /* The section aligment of definition is the maximum alignment
2841      requirement of symbols defined in the section.  Since we don't
2842      know the symbol alignment requirement, we start with the
2843      maximum alignment and check low bits of the symbol address
2844      for the minimum alignment.  */
2845   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2846   mask = ((bfd_vma) 1 << power_of_two) - 1;
2847   while ((h->root.u.def.value & mask) != 0)
2848     {
2849        mask >>= 1;
2850        --power_of_two;
2851     }
2852
2853   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2854                                                 dynbss))
2855     {
2856       /* Adjust the section alignment if needed.  */
2857       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2858                                        power_of_two))
2859         return FALSE;
2860     }
2861
2862   /* We make sure that the symbol will be aligned properly.  */
2863   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2864
2865   /* Define the symbol as being at this point in DYNBSS.  */
2866   h->root.u.def.section = dynbss;
2867   h->root.u.def.value = dynbss->size;
2868
2869   /* Increment the size of DYNBSS to make room for the symbol.  */
2870   dynbss->size += h->size;
2871
2872   /* No error if extern_protected_data is true.  */
2873   if (h->protected_def
2874       && (!info->extern_protected_data
2875           || (info->extern_protected_data < 0
2876               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2877     info->callbacks->einfo
2878       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2879        h->root.root.string);
2880
2881   return TRUE;
2882 }
2883
2884 /* Adjust all external symbols pointing into SEC_MERGE sections
2885    to reflect the object merging within the sections.  */
2886
2887 static bfd_boolean
2888 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2889 {
2890   asection *sec;
2891
2892   if ((h->root.type == bfd_link_hash_defined
2893        || h->root.type == bfd_link_hash_defweak)
2894       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2895       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2896     {
2897       bfd *output_bfd = (bfd *) data;
2898
2899       h->root.u.def.value =
2900         _bfd_merged_section_offset (output_bfd,
2901                                     &h->root.u.def.section,
2902                                     elf_section_data (sec)->sec_info,
2903                                     h->root.u.def.value);
2904     }
2905
2906   return TRUE;
2907 }
2908
2909 /* Returns false if the symbol referred to by H should be considered
2910    to resolve local to the current module, and true if it should be
2911    considered to bind dynamically.  */
2912
2913 bfd_boolean
2914 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2915                            struct bfd_link_info *info,
2916                            bfd_boolean not_local_protected)
2917 {
2918   bfd_boolean binding_stays_local_p;
2919   const struct elf_backend_data *bed;
2920   struct elf_link_hash_table *hash_table;
2921
2922   if (h == NULL)
2923     return FALSE;
2924
2925   while (h->root.type == bfd_link_hash_indirect
2926          || h->root.type == bfd_link_hash_warning)
2927     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2928
2929   /* If it was forced local, then clearly it's not dynamic.  */
2930   if (h->dynindx == -1)
2931     return FALSE;
2932   if (h->forced_local)
2933     return FALSE;
2934
2935   /* Identify the cases where name binding rules say that a
2936      visible symbol resolves locally.  */
2937   binding_stays_local_p = (bfd_link_executable (info)
2938                            || SYMBOLIC_BIND (info, h));
2939
2940   switch (ELF_ST_VISIBILITY (h->other))
2941     {
2942     case STV_INTERNAL:
2943     case STV_HIDDEN:
2944       return FALSE;
2945
2946     case STV_PROTECTED:
2947       hash_table = elf_hash_table (info);
2948       if (!is_elf_hash_table (hash_table))
2949         return FALSE;
2950
2951       bed = get_elf_backend_data (hash_table->dynobj);
2952
2953       /* Proper resolution for function pointer equality may require
2954          that these symbols perhaps be resolved dynamically, even though
2955          we should be resolving them to the current module.  */
2956       if (!not_local_protected || !bed->is_function_type (h->type))
2957         binding_stays_local_p = TRUE;
2958       break;
2959
2960     default:
2961       break;
2962     }
2963
2964   /* If it isn't defined locally, then clearly it's dynamic.  */
2965   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2966     return TRUE;
2967
2968   /* Otherwise, the symbol is dynamic if binding rules don't tell
2969      us that it remains local.  */
2970   return !binding_stays_local_p;
2971 }
2972
2973 /* Return true if the symbol referred to by H should be considered
2974    to resolve local to the current module, and false otherwise.  Differs
2975    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2976    undefined symbols.  The two functions are virtually identical except
2977    for the place where forced_local and dynindx == -1 are tested.  If
2978    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2979    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2980    the symbol is local only for defined symbols.
2981    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2982    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2983    treatment of undefined weak symbols.  For those that do not make
2984    undefined weak symbols dynamic, both functions may return false.  */
2985
2986 bfd_boolean
2987 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2988                               struct bfd_link_info *info,
2989                               bfd_boolean local_protected)
2990 {
2991   const struct elf_backend_data *bed;
2992   struct elf_link_hash_table *hash_table;
2993
2994   /* If it's a local sym, of course we resolve locally.  */
2995   if (h == NULL)
2996     return TRUE;
2997
2998   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2999   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3000       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3001     return TRUE;
3002
3003   /* Common symbols that become definitions don't get the DEF_REGULAR
3004      flag set, so test it first, and don't bail out.  */
3005   if (ELF_COMMON_DEF_P (h))
3006     /* Do nothing.  */;
3007   /* If we don't have a definition in a regular file, then we can't
3008      resolve locally.  The sym is either undefined or dynamic.  */
3009   else if (!h->def_regular)
3010     return FALSE;
3011
3012   /* Forced local symbols resolve locally.  */
3013   if (h->forced_local)
3014     return TRUE;
3015
3016   /* As do non-dynamic symbols.  */
3017   if (h->dynindx == -1)
3018     return TRUE;
3019
3020   /* At this point, we know the symbol is defined and dynamic.  In an
3021      executable it must resolve locally, likewise when building symbolic
3022      shared libraries.  */
3023   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3024     return TRUE;
3025
3026   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3027      with default visibility might not resolve locally.  */
3028   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3029     return FALSE;
3030
3031   hash_table = elf_hash_table (info);
3032   if (!is_elf_hash_table (hash_table))
3033     return TRUE;
3034
3035   bed = get_elf_backend_data (hash_table->dynobj);
3036
3037   /* If extern_protected_data is false, STV_PROTECTED non-function
3038      symbols are local.  */
3039   if ((!info->extern_protected_data
3040        || (info->extern_protected_data < 0
3041            && !bed->extern_protected_data))
3042       && !bed->is_function_type (h->type))
3043     return TRUE;
3044
3045   /* Function pointer equality tests may require that STV_PROTECTED
3046      symbols be treated as dynamic symbols.  If the address of a
3047      function not defined in an executable is set to that function's
3048      plt entry in the executable, then the address of the function in
3049      a shared library must also be the plt entry in the executable.  */
3050   return local_protected;
3051 }
3052
3053 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3054    aligned.  Returns the first TLS output section.  */
3055
3056 struct bfd_section *
3057 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3058 {
3059   struct bfd_section *sec, *tls;
3060   unsigned int align = 0;
3061
3062   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3063     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3064       break;
3065   tls = sec;
3066
3067   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3068     if (sec->alignment_power > align)
3069       align = sec->alignment_power;
3070
3071   elf_hash_table (info)->tls_sec = tls;
3072
3073   /* Ensure the alignment of the first section is the largest alignment,
3074      so that the tls segment starts aligned.  */
3075   if (tls != NULL)
3076     tls->alignment_power = align;
3077
3078   return tls;
3079 }
3080
3081 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3082 static bfd_boolean
3083 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3084                                   Elf_Internal_Sym *sym)
3085 {
3086   const struct elf_backend_data *bed;
3087
3088   /* Local symbols do not count, but target specific ones might.  */
3089   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3090       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3091     return FALSE;
3092
3093   bed = get_elf_backend_data (abfd);
3094   /* Function symbols do not count.  */
3095   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3096     return FALSE;
3097
3098   /* If the section is undefined, then so is the symbol.  */
3099   if (sym->st_shndx == SHN_UNDEF)
3100     return FALSE;
3101
3102   /* If the symbol is defined in the common section, then
3103      it is a common definition and so does not count.  */
3104   if (bed->common_definition (sym))
3105     return FALSE;
3106
3107   /* If the symbol is in a target specific section then we
3108      must rely upon the backend to tell us what it is.  */
3109   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3110     /* FIXME - this function is not coded yet:
3111
3112        return _bfd_is_global_symbol_definition (abfd, sym);
3113
3114        Instead for now assume that the definition is not global,
3115        Even if this is wrong, at least the linker will behave
3116        in the same way that it used to do.  */
3117     return FALSE;
3118
3119   return TRUE;
3120 }
3121
3122 /* Search the symbol table of the archive element of the archive ABFD
3123    whose archive map contains a mention of SYMDEF, and determine if
3124    the symbol is defined in this element.  */
3125 static bfd_boolean
3126 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3127 {
3128   Elf_Internal_Shdr * hdr;
3129   size_t symcount;
3130   size_t extsymcount;
3131   size_t extsymoff;
3132   Elf_Internal_Sym *isymbuf;
3133   Elf_Internal_Sym *isym;
3134   Elf_Internal_Sym *isymend;
3135   bfd_boolean result;
3136
3137   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3138   if (abfd == NULL)
3139     return FALSE;
3140
3141   if (! bfd_check_format (abfd, bfd_object))
3142     return FALSE;
3143
3144   /* Select the appropriate symbol table.  If we don't know if the
3145      object file is an IR object, give linker LTO plugin a chance to
3146      get the correct symbol table.  */
3147   if (abfd->plugin_format == bfd_plugin_yes
3148 #if BFD_SUPPORTS_PLUGINS
3149       || (abfd->plugin_format == bfd_plugin_unknown
3150           && bfd_link_plugin_object_p (abfd))
3151 #endif
3152       )
3153     {
3154       /* Use the IR symbol table if the object has been claimed by
3155          plugin.  */
3156       abfd = abfd->plugin_dummy_bfd;
3157       hdr = &elf_tdata (abfd)->symtab_hdr;
3158     }
3159   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3160     hdr = &elf_tdata (abfd)->symtab_hdr;
3161   else
3162     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3163
3164   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3165
3166   /* The sh_info field of the symtab header tells us where the
3167      external symbols start.  We don't care about the local symbols.  */
3168   if (elf_bad_symtab (abfd))
3169     {
3170       extsymcount = symcount;
3171       extsymoff = 0;
3172     }
3173   else
3174     {
3175       extsymcount = symcount - hdr->sh_info;
3176       extsymoff = hdr->sh_info;
3177     }
3178
3179   if (extsymcount == 0)
3180     return FALSE;
3181
3182   /* Read in the symbol table.  */
3183   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3184                                   NULL, NULL, NULL);
3185   if (isymbuf == NULL)
3186     return FALSE;
3187
3188   /* Scan the symbol table looking for SYMDEF.  */
3189   result = FALSE;
3190   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3191     {
3192       const char *name;
3193
3194       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3195                                               isym->st_name);
3196       if (name == NULL)
3197         break;
3198
3199       if (strcmp (name, symdef->name) == 0)
3200         {
3201           result = is_global_data_symbol_definition (abfd, isym);
3202           break;
3203         }
3204     }
3205
3206   free (isymbuf);
3207
3208   return result;
3209 }
3210 \f
3211 /* Add an entry to the .dynamic table.  */
3212
3213 bfd_boolean
3214 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3215                             bfd_vma tag,
3216                             bfd_vma val)
3217 {
3218   struct elf_link_hash_table *hash_table;
3219   const struct elf_backend_data *bed;
3220   asection *s;
3221   bfd_size_type newsize;
3222   bfd_byte *newcontents;
3223   Elf_Internal_Dyn dyn;
3224
3225   hash_table = elf_hash_table (info);
3226   if (! is_elf_hash_table (hash_table))
3227     return FALSE;
3228
3229   bed = get_elf_backend_data (hash_table->dynobj);
3230   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3231   BFD_ASSERT (s != NULL);
3232
3233   newsize = s->size + bed->s->sizeof_dyn;
3234   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3235   if (newcontents == NULL)
3236     return FALSE;
3237
3238   dyn.d_tag = tag;
3239   dyn.d_un.d_val = val;
3240   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3241
3242   s->size = newsize;
3243   s->contents = newcontents;
3244
3245   return TRUE;
3246 }
3247
3248 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3249    otherwise just check whether one already exists.  Returns -1 on error,
3250    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3251
3252 static int
3253 elf_add_dt_needed_tag (bfd *abfd,
3254                        struct bfd_link_info *info,
3255                        const char *soname,
3256                        bfd_boolean do_it)
3257 {
3258   struct elf_link_hash_table *hash_table;
3259   size_t strindex;
3260
3261   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3262     return -1;
3263
3264   hash_table = elf_hash_table (info);
3265   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3266   if (strindex == (size_t) -1)
3267     return -1;
3268
3269   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3270     {
3271       asection *sdyn;
3272       const struct elf_backend_data *bed;
3273       bfd_byte *extdyn;
3274
3275       bed = get_elf_backend_data (hash_table->dynobj);
3276       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3277       if (sdyn != NULL)
3278         for (extdyn = sdyn->contents;
3279              extdyn < sdyn->contents + sdyn->size;
3280              extdyn += bed->s->sizeof_dyn)
3281           {
3282             Elf_Internal_Dyn dyn;
3283
3284             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3285             if (dyn.d_tag == DT_NEEDED
3286                 && dyn.d_un.d_val == strindex)
3287               {
3288                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3289                 return 1;
3290               }
3291           }
3292     }
3293
3294   if (do_it)
3295     {
3296       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3297         return -1;
3298
3299       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3300         return -1;
3301     }
3302   else
3303     /* We were just checking for existence of the tag.  */
3304     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3305
3306   return 0;
3307 }
3308
3309 /* Return true if SONAME is on the needed list between NEEDED and STOP
3310    (or the end of list if STOP is NULL), and needed by a library that
3311    will be loaded.  */
3312
3313 static bfd_boolean
3314 on_needed_list (const char *soname,
3315                 struct bfd_link_needed_list *needed,
3316                 struct bfd_link_needed_list *stop)
3317 {
3318   struct bfd_link_needed_list *look;
3319   for (look = needed; look != stop; look = look->next)
3320     if (strcmp (soname, look->name) == 0
3321         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3322             /* If needed by a library that itself is not directly
3323                needed, recursively check whether that library is
3324                indirectly needed.  Since we add DT_NEEDED entries to
3325                the end of the list, library dependencies appear after
3326                the library.  Therefore search prior to the current
3327                LOOK, preventing possible infinite recursion.  */
3328             || on_needed_list (elf_dt_name (look->by), needed, look)))
3329       return TRUE;
3330
3331   return FALSE;
3332 }
3333
3334 /* Sort symbol by value, section, and size.  */
3335 static int
3336 elf_sort_symbol (const void *arg1, const void *arg2)
3337 {
3338   const struct elf_link_hash_entry *h1;
3339   const struct elf_link_hash_entry *h2;
3340   bfd_signed_vma vdiff;
3341
3342   h1 = *(const struct elf_link_hash_entry **) arg1;
3343   h2 = *(const struct elf_link_hash_entry **) arg2;
3344   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3345   if (vdiff != 0)
3346     return vdiff > 0 ? 1 : -1;
3347   else
3348     {
3349       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3350       if (sdiff != 0)
3351         return sdiff > 0 ? 1 : -1;
3352     }
3353   vdiff = h1->size - h2->size;
3354   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3355 }
3356
3357 /* This function is used to adjust offsets into .dynstr for
3358    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3359
3360 static bfd_boolean
3361 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3362 {
3363   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3364
3365   if (h->dynindx != -1)
3366     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3367   return TRUE;
3368 }
3369
3370 /* Assign string offsets in .dynstr, update all structures referencing
3371    them.  */
3372
3373 static bfd_boolean
3374 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3375 {
3376   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3377   struct elf_link_local_dynamic_entry *entry;
3378   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3379   bfd *dynobj = hash_table->dynobj;
3380   asection *sdyn;
3381   bfd_size_type size;
3382   const struct elf_backend_data *bed;
3383   bfd_byte *extdyn;
3384
3385   _bfd_elf_strtab_finalize (dynstr);
3386   size = _bfd_elf_strtab_size (dynstr);
3387
3388   bed = get_elf_backend_data (dynobj);
3389   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3390   BFD_ASSERT (sdyn != NULL);
3391
3392   /* Update all .dynamic entries referencing .dynstr strings.  */
3393   for (extdyn = sdyn->contents;
3394        extdyn < sdyn->contents + sdyn->size;
3395        extdyn += bed->s->sizeof_dyn)
3396     {
3397       Elf_Internal_Dyn dyn;
3398
3399       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3400       switch (dyn.d_tag)
3401         {
3402         case DT_STRSZ:
3403           dyn.d_un.d_val = size;
3404           break;
3405         case DT_NEEDED:
3406         case DT_SONAME:
3407         case DT_RPATH:
3408         case DT_RUNPATH:
3409         case DT_FILTER:
3410         case DT_AUXILIARY:
3411         case DT_AUDIT:
3412         case DT_DEPAUDIT:
3413           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3414           break;
3415         default:
3416           continue;
3417         }
3418       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3419     }
3420
3421   /* Now update local dynamic symbols.  */
3422   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3423     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3424                                                   entry->isym.st_name);
3425
3426   /* And the rest of dynamic symbols.  */
3427   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3428
3429   /* Adjust version definitions.  */
3430   if (elf_tdata (output_bfd)->cverdefs)
3431     {
3432       asection *s;
3433       bfd_byte *p;
3434       size_t i;
3435       Elf_Internal_Verdef def;
3436       Elf_Internal_Verdaux defaux;
3437
3438       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3439       p = s->contents;
3440       do
3441         {
3442           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3443                                    &def);
3444           p += sizeof (Elf_External_Verdef);
3445           if (def.vd_aux != sizeof (Elf_External_Verdef))
3446             continue;
3447           for (i = 0; i < def.vd_cnt; ++i)
3448             {
3449               _bfd_elf_swap_verdaux_in (output_bfd,
3450                                         (Elf_External_Verdaux *) p, &defaux);
3451               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3452                                                         defaux.vda_name);
3453               _bfd_elf_swap_verdaux_out (output_bfd,
3454                                          &defaux, (Elf_External_Verdaux *) p);
3455               p += sizeof (Elf_External_Verdaux);
3456             }
3457         }
3458       while (def.vd_next);
3459     }
3460
3461   /* Adjust version references.  */
3462   if (elf_tdata (output_bfd)->verref)
3463     {
3464       asection *s;
3465       bfd_byte *p;
3466       size_t i;
3467       Elf_Internal_Verneed need;
3468       Elf_Internal_Vernaux needaux;
3469
3470       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3471       p = s->contents;
3472       do
3473         {
3474           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3475                                     &need);
3476           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3477           _bfd_elf_swap_verneed_out (output_bfd, &need,
3478                                      (Elf_External_Verneed *) p);
3479           p += sizeof (Elf_External_Verneed);
3480           for (i = 0; i < need.vn_cnt; ++i)
3481             {
3482               _bfd_elf_swap_vernaux_in (output_bfd,
3483                                         (Elf_External_Vernaux *) p, &needaux);
3484               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3485                                                          needaux.vna_name);
3486               _bfd_elf_swap_vernaux_out (output_bfd,
3487                                          &needaux,
3488                                          (Elf_External_Vernaux *) p);
3489               p += sizeof (Elf_External_Vernaux);
3490             }
3491         }
3492       while (need.vn_next);
3493     }
3494
3495   return TRUE;
3496 }
3497 \f
3498 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3499    The default is to only match when the INPUT and OUTPUT are exactly
3500    the same target.  */
3501
3502 bfd_boolean
3503 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3504                                     const bfd_target *output)
3505 {
3506   return input == output;
3507 }
3508
3509 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3510    This version is used when different targets for the same architecture
3511    are virtually identical.  */
3512
3513 bfd_boolean
3514 _bfd_elf_relocs_compatible (const bfd_target *input,
3515                             const bfd_target *output)
3516 {
3517   const struct elf_backend_data *obed, *ibed;
3518
3519   if (input == output)
3520     return TRUE;
3521
3522   ibed = xvec_get_elf_backend_data (input);
3523   obed = xvec_get_elf_backend_data (output);
3524
3525   if (ibed->arch != obed->arch)
3526     return FALSE;
3527
3528   /* If both backends are using this function, deem them compatible.  */
3529   return ibed->relocs_compatible == obed->relocs_compatible;
3530 }
3531
3532 /* Make a special call to the linker "notice" function to tell it that
3533    we are about to handle an as-needed lib, or have finished
3534    processing the lib.  */
3535
3536 bfd_boolean
3537 _bfd_elf_notice_as_needed (bfd *ibfd,
3538                            struct bfd_link_info *info,
3539                            enum notice_asneeded_action act)
3540 {
3541   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3542 }
3543
3544 /* Check relocations an ELF object file.  */
3545
3546 bfd_boolean
3547 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3548 {
3549   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3550   struct elf_link_hash_table *htab = elf_hash_table (info);
3551
3552   /* If this object is the same format as the output object, and it is
3553      not a shared library, then let the backend look through the
3554      relocs.
3555
3556      This is required to build global offset table entries and to
3557      arrange for dynamic relocs.  It is not required for the
3558      particular common case of linking non PIC code, even when linking
3559      against shared libraries, but unfortunately there is no way of
3560      knowing whether an object file has been compiled PIC or not.
3561      Looking through the relocs is not particularly time consuming.
3562      The problem is that we must either (1) keep the relocs in memory,
3563      which causes the linker to require additional runtime memory or
3564      (2) read the relocs twice from the input file, which wastes time.
3565      This would be a good case for using mmap.
3566
3567      I have no idea how to handle linking PIC code into a file of a
3568      different format.  It probably can't be done.  */
3569   if ((abfd->flags & DYNAMIC) == 0
3570       && is_elf_hash_table (htab)
3571       && bed->check_relocs != NULL
3572       && elf_object_id (abfd) == elf_hash_table_id (htab)
3573       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3574     {
3575       asection *o;
3576
3577       for (o = abfd->sections; o != NULL; o = o->next)
3578         {
3579           Elf_Internal_Rela *internal_relocs;
3580           bfd_boolean ok;
3581
3582           /* Don't check relocations in excluded sections.  */
3583           if ((o->flags & SEC_RELOC) == 0
3584               || (o->flags & SEC_EXCLUDE) != 0
3585               || o->reloc_count == 0
3586               || ((info->strip == strip_all || info->strip == strip_debugger)
3587                   && (o->flags & SEC_DEBUGGING) != 0)
3588               || bfd_is_abs_section (o->output_section))
3589             continue;
3590
3591           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3592                                                        info->keep_memory);
3593           if (internal_relocs == NULL)
3594             return FALSE;
3595
3596           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3597
3598           if (elf_section_data (o)->relocs != internal_relocs)
3599             free (internal_relocs);
3600
3601           if (! ok)
3602             return FALSE;
3603         }
3604     }
3605
3606   return TRUE;
3607 }
3608
3609 /* Add symbols from an ELF object file to the linker hash table.  */
3610
3611 static bfd_boolean
3612 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3613 {
3614   Elf_Internal_Ehdr *ehdr;
3615   Elf_Internal_Shdr *hdr;
3616   size_t symcount;
3617   size_t extsymcount;
3618   size_t extsymoff;
3619   struct elf_link_hash_entry **sym_hash;
3620   bfd_boolean dynamic;
3621   Elf_External_Versym *extversym = NULL;
3622   Elf_External_Versym *ever;
3623   struct elf_link_hash_entry *weaks;
3624   struct elf_link_hash_entry **nondeflt_vers = NULL;
3625   size_t nondeflt_vers_cnt = 0;
3626   Elf_Internal_Sym *isymbuf = NULL;
3627   Elf_Internal_Sym *isym;
3628   Elf_Internal_Sym *isymend;
3629   const struct elf_backend_data *bed;
3630   bfd_boolean add_needed;
3631   struct elf_link_hash_table *htab;
3632   bfd_size_type amt;
3633   void *alloc_mark = NULL;
3634   struct bfd_hash_entry **old_table = NULL;
3635   unsigned int old_size = 0;
3636   unsigned int old_count = 0;
3637   void *old_tab = NULL;
3638   void *old_ent;
3639   struct bfd_link_hash_entry *old_undefs = NULL;
3640   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3641   void *old_strtab = NULL;
3642   size_t tabsize = 0;
3643   asection *s;
3644   bfd_boolean just_syms;
3645
3646   htab = elf_hash_table (info);
3647   bed = get_elf_backend_data (abfd);
3648
3649   if ((abfd->flags & DYNAMIC) == 0)
3650     dynamic = FALSE;
3651   else
3652     {
3653       dynamic = TRUE;
3654
3655       /* You can't use -r against a dynamic object.  Also, there's no
3656          hope of using a dynamic object which does not exactly match
3657          the format of the output file.  */
3658       if (bfd_link_relocatable (info)
3659           || !is_elf_hash_table (htab)
3660           || info->output_bfd->xvec != abfd->xvec)
3661         {
3662           if (bfd_link_relocatable (info))
3663             bfd_set_error (bfd_error_invalid_operation);
3664           else
3665             bfd_set_error (bfd_error_wrong_format);
3666           goto error_return;
3667         }
3668     }
3669
3670   ehdr = elf_elfheader (abfd);
3671   if (info->warn_alternate_em
3672       && bed->elf_machine_code != ehdr->e_machine
3673       && ((bed->elf_machine_alt1 != 0
3674            && ehdr->e_machine == bed->elf_machine_alt1)
3675           || (bed->elf_machine_alt2 != 0
3676               && ehdr->e_machine == bed->elf_machine_alt2)))
3677     info->callbacks->einfo
3678       /* xgettext:c-format */
3679       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3680        ehdr->e_machine, abfd, bed->elf_machine_code);
3681
3682   /* As a GNU extension, any input sections which are named
3683      .gnu.warning.SYMBOL are treated as warning symbols for the given
3684      symbol.  This differs from .gnu.warning sections, which generate
3685      warnings when they are included in an output file.  */
3686   /* PR 12761: Also generate this warning when building shared libraries.  */
3687   for (s = abfd->sections; s != NULL; s = s->next)
3688     {
3689       const char *name;
3690
3691       name = bfd_get_section_name (abfd, s);
3692       if (CONST_STRNEQ (name, ".gnu.warning."))
3693         {
3694           char *msg;
3695           bfd_size_type sz;
3696
3697           name += sizeof ".gnu.warning." - 1;
3698
3699           /* If this is a shared object, then look up the symbol
3700              in the hash table.  If it is there, and it is already
3701              been defined, then we will not be using the entry
3702              from this shared object, so we don't need to warn.
3703              FIXME: If we see the definition in a regular object
3704              later on, we will warn, but we shouldn't.  The only
3705              fix is to keep track of what warnings we are supposed
3706              to emit, and then handle them all at the end of the
3707              link.  */
3708           if (dynamic)
3709             {
3710               struct elf_link_hash_entry *h;
3711
3712               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3713
3714               /* FIXME: What about bfd_link_hash_common?  */
3715               if (h != NULL
3716                   && (h->root.type == bfd_link_hash_defined
3717                       || h->root.type == bfd_link_hash_defweak))
3718                 continue;
3719             }
3720
3721           sz = s->size;
3722           msg = (char *) bfd_alloc (abfd, sz + 1);
3723           if (msg == NULL)
3724             goto error_return;
3725
3726           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3727             goto error_return;
3728
3729           msg[sz] = '\0';
3730
3731           if (! (_bfd_generic_link_add_one_symbol
3732                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3733                   FALSE, bed->collect, NULL)))
3734             goto error_return;
3735
3736           if (bfd_link_executable (info))
3737             {
3738               /* Clobber the section size so that the warning does
3739                  not get copied into the output file.  */
3740               s->size = 0;
3741
3742               /* Also set SEC_EXCLUDE, so that symbols defined in
3743                  the warning section don't get copied to the output.  */
3744               s->flags |= SEC_EXCLUDE;
3745             }
3746         }
3747     }
3748
3749   just_syms = ((s = abfd->sections) != NULL
3750                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3751
3752   add_needed = TRUE;
3753   if (! dynamic)
3754     {
3755       /* If we are creating a shared library, create all the dynamic
3756          sections immediately.  We need to attach them to something,
3757          so we attach them to this BFD, provided it is the right
3758          format and is not from ld --just-symbols.  Always create the
3759          dynamic sections for -E/--dynamic-list.  FIXME: If there
3760          are no input BFD's of the same format as the output, we can't
3761          make a shared library.  */
3762       if (!just_syms
3763           && (bfd_link_pic (info)
3764               || (!bfd_link_relocatable (info)
3765                   && (info->export_dynamic || info->dynamic)))
3766           && is_elf_hash_table (htab)
3767           && info->output_bfd->xvec == abfd->xvec
3768           && !htab->dynamic_sections_created)
3769         {
3770           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3771             goto error_return;
3772         }
3773     }
3774   else if (!is_elf_hash_table (htab))
3775     goto error_return;
3776   else
3777     {
3778       const char *soname = NULL;
3779       char *audit = NULL;
3780       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3781       int ret;
3782
3783       /* ld --just-symbols and dynamic objects don't mix very well.
3784          ld shouldn't allow it.  */
3785       if (just_syms)
3786         abort ();
3787
3788       /* If this dynamic lib was specified on the command line with
3789          --as-needed in effect, then we don't want to add a DT_NEEDED
3790          tag unless the lib is actually used.  Similary for libs brought
3791          in by another lib's DT_NEEDED.  When --no-add-needed is used
3792          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3793          any dynamic library in DT_NEEDED tags in the dynamic lib at
3794          all.  */
3795       add_needed = (elf_dyn_lib_class (abfd)
3796                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3797                        | DYN_NO_NEEDED)) == 0;
3798
3799       s = bfd_get_section_by_name (abfd, ".dynamic");
3800       if (s != NULL)
3801         {
3802           bfd_byte *dynbuf;
3803           bfd_byte *extdyn;
3804           unsigned int elfsec;
3805           unsigned long shlink;
3806
3807           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3808             {
3809 error_free_dyn:
3810               free (dynbuf);
3811               goto error_return;
3812             }
3813
3814           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3815           if (elfsec == SHN_BAD)
3816             goto error_free_dyn;
3817           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3818
3819           for (extdyn = dynbuf;
3820                extdyn < dynbuf + s->size;
3821                extdyn += bed->s->sizeof_dyn)
3822             {
3823               Elf_Internal_Dyn dyn;
3824
3825               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3826               if (dyn.d_tag == DT_SONAME)
3827                 {
3828                   unsigned int tagv = dyn.d_un.d_val;
3829                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3830                   if (soname == NULL)
3831                     goto error_free_dyn;
3832                 }
3833               if (dyn.d_tag == DT_NEEDED)
3834                 {
3835                   struct bfd_link_needed_list *n, **pn;
3836                   char *fnm, *anm;
3837                   unsigned int tagv = dyn.d_un.d_val;
3838
3839                   amt = sizeof (struct bfd_link_needed_list);
3840                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3841                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3842                   if (n == NULL || fnm == NULL)
3843                     goto error_free_dyn;
3844                   amt = strlen (fnm) + 1;
3845                   anm = (char *) bfd_alloc (abfd, amt);
3846                   if (anm == NULL)
3847                     goto error_free_dyn;
3848                   memcpy (anm, fnm, amt);
3849                   n->name = anm;
3850                   n->by = abfd;
3851                   n->next = NULL;
3852                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3853                     ;
3854                   *pn = n;
3855                 }
3856               if (dyn.d_tag == DT_RUNPATH)
3857                 {
3858                   struct bfd_link_needed_list *n, **pn;
3859                   char *fnm, *anm;
3860                   unsigned int tagv = dyn.d_un.d_val;
3861
3862                   amt = sizeof (struct bfd_link_needed_list);
3863                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3864                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3865                   if (n == NULL || fnm == NULL)
3866                     goto error_free_dyn;
3867                   amt = strlen (fnm) + 1;
3868                   anm = (char *) bfd_alloc (abfd, amt);
3869                   if (anm == NULL)
3870                     goto error_free_dyn;
3871                   memcpy (anm, fnm, amt);
3872                   n->name = anm;
3873                   n->by = abfd;
3874                   n->next = NULL;
3875                   for (pn = & runpath;
3876                        *pn != NULL;
3877                        pn = &(*pn)->next)
3878                     ;
3879                   *pn = n;
3880                 }
3881               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3882               if (!runpath && dyn.d_tag == DT_RPATH)
3883                 {
3884                   struct bfd_link_needed_list *n, **pn;
3885                   char *fnm, *anm;
3886                   unsigned int tagv = dyn.d_un.d_val;
3887
3888                   amt = sizeof (struct bfd_link_needed_list);
3889                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3890                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3891                   if (n == NULL || fnm == NULL)
3892                     goto error_free_dyn;
3893                   amt = strlen (fnm) + 1;
3894                   anm = (char *) bfd_alloc (abfd, amt);
3895                   if (anm == NULL)
3896                     goto error_free_dyn;
3897                   memcpy (anm, fnm, amt);
3898                   n->name = anm;
3899                   n->by = abfd;
3900                   n->next = NULL;
3901                   for (pn = & rpath;
3902                        *pn != NULL;
3903                        pn = &(*pn)->next)
3904                     ;
3905                   *pn = n;
3906                 }
3907               if (dyn.d_tag == DT_AUDIT)
3908                 {
3909                   unsigned int tagv = dyn.d_un.d_val;
3910                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3911                 }
3912             }
3913
3914           free (dynbuf);
3915         }
3916
3917       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3918          frees all more recently bfd_alloc'd blocks as well.  */
3919       if (runpath)
3920         rpath = runpath;
3921
3922       if (rpath)
3923         {
3924           struct bfd_link_needed_list **pn;
3925           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3926             ;
3927           *pn = rpath;
3928         }
3929
3930       /* We do not want to include any of the sections in a dynamic
3931          object in the output file.  We hack by simply clobbering the
3932          list of sections in the BFD.  This could be handled more
3933          cleanly by, say, a new section flag; the existing
3934          SEC_NEVER_LOAD flag is not the one we want, because that one
3935          still implies that the section takes up space in the output
3936          file.  */
3937       bfd_section_list_clear (abfd);
3938
3939       /* Find the name to use in a DT_NEEDED entry that refers to this
3940          object.  If the object has a DT_SONAME entry, we use it.
3941          Otherwise, if the generic linker stuck something in
3942          elf_dt_name, we use that.  Otherwise, we just use the file
3943          name.  */
3944       if (soname == NULL || *soname == '\0')
3945         {
3946           soname = elf_dt_name (abfd);
3947           if (soname == NULL || *soname == '\0')
3948             soname = bfd_get_filename (abfd);
3949         }
3950
3951       /* Save the SONAME because sometimes the linker emulation code
3952          will need to know it.  */
3953       elf_dt_name (abfd) = soname;
3954
3955       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3956       if (ret < 0)
3957         goto error_return;
3958
3959       /* If we have already included this dynamic object in the
3960          link, just ignore it.  There is no reason to include a
3961          particular dynamic object more than once.  */
3962       if (ret > 0)
3963         return TRUE;
3964
3965       /* Save the DT_AUDIT entry for the linker emulation code. */
3966       elf_dt_audit (abfd) = audit;
3967     }
3968
3969   /* If this is a dynamic object, we always link against the .dynsym
3970      symbol table, not the .symtab symbol table.  The dynamic linker
3971      will only see the .dynsym symbol table, so there is no reason to
3972      look at .symtab for a dynamic object.  */
3973
3974   if (! dynamic || elf_dynsymtab (abfd) == 0)
3975     hdr = &elf_tdata (abfd)->symtab_hdr;
3976   else
3977     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3978
3979   symcount = hdr->sh_size / bed->s->sizeof_sym;
3980
3981   /* The sh_info field of the symtab header tells us where the
3982      external symbols start.  We don't care about the local symbols at
3983      this point.  */
3984   if (elf_bad_symtab (abfd))
3985     {
3986       extsymcount = symcount;
3987       extsymoff = 0;
3988     }
3989   else
3990     {
3991       extsymcount = symcount - hdr->sh_info;
3992       extsymoff = hdr->sh_info;
3993     }
3994
3995   sym_hash = elf_sym_hashes (abfd);
3996   if (extsymcount != 0)
3997     {
3998       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3999                                       NULL, NULL, NULL);
4000       if (isymbuf == NULL)
4001         goto error_return;
4002
4003       if (sym_hash == NULL)
4004         {
4005           /* We store a pointer to the hash table entry for each
4006              external symbol.  */
4007           amt = extsymcount;
4008           amt *= sizeof (struct elf_link_hash_entry *);
4009           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4010           if (sym_hash == NULL)
4011             goto error_free_sym;
4012           elf_sym_hashes (abfd) = sym_hash;
4013         }
4014     }
4015
4016   if (dynamic)
4017     {
4018       /* Read in any version definitions.  */
4019       if (!_bfd_elf_slurp_version_tables (abfd,
4020                                           info->default_imported_symver))
4021         goto error_free_sym;
4022
4023       /* Read in the symbol versions, but don't bother to convert them
4024          to internal format.  */
4025       if (elf_dynversym (abfd) != 0)
4026         {
4027           Elf_Internal_Shdr *versymhdr;
4028
4029           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4030           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4031           if (extversym == NULL)
4032             goto error_free_sym;
4033           amt = versymhdr->sh_size;
4034           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4035               || bfd_bread (extversym, amt, abfd) != amt)
4036             goto error_free_vers;
4037         }
4038     }
4039
4040   /* If we are loading an as-needed shared lib, save the symbol table
4041      state before we start adding symbols.  If the lib turns out
4042      to be unneeded, restore the state.  */
4043   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4044     {
4045       unsigned int i;
4046       size_t entsize;
4047
4048       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4049         {
4050           struct bfd_hash_entry *p;
4051           struct elf_link_hash_entry *h;
4052
4053           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4054             {
4055               h = (struct elf_link_hash_entry *) p;
4056               entsize += htab->root.table.entsize;
4057               if (h->root.type == bfd_link_hash_warning)
4058                 entsize += htab->root.table.entsize;
4059             }
4060         }
4061
4062       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4063       old_tab = bfd_malloc (tabsize + entsize);
4064       if (old_tab == NULL)
4065         goto error_free_vers;
4066
4067       /* Remember the current objalloc pointer, so that all mem for
4068          symbols added can later be reclaimed.  */
4069       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4070       if (alloc_mark == NULL)
4071         goto error_free_vers;
4072
4073       /* Make a special call to the linker "notice" function to
4074          tell it that we are about to handle an as-needed lib.  */
4075       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4076         goto error_free_vers;
4077
4078       /* Clone the symbol table.  Remember some pointers into the
4079          symbol table, and dynamic symbol count.  */
4080       old_ent = (char *) old_tab + tabsize;
4081       memcpy (old_tab, htab->root.table.table, tabsize);
4082       old_undefs = htab->root.undefs;
4083       old_undefs_tail = htab->root.undefs_tail;
4084       old_table = htab->root.table.table;
4085       old_size = htab->root.table.size;
4086       old_count = htab->root.table.count;
4087       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4088       if (old_strtab == NULL)
4089         goto error_free_vers;
4090
4091       for (i = 0; i < htab->root.table.size; i++)
4092         {
4093           struct bfd_hash_entry *p;
4094           struct elf_link_hash_entry *h;
4095
4096           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4097             {
4098               memcpy (old_ent, p, htab->root.table.entsize);
4099               old_ent = (char *) old_ent + htab->root.table.entsize;
4100               h = (struct elf_link_hash_entry *) p;
4101               if (h->root.type == bfd_link_hash_warning)
4102                 {
4103                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4104                   old_ent = (char *) old_ent + htab->root.table.entsize;
4105                 }
4106             }
4107         }
4108     }
4109
4110   weaks = NULL;
4111   ever = extversym != NULL ? extversym + extsymoff : NULL;
4112   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4113        isym < isymend;
4114        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4115     {
4116       int bind;
4117       bfd_vma value;
4118       asection *sec, *new_sec;
4119       flagword flags;
4120       const char *name;
4121       struct elf_link_hash_entry *h;
4122       struct elf_link_hash_entry *hi;
4123       bfd_boolean definition;
4124       bfd_boolean size_change_ok;
4125       bfd_boolean type_change_ok;
4126       bfd_boolean new_weakdef;
4127       bfd_boolean new_weak;
4128       bfd_boolean old_weak;
4129       bfd_boolean override;
4130       bfd_boolean common;
4131       bfd_boolean discarded;
4132       unsigned int old_alignment;
4133       bfd *old_bfd;
4134       bfd_boolean matched;
4135
4136       override = FALSE;
4137
4138       flags = BSF_NO_FLAGS;
4139       sec = NULL;
4140       value = isym->st_value;
4141       common = bed->common_definition (isym);
4142       discarded = FALSE;
4143
4144       bind = ELF_ST_BIND (isym->st_info);
4145       switch (bind)
4146         {
4147         case STB_LOCAL:
4148           /* This should be impossible, since ELF requires that all
4149              global symbols follow all local symbols, and that sh_info
4150              point to the first global symbol.  Unfortunately, Irix 5
4151              screws this up.  */
4152           continue;
4153
4154         case STB_GLOBAL:
4155           if (isym->st_shndx != SHN_UNDEF && !common)
4156             flags = BSF_GLOBAL;
4157           break;
4158
4159         case STB_WEAK:
4160           flags = BSF_WEAK;
4161           break;
4162
4163         case STB_GNU_UNIQUE:
4164           flags = BSF_GNU_UNIQUE;
4165           break;
4166
4167         default:
4168           /* Leave it up to the processor backend.  */
4169           break;
4170         }
4171
4172       if (isym->st_shndx == SHN_UNDEF)
4173         sec = bfd_und_section_ptr;
4174       else if (isym->st_shndx == SHN_ABS)
4175         sec = bfd_abs_section_ptr;
4176       else if (isym->st_shndx == SHN_COMMON)
4177         {
4178           sec = bfd_com_section_ptr;
4179           /* What ELF calls the size we call the value.  What ELF
4180              calls the value we call the alignment.  */
4181           value = isym->st_size;
4182         }
4183       else
4184         {
4185           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4186           if (sec == NULL)
4187             sec = bfd_abs_section_ptr;
4188           else if (discarded_section (sec))
4189             {
4190               /* Symbols from discarded section are undefined.  We keep
4191                  its visibility.  */
4192               sec = bfd_und_section_ptr;
4193               discarded = TRUE;
4194               isym->st_shndx = SHN_UNDEF;
4195             }
4196           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4197             value -= sec->vma;
4198         }
4199
4200       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4201                                               isym->st_name);
4202       if (name == NULL)
4203         goto error_free_vers;
4204
4205       if (isym->st_shndx == SHN_COMMON
4206           && (abfd->flags & BFD_PLUGIN) != 0)
4207         {
4208           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4209
4210           if (xc == NULL)
4211             {
4212               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4213                                  | SEC_EXCLUDE);
4214               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4215               if (xc == NULL)
4216                 goto error_free_vers;
4217             }
4218           sec = xc;
4219         }
4220       else if (isym->st_shndx == SHN_COMMON
4221                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4222                && !bfd_link_relocatable (info))
4223         {
4224           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4225
4226           if (tcomm == NULL)
4227             {
4228               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4229                                  | SEC_LINKER_CREATED);
4230               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4231               if (tcomm == NULL)
4232                 goto error_free_vers;
4233             }
4234           sec = tcomm;
4235         }
4236       else if (bed->elf_add_symbol_hook)
4237         {
4238           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4239                                              &sec, &value))
4240             goto error_free_vers;
4241
4242           /* The hook function sets the name to NULL if this symbol
4243              should be skipped for some reason.  */
4244           if (name == NULL)
4245             continue;
4246         }
4247
4248       /* Sanity check that all possibilities were handled.  */
4249       if (sec == NULL)
4250         {
4251           bfd_set_error (bfd_error_bad_value);
4252           goto error_free_vers;
4253         }
4254
4255       /* Silently discard TLS symbols from --just-syms.  There's
4256          no way to combine a static TLS block with a new TLS block
4257          for this executable.  */
4258       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4259           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4260         continue;
4261
4262       if (bfd_is_und_section (sec)
4263           || bfd_is_com_section (sec))
4264         definition = FALSE;
4265       else
4266         definition = TRUE;
4267
4268       size_change_ok = FALSE;
4269       type_change_ok = bed->type_change_ok;
4270       old_weak = FALSE;
4271       matched = FALSE;
4272       old_alignment = 0;
4273       old_bfd = NULL;
4274       new_sec = sec;
4275
4276       if (is_elf_hash_table (htab))
4277         {
4278           Elf_Internal_Versym iver;
4279           unsigned int vernum = 0;
4280           bfd_boolean skip;
4281
4282           if (ever == NULL)
4283             {
4284               if (info->default_imported_symver)
4285                 /* Use the default symbol version created earlier.  */
4286                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4287               else
4288                 iver.vs_vers = 0;
4289             }
4290           else
4291             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4292
4293           vernum = iver.vs_vers & VERSYM_VERSION;
4294
4295           /* If this is a hidden symbol, or if it is not version
4296              1, we append the version name to the symbol name.
4297              However, we do not modify a non-hidden absolute symbol
4298              if it is not a function, because it might be the version
4299              symbol itself.  FIXME: What if it isn't?  */
4300           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4301               || (vernum > 1
4302                   && (!bfd_is_abs_section (sec)
4303                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4304             {
4305               const char *verstr;
4306               size_t namelen, verlen, newlen;
4307               char *newname, *p;
4308
4309               if (isym->st_shndx != SHN_UNDEF)
4310                 {
4311                   if (vernum > elf_tdata (abfd)->cverdefs)
4312                     verstr = NULL;
4313                   else if (vernum > 1)
4314                     verstr =
4315                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4316                   else
4317                     verstr = "";
4318
4319                   if (verstr == NULL)
4320                     {
4321                       _bfd_error_handler
4322                         /* xgettext:c-format */
4323                         (_("%B: %s: invalid version %u (max %d)"),
4324                          abfd, name, vernum,
4325                          elf_tdata (abfd)->cverdefs);
4326                       bfd_set_error (bfd_error_bad_value);
4327                       goto error_free_vers;
4328                     }
4329                 }
4330               else
4331                 {
4332                   /* We cannot simply test for the number of
4333                      entries in the VERNEED section since the
4334                      numbers for the needed versions do not start
4335                      at 0.  */
4336                   Elf_Internal_Verneed *t;
4337
4338                   verstr = NULL;
4339                   for (t = elf_tdata (abfd)->verref;
4340                        t != NULL;
4341                        t = t->vn_nextref)
4342                     {
4343                       Elf_Internal_Vernaux *a;
4344
4345                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4346                         {
4347                           if (a->vna_other == vernum)
4348                             {
4349                               verstr = a->vna_nodename;
4350                               break;
4351                             }
4352                         }
4353                       if (a != NULL)
4354                         break;
4355                     }
4356                   if (verstr == NULL)
4357                     {
4358                       _bfd_error_handler
4359                         /* xgettext:c-format */
4360                         (_("%B: %s: invalid needed version %d"),
4361                          abfd, name, vernum);
4362                       bfd_set_error (bfd_error_bad_value);
4363                       goto error_free_vers;
4364                     }
4365                 }
4366
4367               namelen = strlen (name);
4368               verlen = strlen (verstr);
4369               newlen = namelen + verlen + 2;
4370               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4371                   && isym->st_shndx != SHN_UNDEF)
4372                 ++newlen;
4373
4374               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4375               if (newname == NULL)
4376                 goto error_free_vers;
4377               memcpy (newname, name, namelen);
4378               p = newname + namelen;
4379               *p++ = ELF_VER_CHR;
4380               /* If this is a defined non-hidden version symbol,
4381                  we add another @ to the name.  This indicates the
4382                  default version of the symbol.  */
4383               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4384                   && isym->st_shndx != SHN_UNDEF)
4385                 *p++ = ELF_VER_CHR;
4386               memcpy (p, verstr, verlen + 1);
4387
4388               name = newname;
4389             }
4390
4391           /* If this symbol has default visibility and the user has
4392              requested we not re-export it, then mark it as hidden.  */
4393           if (!bfd_is_und_section (sec)
4394               && !dynamic
4395               && abfd->no_export
4396               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4397             isym->st_other = (STV_HIDDEN
4398                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4399
4400           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4401                                       sym_hash, &old_bfd, &old_weak,
4402                                       &old_alignment, &skip, &override,
4403                                       &type_change_ok, &size_change_ok,
4404                                       &matched))
4405             goto error_free_vers;
4406
4407           if (skip)
4408             continue;
4409
4410           /* Override a definition only if the new symbol matches the
4411              existing one.  */
4412           if (override && matched)
4413             definition = FALSE;
4414
4415           h = *sym_hash;
4416           while (h->root.type == bfd_link_hash_indirect
4417                  || h->root.type == bfd_link_hash_warning)
4418             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4419
4420           if (elf_tdata (abfd)->verdef != NULL
4421               && vernum > 1
4422               && definition)
4423             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4424         }
4425
4426       if (! (_bfd_generic_link_add_one_symbol
4427              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4428               (struct bfd_link_hash_entry **) sym_hash)))
4429         goto error_free_vers;
4430
4431       if ((flags & BSF_GNU_UNIQUE)
4432           && (abfd->flags & DYNAMIC) == 0
4433           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4434         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4435
4436       h = *sym_hash;
4437       /* We need to make sure that indirect symbol dynamic flags are
4438          updated.  */
4439       hi = h;
4440       while (h->root.type == bfd_link_hash_indirect
4441              || h->root.type == bfd_link_hash_warning)
4442         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4443
4444       /* Setting the index to -3 tells elf_link_output_extsym that
4445          this symbol is defined in a discarded section.  */
4446       if (discarded)
4447         h->indx = -3;
4448
4449       *sym_hash = h;
4450
4451       new_weak = (flags & BSF_WEAK) != 0;
4452       new_weakdef = FALSE;
4453       if (dynamic
4454           && definition
4455           && new_weak
4456           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4457           && is_elf_hash_table (htab)
4458           && h->u.weakdef == NULL)
4459         {
4460           /* Keep a list of all weak defined non function symbols from
4461              a dynamic object, using the weakdef field.  Later in this
4462              function we will set the weakdef field to the correct
4463              value.  We only put non-function symbols from dynamic
4464              objects on this list, because that happens to be the only
4465              time we need to know the normal symbol corresponding to a
4466              weak symbol, and the information is time consuming to
4467              figure out.  If the weakdef field is not already NULL,
4468              then this symbol was already defined by some previous
4469              dynamic object, and we will be using that previous
4470              definition anyhow.  */
4471
4472           h->u.weakdef = weaks;
4473           weaks = h;
4474           new_weakdef = TRUE;
4475         }
4476
4477       /* Set the alignment of a common symbol.  */
4478       if ((common || bfd_is_com_section (sec))
4479           && h->root.type == bfd_link_hash_common)
4480         {
4481           unsigned int align;
4482
4483           if (common)
4484             align = bfd_log2 (isym->st_value);
4485           else
4486             {
4487               /* The new symbol is a common symbol in a shared object.
4488                  We need to get the alignment from the section.  */
4489               align = new_sec->alignment_power;
4490             }
4491           if (align > old_alignment)
4492             h->root.u.c.p->alignment_power = align;
4493           else
4494             h->root.u.c.p->alignment_power = old_alignment;
4495         }
4496
4497       if (is_elf_hash_table (htab))
4498         {
4499           /* Set a flag in the hash table entry indicating the type of
4500              reference or definition we just found.  A dynamic symbol
4501              is one which is referenced or defined by both a regular
4502              object and a shared object.  */
4503           bfd_boolean dynsym = FALSE;
4504
4505           /* Plugin symbols aren't normal.  Don't set def_regular or
4506              ref_regular for them, or make them dynamic.  */
4507           if ((abfd->flags & BFD_PLUGIN) != 0)
4508             ;
4509           else if (! dynamic)
4510             {
4511               if (! definition)
4512                 {
4513                   h->ref_regular = 1;
4514                   if (bind != STB_WEAK)
4515                     h->ref_regular_nonweak = 1;
4516                 }
4517               else
4518                 {
4519                   h->def_regular = 1;
4520                   if (h->def_dynamic)
4521                     {
4522                       h->def_dynamic = 0;
4523                       h->ref_dynamic = 1;
4524                     }
4525                 }
4526
4527               /* If the indirect symbol has been forced local, don't
4528                  make the real symbol dynamic.  */
4529               if ((h == hi || !hi->forced_local)
4530                   && (bfd_link_dll (info)
4531                       || h->def_dynamic
4532                       || h->ref_dynamic))
4533                 dynsym = TRUE;
4534             }
4535           else
4536             {
4537               if (! definition)
4538                 {
4539                   h->ref_dynamic = 1;
4540                   hi->ref_dynamic = 1;
4541                 }
4542               else
4543                 {
4544                   h->def_dynamic = 1;
4545                   hi->def_dynamic = 1;
4546                 }
4547
4548               /* If the indirect symbol has been forced local, don't
4549                  make the real symbol dynamic.  */
4550               if ((h == hi || !hi->forced_local)
4551                   && (h->def_regular
4552                       || h->ref_regular
4553                       || (h->u.weakdef != NULL
4554                           && ! new_weakdef
4555                           && h->u.weakdef->dynindx != -1)))
4556                 dynsym = TRUE;
4557             }
4558
4559           /* Check to see if we need to add an indirect symbol for
4560              the default name.  */
4561           if (definition
4562               || (!override && h->root.type == bfd_link_hash_common))
4563             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4564                                               sec, value, &old_bfd, &dynsym))
4565               goto error_free_vers;
4566
4567           /* Check the alignment when a common symbol is involved. This
4568              can change when a common symbol is overridden by a normal
4569              definition or a common symbol is ignored due to the old
4570              normal definition. We need to make sure the maximum
4571              alignment is maintained.  */
4572           if ((old_alignment || common)
4573               && h->root.type != bfd_link_hash_common)
4574             {
4575               unsigned int common_align;
4576               unsigned int normal_align;
4577               unsigned int symbol_align;
4578               bfd *normal_bfd;
4579               bfd *common_bfd;
4580
4581               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4582                           || h->root.type == bfd_link_hash_defweak);
4583
4584               symbol_align = ffs (h->root.u.def.value) - 1;
4585               if (h->root.u.def.section->owner != NULL
4586                   && (h->root.u.def.section->owner->flags
4587                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4588                 {
4589                   normal_align = h->root.u.def.section->alignment_power;
4590                   if (normal_align > symbol_align)
4591                     normal_align = symbol_align;
4592                 }
4593               else
4594                 normal_align = symbol_align;
4595
4596               if (old_alignment)
4597                 {
4598                   common_align = old_alignment;
4599                   common_bfd = old_bfd;
4600                   normal_bfd = abfd;
4601                 }
4602               else
4603                 {
4604                   common_align = bfd_log2 (isym->st_value);
4605                   common_bfd = abfd;
4606                   normal_bfd = old_bfd;
4607                 }
4608
4609               if (normal_align < common_align)
4610                 {
4611                   /* PR binutils/2735 */
4612                   if (normal_bfd == NULL)
4613                     _bfd_error_handler
4614                       /* xgettext:c-format */
4615                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4616                          " greater than the alignment (%u) of its section %A"),
4617                        common_bfd, h->root.u.def.section,
4618                        1 << common_align, name, 1 << normal_align);
4619                   else
4620                     _bfd_error_handler
4621                       /* xgettext:c-format */
4622                       (_("Warning: alignment %u of symbol `%s' in %B"
4623                          " is smaller than %u in %B"),
4624                        normal_bfd, common_bfd,
4625                        1 << normal_align, name, 1 << common_align);
4626                 }
4627             }
4628
4629           /* Remember the symbol size if it isn't undefined.  */
4630           if (isym->st_size != 0
4631               && isym->st_shndx != SHN_UNDEF
4632               && (definition || h->size == 0))
4633             {
4634               if (h->size != 0
4635                   && h->size != isym->st_size
4636                   && ! size_change_ok)
4637                 _bfd_error_handler
4638                   /* xgettext:c-format */
4639                   (_("Warning: size of symbol `%s' changed"
4640                      " from %lu in %B to %lu in %B"),
4641                    old_bfd, abfd,
4642                    name, (unsigned long) h->size,
4643                    (unsigned long) isym->st_size);
4644
4645               h->size = isym->st_size;
4646             }
4647
4648           /* If this is a common symbol, then we always want H->SIZE
4649              to be the size of the common symbol.  The code just above
4650              won't fix the size if a common symbol becomes larger.  We
4651              don't warn about a size change here, because that is
4652              covered by --warn-common.  Allow changes between different
4653              function types.  */
4654           if (h->root.type == bfd_link_hash_common)
4655             h->size = h->root.u.c.size;
4656
4657           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4658               && ((definition && !new_weak)
4659                   || (old_weak && h->root.type == bfd_link_hash_common)
4660                   || h->type == STT_NOTYPE))
4661             {
4662               unsigned int type = ELF_ST_TYPE (isym->st_info);
4663
4664               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4665                  symbol.  */
4666               if (type == STT_GNU_IFUNC
4667                   && (abfd->flags & DYNAMIC) != 0)
4668                 type = STT_FUNC;
4669
4670               if (h->type != type)
4671                 {
4672                   if (h->type != STT_NOTYPE && ! type_change_ok)
4673                     /* xgettext:c-format */
4674                     _bfd_error_handler
4675                       (_("Warning: type of symbol `%s' changed"
4676                          " from %d to %d in %B"),
4677                        abfd, name, h->type, type);
4678
4679                   h->type = type;
4680                 }
4681             }
4682
4683           /* Merge st_other field.  */
4684           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4685
4686           /* We don't want to make debug symbol dynamic.  */
4687           if (definition
4688               && (sec->flags & SEC_DEBUGGING)
4689               && !bfd_link_relocatable (info))
4690             dynsym = FALSE;
4691
4692           /* Nor should we make plugin symbols dynamic.  */
4693           if ((abfd->flags & BFD_PLUGIN) != 0)
4694             dynsym = FALSE;
4695
4696           if (definition)
4697             {
4698               h->target_internal = isym->st_target_internal;
4699               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4700             }
4701
4702           if (definition && !dynamic)
4703             {
4704               char *p = strchr (name, ELF_VER_CHR);
4705               if (p != NULL && p[1] != ELF_VER_CHR)
4706                 {
4707                   /* Queue non-default versions so that .symver x, x@FOO
4708                      aliases can be checked.  */
4709                   if (!nondeflt_vers)
4710                     {
4711                       amt = ((isymend - isym + 1)
4712                              * sizeof (struct elf_link_hash_entry *));
4713                       nondeflt_vers
4714                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4715                       if (!nondeflt_vers)
4716                         goto error_free_vers;
4717                     }
4718                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4719                 }
4720             }
4721
4722           if (dynsym && h->dynindx == -1)
4723             {
4724               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4725                 goto error_free_vers;
4726               if (h->u.weakdef != NULL
4727                   && ! new_weakdef
4728                   && h->u.weakdef->dynindx == -1)
4729                 {
4730                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4731                     goto error_free_vers;
4732                 }
4733             }
4734           else if (h->dynindx != -1)
4735             /* If the symbol already has a dynamic index, but
4736                visibility says it should not be visible, turn it into
4737                a local symbol.  */
4738             switch (ELF_ST_VISIBILITY (h->other))
4739               {
4740               case STV_INTERNAL:
4741               case STV_HIDDEN:
4742                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4743                 dynsym = FALSE;
4744                 break;
4745               }
4746
4747           /* Don't add DT_NEEDED for references from the dummy bfd nor
4748              for unmatched symbol.  */
4749           if (!add_needed
4750               && matched
4751               && definition
4752               && ((dynsym
4753                    && h->ref_regular_nonweak
4754                    && (old_bfd == NULL
4755                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4756                   || (h->ref_dynamic_nonweak
4757                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4758                       && !on_needed_list (elf_dt_name (abfd),
4759                                           htab->needed, NULL))))
4760             {
4761               int ret;
4762               const char *soname = elf_dt_name (abfd);
4763
4764               info->callbacks->minfo ("%!", soname, old_bfd,
4765                                       h->root.root.string);
4766
4767               /* A symbol from a library loaded via DT_NEEDED of some
4768                  other library is referenced by a regular object.
4769                  Add a DT_NEEDED entry for it.  Issue an error if
4770                  --no-add-needed is used and the reference was not
4771                  a weak one.  */
4772               if (old_bfd != NULL
4773                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4774                 {
4775                   _bfd_error_handler
4776                     /* xgettext:c-format */
4777                     (_("%B: undefined reference to symbol '%s'"),
4778                      old_bfd, name);
4779                   bfd_set_error (bfd_error_missing_dso);
4780                   goto error_free_vers;
4781                 }
4782
4783               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4784                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4785
4786               add_needed = TRUE;
4787               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4788               if (ret < 0)
4789                 goto error_free_vers;
4790
4791               BFD_ASSERT (ret == 0);
4792             }
4793         }
4794     }
4795
4796   if (extversym != NULL)
4797     {
4798       free (extversym);
4799       extversym = NULL;
4800     }
4801
4802   if (isymbuf != NULL)
4803     {
4804       free (isymbuf);
4805       isymbuf = NULL;
4806     }
4807
4808   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4809     {
4810       unsigned int i;
4811
4812       /* Restore the symbol table.  */
4813       old_ent = (char *) old_tab + tabsize;
4814       memset (elf_sym_hashes (abfd), 0,
4815               extsymcount * sizeof (struct elf_link_hash_entry *));
4816       htab->root.table.table = old_table;
4817       htab->root.table.size = old_size;
4818       htab->root.table.count = old_count;
4819       memcpy (htab->root.table.table, old_tab, tabsize);
4820       htab->root.undefs = old_undefs;
4821       htab->root.undefs_tail = old_undefs_tail;
4822       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4823       free (old_strtab);
4824       old_strtab = NULL;
4825       for (i = 0; i < htab->root.table.size; i++)
4826         {
4827           struct bfd_hash_entry *p;
4828           struct elf_link_hash_entry *h;
4829           bfd_size_type size;
4830           unsigned int alignment_power;
4831
4832           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4833             {
4834               h = (struct elf_link_hash_entry *) p;
4835               if (h->root.type == bfd_link_hash_warning)
4836                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4837
4838               /* Preserve the maximum alignment and size for common
4839                  symbols even if this dynamic lib isn't on DT_NEEDED
4840                  since it can still be loaded at run time by another
4841                  dynamic lib.  */
4842               if (h->root.type == bfd_link_hash_common)
4843                 {
4844                   size = h->root.u.c.size;
4845                   alignment_power = h->root.u.c.p->alignment_power;
4846                 }
4847               else
4848                 {
4849                   size = 0;
4850                   alignment_power = 0;
4851                 }
4852               memcpy (p, old_ent, htab->root.table.entsize);
4853               old_ent = (char *) old_ent + htab->root.table.entsize;
4854               h = (struct elf_link_hash_entry *) p;
4855               if (h->root.type == bfd_link_hash_warning)
4856                 {
4857                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4858                   old_ent = (char *) old_ent + htab->root.table.entsize;
4859                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4860                 }
4861               if (h->root.type == bfd_link_hash_common)
4862                 {
4863                   if (size > h->root.u.c.size)
4864                     h->root.u.c.size = size;
4865                   if (alignment_power > h->root.u.c.p->alignment_power)
4866                     h->root.u.c.p->alignment_power = alignment_power;
4867                 }
4868             }
4869         }
4870
4871       /* Make a special call to the linker "notice" function to
4872          tell it that symbols added for crefs may need to be removed.  */
4873       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4874         goto error_free_vers;
4875
4876       free (old_tab);
4877       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4878                            alloc_mark);
4879       if (nondeflt_vers != NULL)
4880         free (nondeflt_vers);
4881       return TRUE;
4882     }
4883
4884   if (old_tab != NULL)
4885     {
4886       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4887         goto error_free_vers;
4888       free (old_tab);
4889       old_tab = NULL;
4890     }
4891
4892   /* Now that all the symbols from this input file are created, if
4893      not performing a relocatable link, handle .symver foo, foo@BAR
4894      such that any relocs against foo become foo@BAR.  */
4895   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4896     {
4897       size_t cnt, symidx;
4898
4899       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4900         {
4901           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4902           char *shortname, *p;
4903
4904           p = strchr (h->root.root.string, ELF_VER_CHR);
4905           if (p == NULL
4906               || (h->root.type != bfd_link_hash_defined
4907                   && h->root.type != bfd_link_hash_defweak))
4908             continue;
4909
4910           amt = p - h->root.root.string;
4911           shortname = (char *) bfd_malloc (amt + 1);
4912           if (!shortname)
4913             goto error_free_vers;
4914           memcpy (shortname, h->root.root.string, amt);
4915           shortname[amt] = '\0';
4916
4917           hi = (struct elf_link_hash_entry *)
4918                bfd_link_hash_lookup (&htab->root, shortname,
4919                                      FALSE, FALSE, FALSE);
4920           if (hi != NULL
4921               && hi->root.type == h->root.type
4922               && hi->root.u.def.value == h->root.u.def.value
4923               && hi->root.u.def.section == h->root.u.def.section)
4924             {
4925               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4926               hi->root.type = bfd_link_hash_indirect;
4927               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4928               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4929               sym_hash = elf_sym_hashes (abfd);
4930               if (sym_hash)
4931                 for (symidx = 0; symidx < extsymcount; ++symidx)
4932                   if (sym_hash[symidx] == hi)
4933                     {
4934                       sym_hash[symidx] = h;
4935                       break;
4936                     }
4937             }
4938           free (shortname);
4939         }
4940       free (nondeflt_vers);
4941       nondeflt_vers = NULL;
4942     }
4943
4944   /* Now set the weakdefs field correctly for all the weak defined
4945      symbols we found.  The only way to do this is to search all the
4946      symbols.  Since we only need the information for non functions in
4947      dynamic objects, that's the only time we actually put anything on
4948      the list WEAKS.  We need this information so that if a regular
4949      object refers to a symbol defined weakly in a dynamic object, the
4950      real symbol in the dynamic object is also put in the dynamic
4951      symbols; we also must arrange for both symbols to point to the
4952      same memory location.  We could handle the general case of symbol
4953      aliasing, but a general symbol alias can only be generated in
4954      assembler code, handling it correctly would be very time
4955      consuming, and other ELF linkers don't handle general aliasing
4956      either.  */
4957   if (weaks != NULL)
4958     {
4959       struct elf_link_hash_entry **hpp;
4960       struct elf_link_hash_entry **hppend;
4961       struct elf_link_hash_entry **sorted_sym_hash;
4962       struct elf_link_hash_entry *h;
4963       size_t sym_count;
4964
4965       /* Since we have to search the whole symbol list for each weak
4966          defined symbol, search time for N weak defined symbols will be
4967          O(N^2). Binary search will cut it down to O(NlogN).  */
4968       amt = extsymcount;
4969       amt *= sizeof (struct elf_link_hash_entry *);
4970       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4971       if (sorted_sym_hash == NULL)
4972         goto error_return;
4973       sym_hash = sorted_sym_hash;
4974       hpp = elf_sym_hashes (abfd);
4975       hppend = hpp + extsymcount;
4976       sym_count = 0;
4977       for (; hpp < hppend; hpp++)
4978         {
4979           h = *hpp;
4980           if (h != NULL
4981               && h->root.type == bfd_link_hash_defined
4982               && !bed->is_function_type (h->type))
4983             {
4984               *sym_hash = h;
4985               sym_hash++;
4986               sym_count++;
4987             }
4988         }
4989
4990       qsort (sorted_sym_hash, sym_count,
4991              sizeof (struct elf_link_hash_entry *),
4992              elf_sort_symbol);
4993
4994       while (weaks != NULL)
4995         {
4996           struct elf_link_hash_entry *hlook;
4997           asection *slook;
4998           bfd_vma vlook;
4999           size_t i, j, idx = 0;
5000
5001           hlook = weaks;
5002           weaks = hlook->u.weakdef;
5003           hlook->u.weakdef = NULL;
5004
5005           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5006                       || hlook->root.type == bfd_link_hash_defweak
5007                       || hlook->root.type == bfd_link_hash_common
5008                       || hlook->root.type == bfd_link_hash_indirect);
5009           slook = hlook->root.u.def.section;
5010           vlook = hlook->root.u.def.value;
5011
5012           i = 0;
5013           j = sym_count;
5014           while (i != j)
5015             {
5016               bfd_signed_vma vdiff;
5017               idx = (i + j) / 2;
5018               h = sorted_sym_hash[idx];
5019               vdiff = vlook - h->root.u.def.value;
5020               if (vdiff < 0)
5021                 j = idx;
5022               else if (vdiff > 0)
5023                 i = idx + 1;
5024               else
5025                 {
5026                   int sdiff = slook->id - h->root.u.def.section->id;
5027                   if (sdiff < 0)
5028                     j = idx;
5029                   else if (sdiff > 0)
5030                     i = idx + 1;
5031                   else
5032                     break;
5033                 }
5034             }
5035
5036           /* We didn't find a value/section match.  */
5037           if (i == j)
5038             continue;
5039
5040           /* With multiple aliases, or when the weak symbol is already
5041              strongly defined, we have multiple matching symbols and
5042              the binary search above may land on any of them.  Step
5043              one past the matching symbol(s).  */
5044           while (++idx != j)
5045             {
5046               h = sorted_sym_hash[idx];
5047               if (h->root.u.def.section != slook
5048                   || h->root.u.def.value != vlook)
5049                 break;
5050             }
5051
5052           /* Now look back over the aliases.  Since we sorted by size
5053              as well as value and section, we'll choose the one with
5054              the largest size.  */
5055           while (idx-- != i)
5056             {
5057               h = sorted_sym_hash[idx];
5058
5059               /* Stop if value or section doesn't match.  */
5060               if (h->root.u.def.section != slook
5061                   || h->root.u.def.value != vlook)
5062                 break;
5063               else if (h != hlook)
5064                 {
5065                   hlook->u.weakdef = h;
5066
5067                   /* If the weak definition is in the list of dynamic
5068                      symbols, make sure the real definition is put
5069                      there as well.  */
5070                   if (hlook->dynindx != -1 && h->dynindx == -1)
5071                     {
5072                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5073                         {
5074                         err_free_sym_hash:
5075                           free (sorted_sym_hash);
5076                           goto error_return;
5077                         }
5078                     }
5079
5080                   /* If the real definition is in the list of dynamic
5081                      symbols, make sure the weak definition is put
5082                      there as well.  If we don't do this, then the
5083                      dynamic loader might not merge the entries for the
5084                      real definition and the weak definition.  */
5085                   if (h->dynindx != -1 && hlook->dynindx == -1)
5086                     {
5087                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5088                         goto err_free_sym_hash;
5089                     }
5090                   break;
5091                 }
5092             }
5093         }
5094
5095       free (sorted_sym_hash);
5096     }
5097
5098   if (bed->check_directives
5099       && !(*bed->check_directives) (abfd, info))
5100     return FALSE;
5101
5102   if (!info->check_relocs_after_open_input
5103       && !_bfd_elf_link_check_relocs (abfd, info))
5104     return FALSE;
5105
5106   /* If this is a non-traditional link, try to optimize the handling
5107      of the .stab/.stabstr sections.  */
5108   if (! dynamic
5109       && ! info->traditional_format
5110       && is_elf_hash_table (htab)
5111       && (info->strip != strip_all && info->strip != strip_debugger))
5112     {
5113       asection *stabstr;
5114
5115       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5116       if (stabstr != NULL)
5117         {
5118           bfd_size_type string_offset = 0;
5119           asection *stab;
5120
5121           for (stab = abfd->sections; stab; stab = stab->next)
5122             if (CONST_STRNEQ (stab->name, ".stab")
5123                 && (!stab->name[5] ||
5124                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5125                 && (stab->flags & SEC_MERGE) == 0
5126                 && !bfd_is_abs_section (stab->output_section))
5127               {
5128                 struct bfd_elf_section_data *secdata;
5129
5130                 secdata = elf_section_data (stab);
5131                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5132                                                stabstr, &secdata->sec_info,
5133                                                &string_offset))
5134                   goto error_return;
5135                 if (secdata->sec_info)
5136                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5137             }
5138         }
5139     }
5140
5141   if (is_elf_hash_table (htab) && add_needed)
5142     {
5143       /* Add this bfd to the loaded list.  */
5144       struct elf_link_loaded_list *n;
5145
5146       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5147       if (n == NULL)
5148         goto error_return;
5149       n->abfd = abfd;
5150       n->next = htab->loaded;
5151       htab->loaded = n;
5152     }
5153
5154   return TRUE;
5155
5156  error_free_vers:
5157   if (old_tab != NULL)
5158     free (old_tab);
5159   if (old_strtab != NULL)
5160     free (old_strtab);
5161   if (nondeflt_vers != NULL)
5162     free (nondeflt_vers);
5163   if (extversym != NULL)
5164     free (extversym);
5165  error_free_sym:
5166   if (isymbuf != NULL)
5167     free (isymbuf);
5168  error_return:
5169   return FALSE;
5170 }
5171
5172 /* Return the linker hash table entry of a symbol that might be
5173    satisfied by an archive symbol.  Return -1 on error.  */
5174
5175 struct elf_link_hash_entry *
5176 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5177                                 struct bfd_link_info *info,
5178                                 const char *name)
5179 {
5180   struct elf_link_hash_entry *h;
5181   char *p, *copy;
5182   size_t len, first;
5183
5184   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5185   if (h != NULL)
5186     return h;
5187
5188   /* If this is a default version (the name contains @@), look up the
5189      symbol again with only one `@' as well as without the version.
5190      The effect is that references to the symbol with and without the
5191      version will be matched by the default symbol in the archive.  */
5192
5193   p = strchr (name, ELF_VER_CHR);
5194   if (p == NULL || p[1] != ELF_VER_CHR)
5195     return h;
5196
5197   /* First check with only one `@'.  */
5198   len = strlen (name);
5199   copy = (char *) bfd_alloc (abfd, len);
5200   if (copy == NULL)
5201     return (struct elf_link_hash_entry *) 0 - 1;
5202
5203   first = p - name + 1;
5204   memcpy (copy, name, first);
5205   memcpy (copy + first, name + first + 1, len - first);
5206
5207   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5208   if (h == NULL)
5209     {
5210       /* We also need to check references to the symbol without the
5211          version.  */
5212       copy[first - 1] = '\0';
5213       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5214                                 FALSE, FALSE, TRUE);
5215     }
5216
5217   bfd_release (abfd, copy);
5218   return h;
5219 }
5220
5221 /* Add symbols from an ELF archive file to the linker hash table.  We
5222    don't use _bfd_generic_link_add_archive_symbols because we need to
5223    handle versioned symbols.
5224
5225    Fortunately, ELF archive handling is simpler than that done by
5226    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5227    oddities.  In ELF, if we find a symbol in the archive map, and the
5228    symbol is currently undefined, we know that we must pull in that
5229    object file.
5230
5231    Unfortunately, we do have to make multiple passes over the symbol
5232    table until nothing further is resolved.  */
5233
5234 static bfd_boolean
5235 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5236 {
5237   symindex c;
5238   unsigned char *included = NULL;
5239   carsym *symdefs;
5240   bfd_boolean loop;
5241   bfd_size_type amt;
5242   const struct elf_backend_data *bed;
5243   struct elf_link_hash_entry * (*archive_symbol_lookup)
5244     (bfd *, struct bfd_link_info *, const char *);
5245
5246   if (! bfd_has_map (abfd))
5247     {
5248       /* An empty archive is a special case.  */
5249       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5250         return TRUE;
5251       bfd_set_error (bfd_error_no_armap);
5252       return FALSE;
5253     }
5254
5255   /* Keep track of all symbols we know to be already defined, and all
5256      files we know to be already included.  This is to speed up the
5257      second and subsequent passes.  */
5258   c = bfd_ardata (abfd)->symdef_count;
5259   if (c == 0)
5260     return TRUE;
5261   amt = c;
5262   amt *= sizeof (*included);
5263   included = (unsigned char *) bfd_zmalloc (amt);
5264   if (included == NULL)
5265     return FALSE;
5266
5267   symdefs = bfd_ardata (abfd)->symdefs;
5268   bed = get_elf_backend_data (abfd);
5269   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5270
5271   do
5272     {
5273       file_ptr last;
5274       symindex i;
5275       carsym *symdef;
5276       carsym *symdefend;
5277
5278       loop = FALSE;
5279       last = -1;
5280
5281       symdef = symdefs;
5282       symdefend = symdef + c;
5283       for (i = 0; symdef < symdefend; symdef++, i++)
5284         {
5285           struct elf_link_hash_entry *h;
5286           bfd *element;
5287           struct bfd_link_hash_entry *undefs_tail;
5288           symindex mark;
5289
5290           if (included[i])
5291             continue;
5292           if (symdef->file_offset == last)
5293             {
5294               included[i] = TRUE;
5295               continue;
5296             }
5297
5298           h = archive_symbol_lookup (abfd, info, symdef->name);
5299           if (h == (struct elf_link_hash_entry *) 0 - 1)
5300             goto error_return;
5301
5302           if (h == NULL)
5303             continue;
5304
5305           if (h->root.type == bfd_link_hash_common)
5306             {
5307               /* We currently have a common symbol.  The archive map contains
5308                  a reference to this symbol, so we may want to include it.  We
5309                  only want to include it however, if this archive element
5310                  contains a definition of the symbol, not just another common
5311                  declaration of it.
5312
5313                  Unfortunately some archivers (including GNU ar) will put
5314                  declarations of common symbols into their archive maps, as
5315                  well as real definitions, so we cannot just go by the archive
5316                  map alone.  Instead we must read in the element's symbol
5317                  table and check that to see what kind of symbol definition
5318                  this is.  */
5319               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5320                 continue;
5321             }
5322           else if (h->root.type != bfd_link_hash_undefined)
5323             {
5324               if (h->root.type != bfd_link_hash_undefweak)
5325                 /* Symbol must be defined.  Don't check it again.  */
5326                 included[i] = TRUE;
5327               continue;
5328             }
5329
5330           /* We need to include this archive member.  */
5331           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5332           if (element == NULL)
5333             goto error_return;
5334
5335           if (! bfd_check_format (element, bfd_object))
5336             goto error_return;
5337
5338           undefs_tail = info->hash->undefs_tail;
5339
5340           if (!(*info->callbacks
5341                 ->add_archive_element) (info, element, symdef->name, &element))
5342             continue;
5343           if (!bfd_link_add_symbols (element, info))
5344             goto error_return;
5345
5346           /* If there are any new undefined symbols, we need to make
5347              another pass through the archive in order to see whether
5348              they can be defined.  FIXME: This isn't perfect, because
5349              common symbols wind up on undefs_tail and because an
5350              undefined symbol which is defined later on in this pass
5351              does not require another pass.  This isn't a bug, but it
5352              does make the code less efficient than it could be.  */
5353           if (undefs_tail != info->hash->undefs_tail)
5354             loop = TRUE;
5355
5356           /* Look backward to mark all symbols from this object file
5357              which we have already seen in this pass.  */
5358           mark = i;
5359           do
5360             {
5361               included[mark] = TRUE;
5362               if (mark == 0)
5363                 break;
5364               --mark;
5365             }
5366           while (symdefs[mark].file_offset == symdef->file_offset);
5367
5368           /* We mark subsequent symbols from this object file as we go
5369              on through the loop.  */
5370           last = symdef->file_offset;
5371         }
5372     }
5373   while (loop);
5374
5375   free (included);
5376
5377   return TRUE;
5378
5379  error_return:
5380   if (included != NULL)
5381     free (included);
5382   return FALSE;
5383 }
5384
5385 /* Given an ELF BFD, add symbols to the global hash table as
5386    appropriate.  */
5387
5388 bfd_boolean
5389 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5390 {
5391   switch (bfd_get_format (abfd))
5392     {
5393     case bfd_object:
5394       return elf_link_add_object_symbols (abfd, info);
5395     case bfd_archive:
5396       return elf_link_add_archive_symbols (abfd, info);
5397     default:
5398       bfd_set_error (bfd_error_wrong_format);
5399       return FALSE;
5400     }
5401 }
5402 \f
5403 struct hash_codes_info
5404 {
5405   unsigned long *hashcodes;
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_hash_codes (struct elf_link_hash_entry *h, void *data)
5414 {
5415   struct hash_codes_info *inf = (struct hash_codes_info *) 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   name = h->root.root.string;
5425   if (h->versioned >= versioned)
5426     {
5427       char *p = strchr (name, ELF_VER_CHR);
5428       if (p != NULL)
5429         {
5430           alc = (char *) bfd_malloc (p - name + 1);
5431           if (alc == NULL)
5432             {
5433               inf->error = TRUE;
5434               return FALSE;
5435             }
5436           memcpy (alc, name, p - name);
5437           alc[p - name] = '\0';
5438           name = alc;
5439         }
5440     }
5441
5442   /* Compute the hash value.  */
5443   ha = bfd_elf_hash (name);
5444
5445   /* Store the found hash value in the array given as the argument.  */
5446   *(inf->hashcodes)++ = ha;
5447
5448   /* And store it in the struct so that we can put it in the hash table
5449      later.  */
5450   h->u.elf_hash_value = ha;
5451
5452   if (alc != NULL)
5453     free (alc);
5454
5455   return TRUE;
5456 }
5457
5458 struct collect_gnu_hash_codes
5459 {
5460   bfd *output_bfd;
5461   const struct elf_backend_data *bed;
5462   unsigned long int nsyms;
5463   unsigned long int maskbits;
5464   unsigned long int *hashcodes;
5465   unsigned long int *hashval;
5466   unsigned long int *indx;
5467   unsigned long int *counts;
5468   bfd_vma *bitmask;
5469   bfd_byte *contents;
5470   long int min_dynindx;
5471   unsigned long int bucketcount;
5472   unsigned long int symindx;
5473   long int local_indx;
5474   long int shift1, shift2;
5475   unsigned long int mask;
5476   bfd_boolean error;
5477 };
5478
5479 /* This function will be called though elf_link_hash_traverse to store
5480    all hash value of the exported symbols in an array.  */
5481
5482 static bfd_boolean
5483 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5484 {
5485   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5486   const char *name;
5487   unsigned long ha;
5488   char *alc = NULL;
5489
5490   /* Ignore indirect symbols.  These are added by the versioning code.  */
5491   if (h->dynindx == -1)
5492     return TRUE;
5493
5494   /* Ignore also local symbols and undefined symbols.  */
5495   if (! (*s->bed->elf_hash_symbol) (h))
5496     return TRUE;
5497
5498   name = h->root.root.string;
5499   if (h->versioned >= versioned)
5500     {
5501       char *p = strchr (name, ELF_VER_CHR);
5502       if (p != NULL)
5503         {
5504           alc = (char *) bfd_malloc (p - name + 1);
5505           if (alc == NULL)
5506             {
5507               s->error = TRUE;
5508               return FALSE;
5509             }
5510           memcpy (alc, name, p - name);
5511           alc[p - name] = '\0';
5512           name = alc;
5513         }
5514     }
5515
5516   /* Compute the hash value.  */
5517   ha = bfd_elf_gnu_hash (name);
5518
5519   /* Store the found hash value in the array for compute_bucket_count,
5520      and also for .dynsym reordering purposes.  */
5521   s->hashcodes[s->nsyms] = ha;
5522   s->hashval[h->dynindx] = ha;
5523   ++s->nsyms;
5524   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5525     s->min_dynindx = h->dynindx;
5526
5527   if (alc != NULL)
5528     free (alc);
5529
5530   return TRUE;
5531 }
5532
5533 /* This function will be called though elf_link_hash_traverse to do
5534    final dynaminc symbol renumbering.  */
5535
5536 static bfd_boolean
5537 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5538 {
5539   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5540   unsigned long int bucket;
5541   unsigned long int val;
5542
5543   /* Ignore indirect symbols.  */
5544   if (h->dynindx == -1)
5545     return TRUE;
5546
5547   /* Ignore also local symbols and undefined symbols.  */
5548   if (! (*s->bed->elf_hash_symbol) (h))
5549     {
5550       if (h->dynindx >= s->min_dynindx)
5551         h->dynindx = s->local_indx++;
5552       return TRUE;
5553     }
5554
5555   bucket = s->hashval[h->dynindx] % s->bucketcount;
5556   val = (s->hashval[h->dynindx] >> s->shift1)
5557         & ((s->maskbits >> s->shift1) - 1);
5558   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5559   s->bitmask[val]
5560     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5561   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5562   if (s->counts[bucket] == 1)
5563     /* Last element terminates the chain.  */
5564     val |= 1;
5565   bfd_put_32 (s->output_bfd, val,
5566               s->contents + (s->indx[bucket] - s->symindx) * 4);
5567   --s->counts[bucket];
5568   h->dynindx = s->indx[bucket]++;
5569   return TRUE;
5570 }
5571
5572 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5573
5574 bfd_boolean
5575 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5576 {
5577   return !(h->forced_local
5578            || h->root.type == bfd_link_hash_undefined
5579            || h->root.type == bfd_link_hash_undefweak
5580            || ((h->root.type == bfd_link_hash_defined
5581                 || h->root.type == bfd_link_hash_defweak)
5582                && h->root.u.def.section->output_section == NULL));
5583 }
5584
5585 /* Array used to determine the number of hash table buckets to use
5586    based on the number of symbols there are.  If there are fewer than
5587    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5588    fewer than 37 we use 17 buckets, and so forth.  We never use more
5589    than 32771 buckets.  */
5590
5591 static const size_t elf_buckets[] =
5592 {
5593   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5594   16411, 32771, 0
5595 };
5596
5597 /* Compute bucket count for hashing table.  We do not use a static set
5598    of possible tables sizes anymore.  Instead we determine for all
5599    possible reasonable sizes of the table the outcome (i.e., the
5600    number of collisions etc) and choose the best solution.  The
5601    weighting functions are not too simple to allow the table to grow
5602    without bounds.  Instead one of the weighting factors is the size.
5603    Therefore the result is always a good payoff between few collisions
5604    (= short chain lengths) and table size.  */
5605 static size_t
5606 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5607                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5608                       unsigned long int nsyms,
5609                       int gnu_hash)
5610 {
5611   size_t best_size = 0;
5612   unsigned long int i;
5613
5614   /* We have a problem here.  The following code to optimize the table
5615      size requires an integer type with more the 32 bits.  If
5616      BFD_HOST_U_64_BIT is set we know about such a type.  */
5617 #ifdef BFD_HOST_U_64_BIT
5618   if (info->optimize)
5619     {
5620       size_t minsize;
5621       size_t maxsize;
5622       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5623       bfd *dynobj = elf_hash_table (info)->dynobj;
5624       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5625       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5626       unsigned long int *counts;
5627       bfd_size_type amt;
5628       unsigned int no_improvement_count = 0;
5629
5630       /* Possible optimization parameters: if we have NSYMS symbols we say
5631          that the hashing table must at least have NSYMS/4 and at most
5632          2*NSYMS buckets.  */
5633       minsize = nsyms / 4;
5634       if (minsize == 0)
5635         minsize = 1;
5636       best_size = maxsize = nsyms * 2;
5637       if (gnu_hash)
5638         {
5639           if (minsize < 2)
5640             minsize = 2;
5641           if ((best_size & 31) == 0)
5642             ++best_size;
5643         }
5644
5645       /* Create array where we count the collisions in.  We must use bfd_malloc
5646          since the size could be large.  */
5647       amt = maxsize;
5648       amt *= sizeof (unsigned long int);
5649       counts = (unsigned long int *) bfd_malloc (amt);
5650       if (counts == NULL)
5651         return 0;
5652
5653       /* Compute the "optimal" size for the hash table.  The criteria is a
5654          minimal chain length.  The minor criteria is (of course) the size
5655          of the table.  */
5656       for (i = minsize; i < maxsize; ++i)
5657         {
5658           /* Walk through the array of hashcodes and count the collisions.  */
5659           BFD_HOST_U_64_BIT max;
5660           unsigned long int j;
5661           unsigned long int fact;
5662
5663           if (gnu_hash && (i & 31) == 0)
5664             continue;
5665
5666           memset (counts, '\0', i * sizeof (unsigned long int));
5667
5668           /* Determine how often each hash bucket is used.  */
5669           for (j = 0; j < nsyms; ++j)
5670             ++counts[hashcodes[j] % i];
5671
5672           /* For the weight function we need some information about the
5673              pagesize on the target.  This is information need not be 100%
5674              accurate.  Since this information is not available (so far) we
5675              define it here to a reasonable default value.  If it is crucial
5676              to have a better value some day simply define this value.  */
5677 # ifndef BFD_TARGET_PAGESIZE
5678 #  define BFD_TARGET_PAGESIZE   (4096)
5679 # endif
5680
5681           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5682              and the chains.  */
5683           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5684
5685 # if 1
5686           /* Variant 1: optimize for short chains.  We add the squares
5687              of all the chain lengths (which favors many small chain
5688              over a few long chains).  */
5689           for (j = 0; j < i; ++j)
5690             max += counts[j] * counts[j];
5691
5692           /* This adds penalties for the overall size of the table.  */
5693           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5694           max *= fact * fact;
5695 # else
5696           /* Variant 2: Optimize a lot more for small table.  Here we
5697              also add squares of the size but we also add penalties for
5698              empty slots (the +1 term).  */
5699           for (j = 0; j < i; ++j)
5700             max += (1 + counts[j]) * (1 + counts[j]);
5701
5702           /* The overall size of the table is considered, but not as
5703              strong as in variant 1, where it is squared.  */
5704           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5705           max *= fact;
5706 # endif
5707
5708           /* Compare with current best results.  */
5709           if (max < best_chlen)
5710             {
5711               best_chlen = max;
5712               best_size = i;
5713               no_improvement_count = 0;
5714             }
5715           /* PR 11843: Avoid futile long searches for the best bucket size
5716              when there are a large number of symbols.  */
5717           else if (++no_improvement_count == 100)
5718             break;
5719         }
5720
5721       free (counts);
5722     }
5723   else
5724 #endif /* defined (BFD_HOST_U_64_BIT) */
5725     {
5726       /* This is the fallback solution if no 64bit type is available or if we
5727          are not supposed to spend much time on optimizations.  We select the
5728          bucket count using a fixed set of numbers.  */
5729       for (i = 0; elf_buckets[i] != 0; i++)
5730         {
5731           best_size = elf_buckets[i];
5732           if (nsyms < elf_buckets[i + 1])
5733             break;
5734         }
5735       if (gnu_hash && best_size < 2)
5736         best_size = 2;
5737     }
5738
5739   return best_size;
5740 }
5741
5742 /* Size any SHT_GROUP section for ld -r.  */
5743
5744 bfd_boolean
5745 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5746 {
5747   bfd *ibfd;
5748
5749   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5750     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5751         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5752       return FALSE;
5753   return TRUE;
5754 }
5755
5756 /* Set a default stack segment size.  The value in INFO wins.  If it
5757    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5758    undefined it is initialized.  */
5759
5760 bfd_boolean
5761 bfd_elf_stack_segment_size (bfd *output_bfd,
5762                             struct bfd_link_info *info,
5763                             const char *legacy_symbol,
5764                             bfd_vma default_size)
5765 {
5766   struct elf_link_hash_entry *h = NULL;
5767
5768   /* Look for legacy symbol.  */
5769   if (legacy_symbol)
5770     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5771                               FALSE, FALSE, FALSE);
5772   if (h && (h->root.type == bfd_link_hash_defined
5773             || h->root.type == bfd_link_hash_defweak)
5774       && h->def_regular
5775       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5776     {
5777       /* The symbol has no type if specified on the command line.  */
5778       h->type = STT_OBJECT;
5779       if (info->stacksize)
5780         /* xgettext:c-format */
5781         _bfd_error_handler (_("%B: stack size specified and %s set"),
5782                             output_bfd, legacy_symbol);
5783       else if (h->root.u.def.section != bfd_abs_section_ptr)
5784         /* xgettext:c-format */
5785         _bfd_error_handler (_("%B: %s not absolute"),
5786                             output_bfd, legacy_symbol);
5787       else
5788         info->stacksize = h->root.u.def.value;
5789     }
5790
5791   if (!info->stacksize)
5792     /* If the user didn't set a size, or explicitly inhibit the
5793        size, set it now.  */
5794     info->stacksize = default_size;
5795
5796   /* Provide the legacy symbol, if it is referenced.  */
5797   if (h && (h->root.type == bfd_link_hash_undefined
5798             || h->root.type == bfd_link_hash_undefweak))
5799     {
5800       struct bfd_link_hash_entry *bh = NULL;
5801
5802       if (!(_bfd_generic_link_add_one_symbol
5803             (info, output_bfd, legacy_symbol,
5804              BSF_GLOBAL, bfd_abs_section_ptr,
5805              info->stacksize >= 0 ? info->stacksize : 0,
5806              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5807         return FALSE;
5808
5809       h = (struct elf_link_hash_entry *) bh;
5810       h->def_regular = 1;
5811       h->type = STT_OBJECT;
5812     }
5813
5814   return TRUE;
5815 }
5816
5817 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5818    called by the ELF linker emulation before_allocation routine.  We
5819    must set the sizes of the sections before the linker sets the
5820    addresses of the various sections.  */
5821
5822 bfd_boolean
5823 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5824                                const char *soname,
5825                                const char *rpath,
5826                                const char *filter_shlib,
5827                                const char *audit,
5828                                const char *depaudit,
5829                                const char * const *auxiliary_filters,
5830                                struct bfd_link_info *info,
5831                                asection **sinterpptr)
5832 {
5833   size_t soname_indx;
5834   bfd *dynobj;
5835   const struct elf_backend_data *bed;
5836   struct elf_info_failed asvinfo;
5837
5838   *sinterpptr = NULL;
5839
5840   soname_indx = (size_t) -1;
5841
5842   if (!is_elf_hash_table (info->hash))
5843     return TRUE;
5844
5845   bed = get_elf_backend_data (output_bfd);
5846
5847   /* Any syms created from now on start with -1 in
5848      got.refcount/offset and plt.refcount/offset.  */
5849   elf_hash_table (info)->init_got_refcount
5850     = elf_hash_table (info)->init_got_offset;
5851   elf_hash_table (info)->init_plt_refcount
5852     = elf_hash_table (info)->init_plt_offset;
5853
5854   if (bfd_link_relocatable (info)
5855       && !_bfd_elf_size_group_sections (info))
5856     return FALSE;
5857
5858   /* The backend may have to create some sections regardless of whether
5859      we're dynamic or not.  */
5860   if (bed->elf_backend_always_size_sections
5861       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5862     return FALSE;
5863
5864   /* Determine any GNU_STACK segment requirements, after the backend
5865      has had a chance to set a default segment size.  */
5866   if (info->execstack)
5867     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5868   else if (info->noexecstack)
5869     elf_stack_flags (output_bfd) = PF_R | PF_W;
5870   else
5871     {
5872       bfd *inputobj;
5873       asection *notesec = NULL;
5874       int exec = 0;
5875
5876       for (inputobj = info->input_bfds;
5877            inputobj;
5878            inputobj = inputobj->link.next)
5879         {
5880           asection *s;
5881
5882           if (inputobj->flags
5883               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5884             continue;
5885           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5886           if (s)
5887             {
5888               if (s->flags & SEC_CODE)
5889                 exec = PF_X;
5890               notesec = s;
5891             }
5892           else if (bed->default_execstack)
5893             exec = PF_X;
5894         }
5895       if (notesec || info->stacksize > 0)
5896         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5897       if (notesec && exec && bfd_link_relocatable (info)
5898           && notesec->output_section != bfd_abs_section_ptr)
5899         notesec->output_section->flags |= SEC_CODE;
5900     }
5901
5902   dynobj = elf_hash_table (info)->dynobj;
5903
5904   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5905     {
5906       struct elf_info_failed eif;
5907       struct elf_link_hash_entry *h;
5908       asection *dynstr;
5909       struct bfd_elf_version_tree *t;
5910       struct bfd_elf_version_expr *d;
5911       asection *s;
5912       bfd_boolean all_defined;
5913
5914       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5915       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
5916
5917       if (soname != NULL)
5918         {
5919           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5920                                              soname, TRUE);
5921           if (soname_indx == (size_t) -1
5922               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5923             return FALSE;
5924         }
5925
5926       if (info->symbolic)
5927         {
5928           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5929             return FALSE;
5930           info->flags |= DF_SYMBOLIC;
5931         }
5932
5933       if (rpath != NULL)
5934         {
5935           size_t indx;
5936           bfd_vma tag;
5937
5938           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5939                                       TRUE);
5940           if (indx == (size_t) -1)
5941             return FALSE;
5942
5943           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5944           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5945             return FALSE;
5946         }
5947
5948       if (filter_shlib != NULL)
5949         {
5950           size_t indx;
5951
5952           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5953                                       filter_shlib, TRUE);
5954           if (indx == (size_t) -1
5955               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5956             return FALSE;
5957         }
5958
5959       if (auxiliary_filters != NULL)
5960         {
5961           const char * const *p;
5962
5963           for (p = auxiliary_filters; *p != NULL; p++)
5964             {
5965               size_t indx;
5966
5967               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5968                                           *p, TRUE);
5969               if (indx == (size_t) -1
5970                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5971                 return FALSE;
5972             }
5973         }
5974
5975       if (audit != NULL)
5976         {
5977           size_t indx;
5978
5979           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5980                                       TRUE);
5981           if (indx == (size_t) -1
5982               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5983             return FALSE;
5984         }
5985
5986       if (depaudit != NULL)
5987         {
5988           size_t indx;
5989
5990           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5991                                       TRUE);
5992           if (indx == (size_t) -1
5993               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5994             return FALSE;
5995         }
5996
5997       eif.info = info;
5998       eif.failed = FALSE;
5999
6000       /* If we are supposed to export all symbols into the dynamic symbol
6001          table (this is not the normal case), then do so.  */
6002       if (info->export_dynamic
6003           || (bfd_link_executable (info) && info->dynamic))
6004         {
6005           elf_link_hash_traverse (elf_hash_table (info),
6006                                   _bfd_elf_export_symbol,
6007                                   &eif);
6008           if (eif.failed)
6009             return FALSE;
6010         }
6011
6012       /* Make all global versions with definition.  */
6013       for (t = info->version_info; t != NULL; t = t->next)
6014         for (d = t->globals.list; d != NULL; d = d->next)
6015           if (!d->symver && d->literal)
6016             {
6017               const char *verstr, *name;
6018               size_t namelen, verlen, newlen;
6019               char *newname, *p, leading_char;
6020               struct elf_link_hash_entry *newh;
6021
6022               leading_char = bfd_get_symbol_leading_char (output_bfd);
6023               name = d->pattern;
6024               namelen = strlen (name) + (leading_char != '\0');
6025               verstr = t->name;
6026               verlen = strlen (verstr);
6027               newlen = namelen + verlen + 3;
6028
6029               newname = (char *) bfd_malloc (newlen);
6030               if (newname == NULL)
6031                 return FALSE;
6032               newname[0] = leading_char;
6033               memcpy (newname + (leading_char != '\0'), name, namelen);
6034
6035               /* Check the hidden versioned definition.  */
6036               p = newname + namelen;
6037               *p++ = ELF_VER_CHR;
6038               memcpy (p, verstr, verlen + 1);
6039               newh = elf_link_hash_lookup (elf_hash_table (info),
6040                                            newname, FALSE, FALSE,
6041                                            FALSE);
6042               if (newh == NULL
6043                   || (newh->root.type != bfd_link_hash_defined
6044                       && newh->root.type != bfd_link_hash_defweak))
6045                 {
6046                   /* Check the default versioned definition.  */
6047                   *p++ = ELF_VER_CHR;
6048                   memcpy (p, verstr, verlen + 1);
6049                   newh = elf_link_hash_lookup (elf_hash_table (info),
6050                                                newname, FALSE, FALSE,
6051                                                FALSE);
6052                 }
6053               free (newname);
6054
6055               /* Mark this version if there is a definition and it is
6056                  not defined in a shared object.  */
6057               if (newh != NULL
6058                   && !newh->def_dynamic
6059                   && (newh->root.type == bfd_link_hash_defined
6060                       || newh->root.type == bfd_link_hash_defweak))
6061                 d->symver = 1;
6062             }
6063
6064       /* Attach all the symbols to their version information.  */
6065       asvinfo.info = info;
6066       asvinfo.failed = FALSE;
6067
6068       elf_link_hash_traverse (elf_hash_table (info),
6069                               _bfd_elf_link_assign_sym_version,
6070                               &asvinfo);
6071       if (asvinfo.failed)
6072         return FALSE;
6073
6074       if (!info->allow_undefined_version)
6075         {
6076           /* Check if all global versions have a definition.  */
6077           all_defined = TRUE;
6078           for (t = info->version_info; t != NULL; t = t->next)
6079             for (d = t->globals.list; d != NULL; d = d->next)
6080               if (d->literal && !d->symver && !d->script)
6081                 {
6082                   _bfd_error_handler
6083                     (_("%s: undefined version: %s"),
6084                      d->pattern, t->name);
6085                   all_defined = FALSE;
6086                 }
6087
6088           if (!all_defined)
6089             {
6090               bfd_set_error (bfd_error_bad_value);
6091               return FALSE;
6092             }
6093         }
6094
6095       /* Find all symbols which were defined in a dynamic object and make
6096          the backend pick a reasonable value for them.  */
6097       elf_link_hash_traverse (elf_hash_table (info),
6098                               _bfd_elf_adjust_dynamic_symbol,
6099                               &eif);
6100       if (eif.failed)
6101         return FALSE;
6102
6103       /* Add some entries to the .dynamic section.  We fill in some of the
6104          values later, in bfd_elf_final_link, but we must add the entries
6105          now so that we know the final size of the .dynamic section.  */
6106
6107       /* If there are initialization and/or finalization functions to
6108          call then add the corresponding DT_INIT/DT_FINI entries.  */
6109       h = (info->init_function
6110            ? elf_link_hash_lookup (elf_hash_table (info),
6111                                    info->init_function, FALSE,
6112                                    FALSE, FALSE)
6113            : NULL);
6114       if (h != NULL
6115           && (h->ref_regular
6116               || h->def_regular))
6117         {
6118           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6119             return FALSE;
6120         }
6121       h = (info->fini_function
6122            ? elf_link_hash_lookup (elf_hash_table (info),
6123                                    info->fini_function, FALSE,
6124                                    FALSE, FALSE)
6125            : NULL);
6126       if (h != NULL
6127           && (h->ref_regular
6128               || h->def_regular))
6129         {
6130           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6131             return FALSE;
6132         }
6133
6134       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6135       if (s != NULL && s->linker_has_input)
6136         {
6137           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6138           if (! bfd_link_executable (info))
6139             {
6140               bfd *sub;
6141               asection *o;
6142
6143               for (sub = info->input_bfds; sub != NULL;
6144                    sub = sub->link.next)
6145                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6146                   for (o = sub->sections; o != NULL; o = o->next)
6147                     if (elf_section_data (o)->this_hdr.sh_type
6148                         == SHT_PREINIT_ARRAY)
6149                       {
6150                         _bfd_error_handler
6151                           (_("%B: .preinit_array section is not allowed in DSO"),
6152                            sub);
6153                         break;
6154                       }
6155
6156               bfd_set_error (bfd_error_nonrepresentable_section);
6157               return FALSE;
6158             }
6159
6160           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6161               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6162             return FALSE;
6163         }
6164       s = bfd_get_section_by_name (output_bfd, ".init_array");
6165       if (s != NULL && s->linker_has_input)
6166         {
6167           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6168               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6169             return FALSE;
6170         }
6171       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6172       if (s != NULL && s->linker_has_input)
6173         {
6174           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6175               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6176             return FALSE;
6177         }
6178
6179       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6180       /* If .dynstr is excluded from the link, we don't want any of
6181          these tags.  Strictly, we should be checking each section
6182          individually;  This quick check covers for the case where
6183          someone does a /DISCARD/ : { *(*) }.  */
6184       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6185         {
6186           bfd_size_type strsize;
6187
6188           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6189           if ((info->emit_hash
6190                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6191               || (info->emit_gnu_hash
6192                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6193               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6194               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6195               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6196               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6197                                               bed->s->sizeof_sym))
6198             return FALSE;
6199         }
6200     }
6201
6202   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6203     return FALSE;
6204
6205   /* The backend must work out the sizes of all the other dynamic
6206      sections.  */
6207   if (dynobj != NULL
6208       && bed->elf_backend_size_dynamic_sections != NULL
6209       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6210     return FALSE;
6211
6212   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6213     {
6214       unsigned long section_sym_count;
6215       struct bfd_elf_version_tree *verdefs;
6216       asection *s;
6217
6218       /* Set up the version definition section.  */
6219       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6220       BFD_ASSERT (s != NULL);
6221
6222       /* We may have created additional version definitions if we are
6223          just linking a regular application.  */
6224       verdefs = info->version_info;
6225
6226       /* Skip anonymous version tag.  */
6227       if (verdefs != NULL && verdefs->vernum == 0)
6228         verdefs = verdefs->next;
6229
6230       if (verdefs == NULL && !info->create_default_symver)
6231         s->flags |= SEC_EXCLUDE;
6232       else
6233         {
6234           unsigned int cdefs;
6235           bfd_size_type size;
6236           struct bfd_elf_version_tree *t;
6237           bfd_byte *p;
6238           Elf_Internal_Verdef def;
6239           Elf_Internal_Verdaux defaux;
6240           struct bfd_link_hash_entry *bh;
6241           struct elf_link_hash_entry *h;
6242           const char *name;
6243
6244           cdefs = 0;
6245           size = 0;
6246
6247           /* Make space for the base version.  */
6248           size += sizeof (Elf_External_Verdef);
6249           size += sizeof (Elf_External_Verdaux);
6250           ++cdefs;
6251
6252           /* Make space for the default version.  */
6253           if (info->create_default_symver)
6254             {
6255               size += sizeof (Elf_External_Verdef);
6256               ++cdefs;
6257             }
6258
6259           for (t = verdefs; t != NULL; t = t->next)
6260             {
6261               struct bfd_elf_version_deps *n;
6262
6263               /* Don't emit base version twice.  */
6264               if (t->vernum == 0)
6265                 continue;
6266
6267               size += sizeof (Elf_External_Verdef);
6268               size += sizeof (Elf_External_Verdaux);
6269               ++cdefs;
6270
6271               for (n = t->deps; n != NULL; n = n->next)
6272                 size += sizeof (Elf_External_Verdaux);
6273             }
6274
6275           s->size = size;
6276           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6277           if (s->contents == NULL && s->size != 0)
6278             return FALSE;
6279
6280           /* Fill in the version definition section.  */
6281
6282           p = s->contents;
6283
6284           def.vd_version = VER_DEF_CURRENT;
6285           def.vd_flags = VER_FLG_BASE;
6286           def.vd_ndx = 1;
6287           def.vd_cnt = 1;
6288           if (info->create_default_symver)
6289             {
6290               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6291               def.vd_next = sizeof (Elf_External_Verdef);
6292             }
6293           else
6294             {
6295               def.vd_aux = sizeof (Elf_External_Verdef);
6296               def.vd_next = (sizeof (Elf_External_Verdef)
6297                              + sizeof (Elf_External_Verdaux));
6298             }
6299
6300           if (soname_indx != (size_t) -1)
6301             {
6302               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6303                                       soname_indx);
6304               def.vd_hash = bfd_elf_hash (soname);
6305               defaux.vda_name = soname_indx;
6306               name = soname;
6307             }
6308           else
6309             {
6310               size_t indx;
6311
6312               name = lbasename (output_bfd->filename);
6313               def.vd_hash = bfd_elf_hash (name);
6314               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6315                                           name, FALSE);
6316               if (indx == (size_t) -1)
6317                 return FALSE;
6318               defaux.vda_name = indx;
6319             }
6320           defaux.vda_next = 0;
6321
6322           _bfd_elf_swap_verdef_out (output_bfd, &def,
6323                                     (Elf_External_Verdef *) p);
6324           p += sizeof (Elf_External_Verdef);
6325           if (info->create_default_symver)
6326             {
6327               /* Add a symbol representing this version.  */
6328               bh = NULL;
6329               if (! (_bfd_generic_link_add_one_symbol
6330                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6331                       0, NULL, FALSE,
6332                       get_elf_backend_data (dynobj)->collect, &bh)))
6333                 return FALSE;
6334               h = (struct elf_link_hash_entry *) bh;
6335               h->non_elf = 0;
6336               h->def_regular = 1;
6337               h->type = STT_OBJECT;
6338               h->verinfo.vertree = NULL;
6339
6340               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6341                 return FALSE;
6342
6343               /* Create a duplicate of the base version with the same
6344                  aux block, but different flags.  */
6345               def.vd_flags = 0;
6346               def.vd_ndx = 2;
6347               def.vd_aux = sizeof (Elf_External_Verdef);
6348               if (verdefs)
6349                 def.vd_next = (sizeof (Elf_External_Verdef)
6350                                + sizeof (Elf_External_Verdaux));
6351               else
6352                 def.vd_next = 0;
6353               _bfd_elf_swap_verdef_out (output_bfd, &def,
6354                                         (Elf_External_Verdef *) p);
6355               p += sizeof (Elf_External_Verdef);
6356             }
6357           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6358                                      (Elf_External_Verdaux *) p);
6359           p += sizeof (Elf_External_Verdaux);
6360
6361           for (t = verdefs; t != NULL; t = t->next)
6362             {
6363               unsigned int cdeps;
6364               struct bfd_elf_version_deps *n;
6365
6366               /* Don't emit the base version twice.  */
6367               if (t->vernum == 0)
6368                 continue;
6369
6370               cdeps = 0;
6371               for (n = t->deps; n != NULL; n = n->next)
6372                 ++cdeps;
6373
6374               /* Add a symbol representing this version.  */
6375               bh = NULL;
6376               if (! (_bfd_generic_link_add_one_symbol
6377                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6378                       0, NULL, FALSE,
6379                       get_elf_backend_data (dynobj)->collect, &bh)))
6380                 return FALSE;
6381               h = (struct elf_link_hash_entry *) bh;
6382               h->non_elf = 0;
6383               h->def_regular = 1;
6384               h->type = STT_OBJECT;
6385               h->verinfo.vertree = t;
6386
6387               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6388                 return FALSE;
6389
6390               def.vd_version = VER_DEF_CURRENT;
6391               def.vd_flags = 0;
6392               if (t->globals.list == NULL
6393                   && t->locals.list == NULL
6394                   && ! t->used)
6395                 def.vd_flags |= VER_FLG_WEAK;
6396               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6397               def.vd_cnt = cdeps + 1;
6398               def.vd_hash = bfd_elf_hash (t->name);
6399               def.vd_aux = sizeof (Elf_External_Verdef);
6400               def.vd_next = 0;
6401
6402               /* If a basever node is next, it *must* be the last node in
6403                  the chain, otherwise Verdef construction breaks.  */
6404               if (t->next != NULL && t->next->vernum == 0)
6405                 BFD_ASSERT (t->next->next == NULL);
6406
6407               if (t->next != NULL && t->next->vernum != 0)
6408                 def.vd_next = (sizeof (Elf_External_Verdef)
6409                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6410
6411               _bfd_elf_swap_verdef_out (output_bfd, &def,
6412                                         (Elf_External_Verdef *) p);
6413               p += sizeof (Elf_External_Verdef);
6414
6415               defaux.vda_name = h->dynstr_index;
6416               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6417                                       h->dynstr_index);
6418               defaux.vda_next = 0;
6419               if (t->deps != NULL)
6420                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6421               t->name_indx = defaux.vda_name;
6422
6423               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6424                                          (Elf_External_Verdaux *) p);
6425               p += sizeof (Elf_External_Verdaux);
6426
6427               for (n = t->deps; n != NULL; n = n->next)
6428                 {
6429                   if (n->version_needed == NULL)
6430                     {
6431                       /* This can happen if there was an error in the
6432                          version script.  */
6433                       defaux.vda_name = 0;
6434                     }
6435                   else
6436                     {
6437                       defaux.vda_name = n->version_needed->name_indx;
6438                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6439                                               defaux.vda_name);
6440                     }
6441                   if (n->next == NULL)
6442                     defaux.vda_next = 0;
6443                   else
6444                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6445
6446                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6447                                              (Elf_External_Verdaux *) p);
6448                   p += sizeof (Elf_External_Verdaux);
6449                 }
6450             }
6451
6452           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6453               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6454             return FALSE;
6455
6456           elf_tdata (output_bfd)->cverdefs = cdefs;
6457         }
6458
6459       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6460         {
6461           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6462             return FALSE;
6463         }
6464       else if (info->flags & DF_BIND_NOW)
6465         {
6466           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6467             return FALSE;
6468         }
6469
6470       if (info->flags_1)
6471         {
6472           if (bfd_link_executable (info))
6473             info->flags_1 &= ~ (DF_1_INITFIRST
6474                                 | DF_1_NODELETE
6475                                 | DF_1_NOOPEN);
6476           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6477             return FALSE;
6478         }
6479
6480       /* Work out the size of the version reference section.  */
6481
6482       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6483       BFD_ASSERT (s != NULL);
6484       {
6485         struct elf_find_verdep_info sinfo;
6486
6487         sinfo.info = info;
6488         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6489         if (sinfo.vers == 0)
6490           sinfo.vers = 1;
6491         sinfo.failed = FALSE;
6492
6493         elf_link_hash_traverse (elf_hash_table (info),
6494                                 _bfd_elf_link_find_version_dependencies,
6495                                 &sinfo);
6496         if (sinfo.failed)
6497           return FALSE;
6498
6499         if (elf_tdata (output_bfd)->verref == NULL)
6500           s->flags |= SEC_EXCLUDE;
6501         else
6502           {
6503             Elf_Internal_Verneed *t;
6504             unsigned int size;
6505             unsigned int crefs;
6506             bfd_byte *p;
6507
6508             /* Build the version dependency section.  */
6509             size = 0;
6510             crefs = 0;
6511             for (t = elf_tdata (output_bfd)->verref;
6512                  t != NULL;
6513                  t = t->vn_nextref)
6514               {
6515                 Elf_Internal_Vernaux *a;
6516
6517                 size += sizeof (Elf_External_Verneed);
6518                 ++crefs;
6519                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6520                   size += sizeof (Elf_External_Vernaux);
6521               }
6522
6523             s->size = size;
6524             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6525             if (s->contents == NULL)
6526               return FALSE;
6527
6528             p = s->contents;
6529             for (t = elf_tdata (output_bfd)->verref;
6530                  t != NULL;
6531                  t = t->vn_nextref)
6532               {
6533                 unsigned int caux;
6534                 Elf_Internal_Vernaux *a;
6535                 size_t indx;
6536
6537                 caux = 0;
6538                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6539                   ++caux;
6540
6541                 t->vn_version = VER_NEED_CURRENT;
6542                 t->vn_cnt = caux;
6543                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6544                                             elf_dt_name (t->vn_bfd) != NULL
6545                                             ? elf_dt_name (t->vn_bfd)
6546                                             : lbasename (t->vn_bfd->filename),
6547                                             FALSE);
6548                 if (indx == (size_t) -1)
6549                   return FALSE;
6550                 t->vn_file = indx;
6551                 t->vn_aux = sizeof (Elf_External_Verneed);
6552                 if (t->vn_nextref == NULL)
6553                   t->vn_next = 0;
6554                 else
6555                   t->vn_next = (sizeof (Elf_External_Verneed)
6556                                 + caux * sizeof (Elf_External_Vernaux));
6557
6558                 _bfd_elf_swap_verneed_out (output_bfd, t,
6559                                            (Elf_External_Verneed *) p);
6560                 p += sizeof (Elf_External_Verneed);
6561
6562                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6563                   {
6564                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6565                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6566                                                 a->vna_nodename, FALSE);
6567                     if (indx == (size_t) -1)
6568                       return FALSE;
6569                     a->vna_name = indx;
6570                     if (a->vna_nextptr == NULL)
6571                       a->vna_next = 0;
6572                     else
6573                       a->vna_next = sizeof (Elf_External_Vernaux);
6574
6575                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6576                                                (Elf_External_Vernaux *) p);
6577                     p += sizeof (Elf_External_Vernaux);
6578                   }
6579               }
6580
6581             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6582                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6583               return FALSE;
6584
6585             elf_tdata (output_bfd)->cverrefs = crefs;
6586           }
6587       }
6588
6589       if ((elf_tdata (output_bfd)->cverrefs == 0
6590            && elf_tdata (output_bfd)->cverdefs == 0)
6591           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6592                                              &section_sym_count) == 0)
6593         {
6594           s = bfd_get_linker_section (dynobj, ".gnu.version");
6595           s->flags |= SEC_EXCLUDE;
6596         }
6597     }
6598   return TRUE;
6599 }
6600
6601 /* Find the first non-excluded output section.  We'll use its
6602    section symbol for some emitted relocs.  */
6603 void
6604 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6605 {
6606   asection *s;
6607
6608   for (s = output_bfd->sections; s != NULL; s = s->next)
6609     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6610         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6611       {
6612         elf_hash_table (info)->text_index_section = s;
6613         break;
6614       }
6615 }
6616
6617 /* Find two non-excluded output sections, one for code, one for data.
6618    We'll use their section symbols for some emitted relocs.  */
6619 void
6620 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6621 {
6622   asection *s;
6623
6624   /* Data first, since setting text_index_section changes
6625      _bfd_elf_link_omit_section_dynsym.  */
6626   for (s = output_bfd->sections; s != NULL; s = s->next)
6627     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6628         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6629       {
6630         elf_hash_table (info)->data_index_section = s;
6631         break;
6632       }
6633
6634   for (s = output_bfd->sections; s != NULL; s = s->next)
6635     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6636          == (SEC_ALLOC | SEC_READONLY))
6637         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6638       {
6639         elf_hash_table (info)->text_index_section = s;
6640         break;
6641       }
6642
6643   if (elf_hash_table (info)->text_index_section == NULL)
6644     elf_hash_table (info)->text_index_section
6645       = elf_hash_table (info)->data_index_section;
6646 }
6647
6648 bfd_boolean
6649 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6650 {
6651   const struct elf_backend_data *bed;
6652
6653   if (!is_elf_hash_table (info->hash))
6654     return TRUE;
6655
6656   bed = get_elf_backend_data (output_bfd);
6657   (*bed->elf_backend_init_index_section) (output_bfd, info);
6658
6659   if (elf_hash_table (info)->dynamic_sections_created)
6660     {
6661       bfd *dynobj;
6662       asection *s;
6663       bfd_size_type dynsymcount;
6664       unsigned long section_sym_count;
6665       unsigned int dtagcount;
6666
6667       dynobj = elf_hash_table (info)->dynobj;
6668
6669       /* Assign dynsym indicies.  In a shared library we generate a
6670          section symbol for each output section, which come first.
6671          Next come all of the back-end allocated local dynamic syms,
6672          followed by the rest of the global symbols.  */
6673
6674       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6675                                                     &section_sym_count);
6676
6677       /* Work out the size of the symbol version section.  */
6678       s = bfd_get_linker_section (dynobj, ".gnu.version");
6679       BFD_ASSERT (s != NULL);
6680       if ((s->flags & SEC_EXCLUDE) == 0)
6681         {
6682           s->size = dynsymcount * sizeof (Elf_External_Versym);
6683           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6684           if (s->contents == NULL)
6685             return FALSE;
6686
6687           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6688             return FALSE;
6689         }
6690
6691       /* Set the size of the .dynsym and .hash sections.  We counted
6692          the number of dynamic symbols in elf_link_add_object_symbols.
6693          We will build the contents of .dynsym and .hash when we build
6694          the final symbol table, because until then we do not know the
6695          correct value to give the symbols.  We built the .dynstr
6696          section as we went along in elf_link_add_object_symbols.  */
6697       s = elf_hash_table (info)->dynsym;
6698       BFD_ASSERT (s != NULL);
6699       s->size = dynsymcount * bed->s->sizeof_sym;
6700
6701       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6702       if (s->contents == NULL)
6703         return FALSE;
6704
6705       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6706          section syms, in case we don't output them all.  */
6707       ++section_sym_count;
6708       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6709
6710       elf_hash_table (info)->bucketcount = 0;
6711
6712       /* Compute the size of the hashing table.  As a side effect this
6713          computes the hash values for all the names we export.  */
6714       if (info->emit_hash)
6715         {
6716           unsigned long int *hashcodes;
6717           struct hash_codes_info hashinf;
6718           bfd_size_type amt;
6719           unsigned long int nsyms;
6720           size_t bucketcount;
6721           size_t hash_entry_size;
6722
6723           /* Compute the hash values for all exported symbols.  At the same
6724              time store the values in an array so that we could use them for
6725              optimizations.  */
6726           amt = dynsymcount * sizeof (unsigned long int);
6727           hashcodes = (unsigned long int *) bfd_malloc (amt);
6728           if (hashcodes == NULL)
6729             return FALSE;
6730           hashinf.hashcodes = hashcodes;
6731           hashinf.error = FALSE;
6732
6733           /* Put all hash values in HASHCODES.  */
6734           elf_link_hash_traverse (elf_hash_table (info),
6735                                   elf_collect_hash_codes, &hashinf);
6736           if (hashinf.error)
6737             {
6738               free (hashcodes);
6739               return FALSE;
6740             }
6741
6742           nsyms = hashinf.hashcodes - hashcodes;
6743           bucketcount
6744             = compute_bucket_count (info, hashcodes, nsyms, 0);
6745           free (hashcodes);
6746
6747           if (bucketcount == 0)
6748             return FALSE;
6749
6750           elf_hash_table (info)->bucketcount = bucketcount;
6751
6752           s = bfd_get_linker_section (dynobj, ".hash");
6753           BFD_ASSERT (s != NULL);
6754           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6755           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6756           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6757           if (s->contents == NULL)
6758             return FALSE;
6759
6760           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6761           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6762                    s->contents + hash_entry_size);
6763         }
6764
6765       if (info->emit_gnu_hash)
6766         {
6767           size_t i, cnt;
6768           unsigned char *contents;
6769           struct collect_gnu_hash_codes cinfo;
6770           bfd_size_type amt;
6771           size_t bucketcount;
6772
6773           memset (&cinfo, 0, sizeof (cinfo));
6774
6775           /* Compute the hash values for all exported symbols.  At the same
6776              time store the values in an array so that we could use them for
6777              optimizations.  */
6778           amt = dynsymcount * 2 * sizeof (unsigned long int);
6779           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6780           if (cinfo.hashcodes == NULL)
6781             return FALSE;
6782
6783           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6784           cinfo.min_dynindx = -1;
6785           cinfo.output_bfd = output_bfd;
6786           cinfo.bed = bed;
6787
6788           /* Put all hash values in HASHCODES.  */
6789           elf_link_hash_traverse (elf_hash_table (info),
6790                                   elf_collect_gnu_hash_codes, &cinfo);
6791           if (cinfo.error)
6792             {
6793               free (cinfo.hashcodes);
6794               return FALSE;
6795             }
6796
6797           bucketcount
6798             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6799
6800           if (bucketcount == 0)
6801             {
6802               free (cinfo.hashcodes);
6803               return FALSE;
6804             }
6805
6806           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6807           BFD_ASSERT (s != NULL);
6808
6809           if (cinfo.nsyms == 0)
6810             {
6811               /* Empty .gnu.hash section is special.  */
6812               BFD_ASSERT (cinfo.min_dynindx == -1);
6813               free (cinfo.hashcodes);
6814               s->size = 5 * 4 + bed->s->arch_size / 8;
6815               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6816               if (contents == NULL)
6817                 return FALSE;
6818               s->contents = contents;
6819               /* 1 empty bucket.  */
6820               bfd_put_32 (output_bfd, 1, contents);
6821               /* SYMIDX above the special symbol 0.  */
6822               bfd_put_32 (output_bfd, 1, contents + 4);
6823               /* Just one word for bitmask.  */
6824               bfd_put_32 (output_bfd, 1, contents + 8);
6825               /* Only hash fn bloom filter.  */
6826               bfd_put_32 (output_bfd, 0, contents + 12);
6827               /* No hashes are valid - empty bitmask.  */
6828               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6829               /* No hashes in the only bucket.  */
6830               bfd_put_32 (output_bfd, 0,
6831                           contents + 16 + bed->s->arch_size / 8);
6832             }
6833           else
6834             {
6835               unsigned long int maskwords, maskbitslog2, x;
6836               BFD_ASSERT (cinfo.min_dynindx != -1);
6837
6838               x = cinfo.nsyms;
6839               maskbitslog2 = 1;
6840               while ((x >>= 1) != 0)
6841                 ++maskbitslog2;
6842               if (maskbitslog2 < 3)
6843                 maskbitslog2 = 5;
6844               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6845                 maskbitslog2 = maskbitslog2 + 3;
6846               else
6847                 maskbitslog2 = maskbitslog2 + 2;
6848               if (bed->s->arch_size == 64)
6849                 {
6850                   if (maskbitslog2 == 5)
6851                     maskbitslog2 = 6;
6852                   cinfo.shift1 = 6;
6853                 }
6854               else
6855                 cinfo.shift1 = 5;
6856               cinfo.mask = (1 << cinfo.shift1) - 1;
6857               cinfo.shift2 = maskbitslog2;
6858               cinfo.maskbits = 1 << maskbitslog2;
6859               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6860               amt = bucketcount * sizeof (unsigned long int) * 2;
6861               amt += maskwords * sizeof (bfd_vma);
6862               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6863               if (cinfo.bitmask == NULL)
6864                 {
6865                   free (cinfo.hashcodes);
6866                   return FALSE;
6867                 }
6868
6869               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6870               cinfo.indx = cinfo.counts + bucketcount;
6871               cinfo.symindx = dynsymcount - cinfo.nsyms;
6872               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6873
6874               /* Determine how often each hash bucket is used.  */
6875               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6876               for (i = 0; i < cinfo.nsyms; ++i)
6877                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6878
6879               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6880                 if (cinfo.counts[i] != 0)
6881                   {
6882                     cinfo.indx[i] = cnt;
6883                     cnt += cinfo.counts[i];
6884                   }
6885               BFD_ASSERT (cnt == dynsymcount);
6886               cinfo.bucketcount = bucketcount;
6887               cinfo.local_indx = cinfo.min_dynindx;
6888
6889               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6890               s->size += cinfo.maskbits / 8;
6891               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6892               if (contents == NULL)
6893                 {
6894                   free (cinfo.bitmask);
6895                   free (cinfo.hashcodes);
6896                   return FALSE;
6897                 }
6898
6899               s->contents = contents;
6900               bfd_put_32 (output_bfd, bucketcount, contents);
6901               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6902               bfd_put_32 (output_bfd, maskwords, contents + 8);
6903               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6904               contents += 16 + cinfo.maskbits / 8;
6905
6906               for (i = 0; i < bucketcount; ++i)
6907                 {
6908                   if (cinfo.counts[i] == 0)
6909                     bfd_put_32 (output_bfd, 0, contents);
6910                   else
6911                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6912                   contents += 4;
6913                 }
6914
6915               cinfo.contents = contents;
6916
6917               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6918               elf_link_hash_traverse (elf_hash_table (info),
6919                                       elf_renumber_gnu_hash_syms, &cinfo);
6920
6921               contents = s->contents + 16;
6922               for (i = 0; i < maskwords; ++i)
6923                 {
6924                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6925                            contents);
6926                   contents += bed->s->arch_size / 8;
6927                 }
6928
6929               free (cinfo.bitmask);
6930               free (cinfo.hashcodes);
6931             }
6932         }
6933
6934       s = bfd_get_linker_section (dynobj, ".dynstr");
6935       BFD_ASSERT (s != NULL);
6936
6937       elf_finalize_dynstr (output_bfd, info);
6938
6939       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6940
6941       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6942         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6943           return FALSE;
6944     }
6945
6946   return TRUE;
6947 }
6948 \f
6949 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6950
6951 static void
6952 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6953                             asection *sec)
6954 {
6955   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6956   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6957 }
6958
6959 /* Finish SHF_MERGE section merging.  */
6960
6961 bfd_boolean
6962 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
6963 {
6964   bfd *ibfd;
6965   asection *sec;
6966
6967   if (!is_elf_hash_table (info->hash))
6968     return FALSE;
6969
6970   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6971     if ((ibfd->flags & DYNAMIC) == 0
6972         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6973         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
6974             == get_elf_backend_data (obfd)->s->elfclass))
6975       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6976         if ((sec->flags & SEC_MERGE) != 0
6977             && !bfd_is_abs_section (sec->output_section))
6978           {
6979             struct bfd_elf_section_data *secdata;
6980
6981             secdata = elf_section_data (sec);
6982             if (! _bfd_add_merge_section (obfd,
6983                                           &elf_hash_table (info)->merge_info,
6984                                           sec, &secdata->sec_info))
6985               return FALSE;
6986             else if (secdata->sec_info)
6987               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6988           }
6989
6990   if (elf_hash_table (info)->merge_info != NULL)
6991     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
6992                          merge_sections_remove_hook);
6993   return TRUE;
6994 }
6995
6996 /* Create an entry in an ELF linker hash table.  */
6997
6998 struct bfd_hash_entry *
6999 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7000                             struct bfd_hash_table *table,
7001                             const char *string)
7002 {
7003   /* Allocate the structure if it has not already been allocated by a
7004      subclass.  */
7005   if (entry == NULL)
7006     {
7007       entry = (struct bfd_hash_entry *)
7008         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7009       if (entry == NULL)
7010         return entry;
7011     }
7012
7013   /* Call the allocation method of the superclass.  */
7014   entry = _bfd_link_hash_newfunc (entry, table, string);
7015   if (entry != NULL)
7016     {
7017       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7018       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7019
7020       /* Set local fields.  */
7021       ret->indx = -1;
7022       ret->dynindx = -1;
7023       ret->got = htab->init_got_refcount;
7024       ret->plt = htab->init_plt_refcount;
7025       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7026                               - offsetof (struct elf_link_hash_entry, size)));
7027       /* Assume that we have been called by a non-ELF symbol reader.
7028          This flag is then reset by the code which reads an ELF input
7029          file.  This ensures that a symbol created by a non-ELF symbol
7030          reader will have the flag set correctly.  */
7031       ret->non_elf = 1;
7032     }
7033
7034   return entry;
7035 }
7036
7037 /* Copy data from an indirect symbol to its direct symbol, hiding the
7038    old indirect symbol.  Also used for copying flags to a weakdef.  */
7039
7040 void
7041 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7042                                   struct elf_link_hash_entry *dir,
7043                                   struct elf_link_hash_entry *ind)
7044 {
7045   struct elf_link_hash_table *htab;
7046
7047   /* Copy down any references that we may have already seen to the
7048      symbol which just became indirect if DIR isn't a hidden versioned
7049      symbol.  */
7050
7051   if (dir->versioned != versioned_hidden)
7052     {
7053       dir->ref_dynamic |= ind->ref_dynamic;
7054       dir->ref_regular |= ind->ref_regular;
7055       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7056       dir->non_got_ref |= ind->non_got_ref;
7057       dir->needs_plt |= ind->needs_plt;
7058       dir->pointer_equality_needed |= ind->pointer_equality_needed;
7059     }
7060
7061   if (ind->root.type != bfd_link_hash_indirect)
7062     return;
7063
7064   /* Copy over the global and procedure linkage table refcount entries.
7065      These may have been already set up by a check_relocs routine.  */
7066   htab = elf_hash_table (info);
7067   if (ind->got.refcount > htab->init_got_refcount.refcount)
7068     {
7069       if (dir->got.refcount < 0)
7070         dir->got.refcount = 0;
7071       dir->got.refcount += ind->got.refcount;
7072       ind->got.refcount = htab->init_got_refcount.refcount;
7073     }
7074
7075   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7076     {
7077       if (dir->plt.refcount < 0)
7078         dir->plt.refcount = 0;
7079       dir->plt.refcount += ind->plt.refcount;
7080       ind->plt.refcount = htab->init_plt_refcount.refcount;
7081     }
7082
7083   if (ind->dynindx != -1)
7084     {
7085       if (dir->dynindx != -1)
7086         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7087       dir->dynindx = ind->dynindx;
7088       dir->dynstr_index = ind->dynstr_index;
7089       ind->dynindx = -1;
7090       ind->dynstr_index = 0;
7091     }
7092 }
7093
7094 void
7095 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7096                                 struct elf_link_hash_entry *h,
7097                                 bfd_boolean force_local)
7098 {
7099   /* STT_GNU_IFUNC symbol must go through PLT.  */
7100   if (h->type != STT_GNU_IFUNC)
7101     {
7102       h->plt = elf_hash_table (info)->init_plt_offset;
7103       h->needs_plt = 0;
7104     }
7105   if (force_local)
7106     {
7107       h->forced_local = 1;
7108       if (h->dynindx != -1)
7109         {
7110           h->dynindx = -1;
7111           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7112                                   h->dynstr_index);
7113         }
7114     }
7115 }
7116
7117 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7118    caller.  */
7119
7120 bfd_boolean
7121 _bfd_elf_link_hash_table_init
7122   (struct elf_link_hash_table *table,
7123    bfd *abfd,
7124    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7125                                       struct bfd_hash_table *,
7126                                       const char *),
7127    unsigned int entsize,
7128    enum elf_target_id target_id)
7129 {
7130   bfd_boolean ret;
7131   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7132
7133   table->init_got_refcount.refcount = can_refcount - 1;
7134   table->init_plt_refcount.refcount = can_refcount - 1;
7135   table->init_got_offset.offset = -(bfd_vma) 1;
7136   table->init_plt_offset.offset = -(bfd_vma) 1;
7137   /* The first dynamic symbol is a dummy.  */
7138   table->dynsymcount = 1;
7139
7140   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7141
7142   table->root.type = bfd_link_elf_hash_table;
7143   table->hash_table_id = target_id;
7144
7145   return ret;
7146 }
7147
7148 /* Create an ELF linker hash table.  */
7149
7150 struct bfd_link_hash_table *
7151 _bfd_elf_link_hash_table_create (bfd *abfd)
7152 {
7153   struct elf_link_hash_table *ret;
7154   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7155
7156   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7157   if (ret == NULL)
7158     return NULL;
7159
7160   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7161                                        sizeof (struct elf_link_hash_entry),
7162                                        GENERIC_ELF_DATA))
7163     {
7164       free (ret);
7165       return NULL;
7166     }
7167   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7168
7169   return &ret->root;
7170 }
7171
7172 /* Destroy an ELF linker hash table.  */
7173
7174 void
7175 _bfd_elf_link_hash_table_free (bfd *obfd)
7176 {
7177   struct elf_link_hash_table *htab;
7178
7179   htab = (struct elf_link_hash_table *) obfd->link.hash;
7180   if (htab->dynstr != NULL)
7181     _bfd_elf_strtab_free (htab->dynstr);
7182   _bfd_merge_sections_free (htab->merge_info);
7183   _bfd_generic_link_hash_table_free (obfd);
7184 }
7185
7186 /* This is a hook for the ELF emulation code in the generic linker to
7187    tell the backend linker what file name to use for the DT_NEEDED
7188    entry for a dynamic object.  */
7189
7190 void
7191 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7192 {
7193   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7194       && bfd_get_format (abfd) == bfd_object)
7195     elf_dt_name (abfd) = name;
7196 }
7197
7198 int
7199 bfd_elf_get_dyn_lib_class (bfd *abfd)
7200 {
7201   int lib_class;
7202   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7203       && bfd_get_format (abfd) == bfd_object)
7204     lib_class = elf_dyn_lib_class (abfd);
7205   else
7206     lib_class = 0;
7207   return lib_class;
7208 }
7209
7210 void
7211 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7212 {
7213   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7214       && bfd_get_format (abfd) == bfd_object)
7215     elf_dyn_lib_class (abfd) = lib_class;
7216 }
7217
7218 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7219    the linker ELF emulation code.  */
7220
7221 struct bfd_link_needed_list *
7222 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7223                          struct bfd_link_info *info)
7224 {
7225   if (! is_elf_hash_table (info->hash))
7226     return NULL;
7227   return elf_hash_table (info)->needed;
7228 }
7229
7230 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7231    hook for the linker ELF emulation code.  */
7232
7233 struct bfd_link_needed_list *
7234 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7235                           struct bfd_link_info *info)
7236 {
7237   if (! is_elf_hash_table (info->hash))
7238     return NULL;
7239   return elf_hash_table (info)->runpath;
7240 }
7241
7242 /* Get the name actually used for a dynamic object for a link.  This
7243    is the SONAME entry if there is one.  Otherwise, it is the string
7244    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7245
7246 const char *
7247 bfd_elf_get_dt_soname (bfd *abfd)
7248 {
7249   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7250       && bfd_get_format (abfd) == bfd_object)
7251     return elf_dt_name (abfd);
7252   return NULL;
7253 }
7254
7255 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7256    the ELF linker emulation code.  */
7257
7258 bfd_boolean
7259 bfd_elf_get_bfd_needed_list (bfd *abfd,
7260                              struct bfd_link_needed_list **pneeded)
7261 {
7262   asection *s;
7263   bfd_byte *dynbuf = NULL;
7264   unsigned int elfsec;
7265   unsigned long shlink;
7266   bfd_byte *extdyn, *extdynend;
7267   size_t extdynsize;
7268   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7269
7270   *pneeded = NULL;
7271
7272   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7273       || bfd_get_format (abfd) != bfd_object)
7274     return TRUE;
7275
7276   s = bfd_get_section_by_name (abfd, ".dynamic");
7277   if (s == NULL || s->size == 0)
7278     return TRUE;
7279
7280   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7281     goto error_return;
7282
7283   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7284   if (elfsec == SHN_BAD)
7285     goto error_return;
7286
7287   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7288
7289   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7290   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7291
7292   extdyn = dynbuf;
7293   extdynend = extdyn + s->size;
7294   for (; extdyn < extdynend; extdyn += extdynsize)
7295     {
7296       Elf_Internal_Dyn dyn;
7297
7298       (*swap_dyn_in) (abfd, extdyn, &dyn);
7299
7300       if (dyn.d_tag == DT_NULL)
7301         break;
7302
7303       if (dyn.d_tag == DT_NEEDED)
7304         {
7305           const char *string;
7306           struct bfd_link_needed_list *l;
7307           unsigned int tagv = dyn.d_un.d_val;
7308           bfd_size_type amt;
7309
7310           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7311           if (string == NULL)
7312             goto error_return;
7313
7314           amt = sizeof *l;
7315           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7316           if (l == NULL)
7317             goto error_return;
7318
7319           l->by = abfd;
7320           l->name = string;
7321           l->next = *pneeded;
7322           *pneeded = l;
7323         }
7324     }
7325
7326   free (dynbuf);
7327
7328   return TRUE;
7329
7330  error_return:
7331   if (dynbuf != NULL)
7332     free (dynbuf);
7333   return FALSE;
7334 }
7335
7336 struct elf_symbuf_symbol
7337 {
7338   unsigned long st_name;        /* Symbol name, index in string tbl */
7339   unsigned char st_info;        /* Type and binding attributes */
7340   unsigned char st_other;       /* Visibilty, and target specific */
7341 };
7342
7343 struct elf_symbuf_head
7344 {
7345   struct elf_symbuf_symbol *ssym;
7346   size_t count;
7347   unsigned int st_shndx;
7348 };
7349
7350 struct elf_symbol
7351 {
7352   union
7353     {
7354       Elf_Internal_Sym *isym;
7355       struct elf_symbuf_symbol *ssym;
7356     } u;
7357   const char *name;
7358 };
7359
7360 /* Sort references to symbols by ascending section number.  */
7361
7362 static int
7363 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7364 {
7365   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7366   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7367
7368   return s1->st_shndx - s2->st_shndx;
7369 }
7370
7371 static int
7372 elf_sym_name_compare (const void *arg1, const void *arg2)
7373 {
7374   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7375   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7376   return strcmp (s1->name, s2->name);
7377 }
7378
7379 static struct elf_symbuf_head *
7380 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7381 {
7382   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7383   struct elf_symbuf_symbol *ssym;
7384   struct elf_symbuf_head *ssymbuf, *ssymhead;
7385   size_t i, shndx_count, total_size;
7386
7387   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7388   if (indbuf == NULL)
7389     return NULL;
7390
7391   for (ind = indbuf, i = 0; i < symcount; i++)
7392     if (isymbuf[i].st_shndx != SHN_UNDEF)
7393       *ind++ = &isymbuf[i];
7394   indbufend = ind;
7395
7396   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7397          elf_sort_elf_symbol);
7398
7399   shndx_count = 0;
7400   if (indbufend > indbuf)
7401     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7402       if (ind[0]->st_shndx != ind[1]->st_shndx)
7403         shndx_count++;
7404
7405   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7406                 + (indbufend - indbuf) * sizeof (*ssym));
7407   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7408   if (ssymbuf == NULL)
7409     {
7410       free (indbuf);
7411       return NULL;
7412     }
7413
7414   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7415   ssymbuf->ssym = NULL;
7416   ssymbuf->count = shndx_count;
7417   ssymbuf->st_shndx = 0;
7418   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7419     {
7420       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7421         {
7422           ssymhead++;
7423           ssymhead->ssym = ssym;
7424           ssymhead->count = 0;
7425           ssymhead->st_shndx = (*ind)->st_shndx;
7426         }
7427       ssym->st_name = (*ind)->st_name;
7428       ssym->st_info = (*ind)->st_info;
7429       ssym->st_other = (*ind)->st_other;
7430       ssymhead->count++;
7431     }
7432   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7433               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7434                   == total_size));
7435
7436   free (indbuf);
7437   return ssymbuf;
7438 }
7439
7440 /* Check if 2 sections define the same set of local and global
7441    symbols.  */
7442
7443 static bfd_boolean
7444 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7445                                    struct bfd_link_info *info)
7446 {
7447   bfd *bfd1, *bfd2;
7448   const struct elf_backend_data *bed1, *bed2;
7449   Elf_Internal_Shdr *hdr1, *hdr2;
7450   size_t symcount1, symcount2;
7451   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7452   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7453   Elf_Internal_Sym *isym, *isymend;
7454   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7455   size_t count1, count2, i;
7456   unsigned int shndx1, shndx2;
7457   bfd_boolean result;
7458
7459   bfd1 = sec1->owner;
7460   bfd2 = sec2->owner;
7461
7462   /* Both sections have to be in ELF.  */
7463   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7464       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7465     return FALSE;
7466
7467   if (elf_section_type (sec1) != elf_section_type (sec2))
7468     return FALSE;
7469
7470   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7471   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7472   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7473     return FALSE;
7474
7475   bed1 = get_elf_backend_data (bfd1);
7476   bed2 = get_elf_backend_data (bfd2);
7477   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7478   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7479   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7480   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7481
7482   if (symcount1 == 0 || symcount2 == 0)
7483     return FALSE;
7484
7485   result = FALSE;
7486   isymbuf1 = NULL;
7487   isymbuf2 = NULL;
7488   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7489   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7490
7491   if (ssymbuf1 == NULL)
7492     {
7493       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7494                                        NULL, NULL, NULL);
7495       if (isymbuf1 == NULL)
7496         goto done;
7497
7498       if (!info->reduce_memory_overheads)
7499         elf_tdata (bfd1)->symbuf = ssymbuf1
7500           = elf_create_symbuf (symcount1, isymbuf1);
7501     }
7502
7503   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7504     {
7505       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7506                                        NULL, NULL, NULL);
7507       if (isymbuf2 == NULL)
7508         goto done;
7509
7510       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7511         elf_tdata (bfd2)->symbuf = ssymbuf2
7512           = elf_create_symbuf (symcount2, isymbuf2);
7513     }
7514
7515   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7516     {
7517       /* Optimized faster version.  */
7518       size_t lo, hi, mid;
7519       struct elf_symbol *symp;
7520       struct elf_symbuf_symbol *ssym, *ssymend;
7521
7522       lo = 0;
7523       hi = ssymbuf1->count;
7524       ssymbuf1++;
7525       count1 = 0;
7526       while (lo < hi)
7527         {
7528           mid = (lo + hi) / 2;
7529           if (shndx1 < ssymbuf1[mid].st_shndx)
7530             hi = mid;
7531           else if (shndx1 > ssymbuf1[mid].st_shndx)
7532             lo = mid + 1;
7533           else
7534             {
7535               count1 = ssymbuf1[mid].count;
7536               ssymbuf1 += mid;
7537               break;
7538             }
7539         }
7540
7541       lo = 0;
7542       hi = ssymbuf2->count;
7543       ssymbuf2++;
7544       count2 = 0;
7545       while (lo < hi)
7546         {
7547           mid = (lo + hi) / 2;
7548           if (shndx2 < ssymbuf2[mid].st_shndx)
7549             hi = mid;
7550           else if (shndx2 > ssymbuf2[mid].st_shndx)
7551             lo = mid + 1;
7552           else
7553             {
7554               count2 = ssymbuf2[mid].count;
7555               ssymbuf2 += mid;
7556               break;
7557             }
7558         }
7559
7560       if (count1 == 0 || count2 == 0 || count1 != count2)
7561         goto done;
7562
7563       symtable1
7564         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7565       symtable2
7566         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7567       if (symtable1 == NULL || symtable2 == NULL)
7568         goto done;
7569
7570       symp = symtable1;
7571       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7572            ssym < ssymend; ssym++, symp++)
7573         {
7574           symp->u.ssym = ssym;
7575           symp->name = bfd_elf_string_from_elf_section (bfd1,
7576                                                         hdr1->sh_link,
7577                                                         ssym->st_name);
7578         }
7579
7580       symp = symtable2;
7581       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7582            ssym < ssymend; ssym++, symp++)
7583         {
7584           symp->u.ssym = ssym;
7585           symp->name = bfd_elf_string_from_elf_section (bfd2,
7586                                                         hdr2->sh_link,
7587                                                         ssym->st_name);
7588         }
7589
7590       /* Sort symbol by name.  */
7591       qsort (symtable1, count1, sizeof (struct elf_symbol),
7592              elf_sym_name_compare);
7593       qsort (symtable2, count1, sizeof (struct elf_symbol),
7594              elf_sym_name_compare);
7595
7596       for (i = 0; i < count1; i++)
7597         /* Two symbols must have the same binding, type and name.  */
7598         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7599             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7600             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7601           goto done;
7602
7603       result = TRUE;
7604       goto done;
7605     }
7606
7607   symtable1 = (struct elf_symbol *)
7608       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7609   symtable2 = (struct elf_symbol *)
7610       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7611   if (symtable1 == NULL || symtable2 == NULL)
7612     goto done;
7613
7614   /* Count definitions in the section.  */
7615   count1 = 0;
7616   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7617     if (isym->st_shndx == shndx1)
7618       symtable1[count1++].u.isym = isym;
7619
7620   count2 = 0;
7621   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7622     if (isym->st_shndx == shndx2)
7623       symtable2[count2++].u.isym = isym;
7624
7625   if (count1 == 0 || count2 == 0 || count1 != count2)
7626     goto done;
7627
7628   for (i = 0; i < count1; i++)
7629     symtable1[i].name
7630       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7631                                          symtable1[i].u.isym->st_name);
7632
7633   for (i = 0; i < count2; i++)
7634     symtable2[i].name
7635       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7636                                          symtable2[i].u.isym->st_name);
7637
7638   /* Sort symbol by name.  */
7639   qsort (symtable1, count1, sizeof (struct elf_symbol),
7640          elf_sym_name_compare);
7641   qsort (symtable2, count1, sizeof (struct elf_symbol),
7642          elf_sym_name_compare);
7643
7644   for (i = 0; i < count1; i++)
7645     /* Two symbols must have the same binding, type and name.  */
7646     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7647         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7648         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7649       goto done;
7650
7651   result = TRUE;
7652
7653 done:
7654   if (symtable1)
7655     free (symtable1);
7656   if (symtable2)
7657     free (symtable2);
7658   if (isymbuf1)
7659     free (isymbuf1);
7660   if (isymbuf2)
7661     free (isymbuf2);
7662
7663   return result;
7664 }
7665
7666 /* Return TRUE if 2 section types are compatible.  */
7667
7668 bfd_boolean
7669 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7670                                  bfd *bbfd, const asection *bsec)
7671 {
7672   if (asec == NULL
7673       || bsec == NULL
7674       || abfd->xvec->flavour != bfd_target_elf_flavour
7675       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7676     return TRUE;
7677
7678   return elf_section_type (asec) == elf_section_type (bsec);
7679 }
7680 \f
7681 /* Final phase of ELF linker.  */
7682
7683 /* A structure we use to avoid passing large numbers of arguments.  */
7684
7685 struct elf_final_link_info
7686 {
7687   /* General link information.  */
7688   struct bfd_link_info *info;
7689   /* Output BFD.  */
7690   bfd *output_bfd;
7691   /* Symbol string table.  */
7692   struct elf_strtab_hash *symstrtab;
7693   /* .hash section.  */
7694   asection *hash_sec;
7695   /* symbol version section (.gnu.version).  */
7696   asection *symver_sec;
7697   /* Buffer large enough to hold contents of any section.  */
7698   bfd_byte *contents;
7699   /* Buffer large enough to hold external relocs of any section.  */
7700   void *external_relocs;
7701   /* Buffer large enough to hold internal relocs of any section.  */
7702   Elf_Internal_Rela *internal_relocs;
7703   /* Buffer large enough to hold external local symbols of any input
7704      BFD.  */
7705   bfd_byte *external_syms;
7706   /* And a buffer for symbol section indices.  */
7707   Elf_External_Sym_Shndx *locsym_shndx;
7708   /* Buffer large enough to hold internal local symbols of any input
7709      BFD.  */
7710   Elf_Internal_Sym *internal_syms;
7711   /* Array large enough to hold a symbol index for each local symbol
7712      of any input BFD.  */
7713   long *indices;
7714   /* Array large enough to hold a section pointer for each local
7715      symbol of any input BFD.  */
7716   asection **sections;
7717   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7718   Elf_External_Sym_Shndx *symshndxbuf;
7719   /* Number of STT_FILE syms seen.  */
7720   size_t filesym_count;
7721 };
7722
7723 /* This struct is used to pass information to elf_link_output_extsym.  */
7724
7725 struct elf_outext_info
7726 {
7727   bfd_boolean failed;
7728   bfd_boolean localsyms;
7729   bfd_boolean file_sym_done;
7730   struct elf_final_link_info *flinfo;
7731 };
7732
7733
7734 /* Support for evaluating a complex relocation.
7735
7736    Complex relocations are generalized, self-describing relocations.  The
7737    implementation of them consists of two parts: complex symbols, and the
7738    relocations themselves.
7739
7740    The relocations are use a reserved elf-wide relocation type code (R_RELC
7741    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7742    information (start bit, end bit, word width, etc) into the addend.  This
7743    information is extracted from CGEN-generated operand tables within gas.
7744
7745    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7746    internal) representing prefix-notation expressions, including but not
7747    limited to those sorts of expressions normally encoded as addends in the
7748    addend field.  The symbol mangling format is:
7749
7750    <node> := <literal>
7751           |  <unary-operator> ':' <node>
7752           |  <binary-operator> ':' <node> ':' <node>
7753           ;
7754
7755    <literal> := 's' <digits=N> ':' <N character symbol name>
7756              |  'S' <digits=N> ':' <N character section name>
7757              |  '#' <hexdigits>
7758              ;
7759
7760    <binary-operator> := as in C
7761    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7762
7763 static void
7764 set_symbol_value (bfd *bfd_with_globals,
7765                   Elf_Internal_Sym *isymbuf,
7766                   size_t locsymcount,
7767                   size_t symidx,
7768                   bfd_vma val)
7769 {
7770   struct elf_link_hash_entry **sym_hashes;
7771   struct elf_link_hash_entry *h;
7772   size_t extsymoff = locsymcount;
7773
7774   if (symidx < locsymcount)
7775     {
7776       Elf_Internal_Sym *sym;
7777
7778       sym = isymbuf + symidx;
7779       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7780         {
7781           /* It is a local symbol: move it to the
7782              "absolute" section and give it a value.  */
7783           sym->st_shndx = SHN_ABS;
7784           sym->st_value = val;
7785           return;
7786         }
7787       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7788       extsymoff = 0;
7789     }
7790
7791   /* It is a global symbol: set its link type
7792      to "defined" and give it a value.  */
7793
7794   sym_hashes = elf_sym_hashes (bfd_with_globals);
7795   h = sym_hashes [symidx - extsymoff];
7796   while (h->root.type == bfd_link_hash_indirect
7797          || h->root.type == bfd_link_hash_warning)
7798     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7799   h->root.type = bfd_link_hash_defined;
7800   h->root.u.def.value = val;
7801   h->root.u.def.section = bfd_abs_section_ptr;
7802 }
7803
7804 static bfd_boolean
7805 resolve_symbol (const char *name,
7806                 bfd *input_bfd,
7807                 struct elf_final_link_info *flinfo,
7808                 bfd_vma *result,
7809                 Elf_Internal_Sym *isymbuf,
7810                 size_t locsymcount)
7811 {
7812   Elf_Internal_Sym *sym;
7813   struct bfd_link_hash_entry *global_entry;
7814   const char *candidate = NULL;
7815   Elf_Internal_Shdr *symtab_hdr;
7816   size_t i;
7817
7818   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7819
7820   for (i = 0; i < locsymcount; ++ i)
7821     {
7822       sym = isymbuf + i;
7823
7824       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7825         continue;
7826
7827       candidate = bfd_elf_string_from_elf_section (input_bfd,
7828                                                    symtab_hdr->sh_link,
7829                                                    sym->st_name);
7830 #ifdef DEBUG
7831       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7832               name, candidate, (unsigned long) sym->st_value);
7833 #endif
7834       if (candidate && strcmp (candidate, name) == 0)
7835         {
7836           asection *sec = flinfo->sections [i];
7837
7838           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7839           *result += sec->output_offset + sec->output_section->vma;
7840 #ifdef DEBUG
7841           printf ("Found symbol with value %8.8lx\n",
7842                   (unsigned long) *result);
7843 #endif
7844           return TRUE;
7845         }
7846     }
7847
7848   /* Hmm, haven't found it yet. perhaps it is a global.  */
7849   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7850                                        FALSE, FALSE, TRUE);
7851   if (!global_entry)
7852     return FALSE;
7853
7854   if (global_entry->type == bfd_link_hash_defined
7855       || global_entry->type == bfd_link_hash_defweak)
7856     {
7857       *result = (global_entry->u.def.value
7858                  + global_entry->u.def.section->output_section->vma
7859                  + global_entry->u.def.section->output_offset);
7860 #ifdef DEBUG
7861       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7862               global_entry->root.string, (unsigned long) *result);
7863 #endif
7864       return TRUE;
7865     }
7866
7867   return FALSE;
7868 }
7869
7870 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
7871    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
7872    names like "foo.end" which is the end address of section "foo".  */
7873    
7874 static bfd_boolean
7875 resolve_section (const char *name,
7876                  asection *sections,
7877                  bfd_vma *result,
7878                  bfd * abfd)
7879 {
7880   asection *curr;
7881   unsigned int len;
7882
7883   for (curr = sections; curr; curr = curr->next)
7884     if (strcmp (curr->name, name) == 0)
7885       {
7886         *result = curr->vma;
7887         return TRUE;
7888       }
7889
7890   /* Hmm. still haven't found it. try pseudo-section names.  */
7891   /* FIXME: This could be coded more efficiently...  */
7892   for (curr = sections; curr; curr = curr->next)
7893     {
7894       len = strlen (curr->name);
7895       if (len > strlen (name))
7896         continue;
7897
7898       if (strncmp (curr->name, name, len) == 0)
7899         {
7900           if (strncmp (".end", name + len, 4) == 0)
7901             {
7902               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
7903               return TRUE;
7904             }
7905
7906           /* Insert more pseudo-section names here, if you like.  */
7907         }
7908     }
7909
7910   return FALSE;
7911 }
7912
7913 static void
7914 undefined_reference (const char *reftype, const char *name)
7915 {
7916   /* xgettext:c-format */
7917   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7918                       reftype, name);
7919 }
7920
7921 static bfd_boolean
7922 eval_symbol (bfd_vma *result,
7923              const char **symp,
7924              bfd *input_bfd,
7925              struct elf_final_link_info *flinfo,
7926              bfd_vma dot,
7927              Elf_Internal_Sym *isymbuf,
7928              size_t locsymcount,
7929              int signed_p)
7930 {
7931   size_t len;
7932   size_t symlen;
7933   bfd_vma a;
7934   bfd_vma b;
7935   char symbuf[4096];
7936   const char *sym = *symp;
7937   const char *symend;
7938   bfd_boolean symbol_is_section = FALSE;
7939
7940   len = strlen (sym);
7941   symend = sym + len;
7942
7943   if (len < 1 || len > sizeof (symbuf))
7944     {
7945       bfd_set_error (bfd_error_invalid_operation);
7946       return FALSE;
7947     }
7948
7949   switch (* sym)
7950     {
7951     case '.':
7952       *result = dot;
7953       *symp = sym + 1;
7954       return TRUE;
7955
7956     case '#':
7957       ++sym;
7958       *result = strtoul (sym, (char **) symp, 16);
7959       return TRUE;
7960
7961     case 'S':
7962       symbol_is_section = TRUE;
7963       /* Fall through.  */
7964     case 's':
7965       ++sym;
7966       symlen = strtol (sym, (char **) symp, 10);
7967       sym = *symp + 1; /* Skip the trailing ':'.  */
7968
7969       if (symend < sym || symlen + 1 > sizeof (symbuf))
7970         {
7971           bfd_set_error (bfd_error_invalid_operation);
7972           return FALSE;
7973         }
7974
7975       memcpy (symbuf, sym, symlen);
7976       symbuf[symlen] = '\0';
7977       *symp = sym + symlen;
7978
7979       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7980          the symbol as a section, or vice-versa. so we're pretty liberal in our
7981          interpretation here; section means "try section first", not "must be a
7982          section", and likewise with symbol.  */
7983
7984       if (symbol_is_section)
7985         {
7986           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
7987               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7988                                   isymbuf, locsymcount))
7989             {
7990               undefined_reference ("section", symbuf);
7991               return FALSE;
7992             }
7993         }
7994       else
7995         {
7996           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7997                                isymbuf, locsymcount)
7998               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7999                                    result, input_bfd))
8000             {
8001               undefined_reference ("symbol", symbuf);
8002               return FALSE;
8003             }
8004         }
8005
8006       return TRUE;
8007
8008       /* All that remains are operators.  */
8009
8010 #define UNARY_OP(op)                                            \
8011   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8012     {                                                           \
8013       sym += strlen (#op);                                      \
8014       if (*sym == ':')                                          \
8015         ++sym;                                                  \
8016       *symp = sym;                                              \
8017       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8018                         isymbuf, locsymcount, signed_p))        \
8019         return FALSE;                                           \
8020       if (signed_p)                                             \
8021         *result = op ((bfd_signed_vma) a);                      \
8022       else                                                      \
8023         *result = op a;                                         \
8024       return TRUE;                                              \
8025     }
8026
8027 #define BINARY_OP(op)                                           \
8028   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8029     {                                                           \
8030       sym += strlen (#op);                                      \
8031       if (*sym == ':')                                          \
8032         ++sym;                                                  \
8033       *symp = sym;                                              \
8034       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8035                         isymbuf, locsymcount, signed_p))        \
8036         return FALSE;                                           \
8037       ++*symp;                                                  \
8038       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8039                         isymbuf, locsymcount, signed_p))        \
8040         return FALSE;                                           \
8041       if (signed_p)                                             \
8042         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8043       else                                                      \
8044         *result = a op b;                                       \
8045       return TRUE;                                              \
8046     }
8047
8048     default:
8049       UNARY_OP  (0-);
8050       BINARY_OP (<<);
8051       BINARY_OP (>>);
8052       BINARY_OP (==);
8053       BINARY_OP (!=);
8054       BINARY_OP (<=);
8055       BINARY_OP (>=);
8056       BINARY_OP (&&);
8057       BINARY_OP (||);
8058       UNARY_OP  (~);
8059       UNARY_OP  (!);
8060       BINARY_OP (*);
8061       BINARY_OP (/);
8062       BINARY_OP (%);
8063       BINARY_OP (^);
8064       BINARY_OP (|);
8065       BINARY_OP (&);
8066       BINARY_OP (+);
8067       BINARY_OP (-);
8068       BINARY_OP (<);
8069       BINARY_OP (>);
8070 #undef UNARY_OP
8071 #undef BINARY_OP
8072       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8073       bfd_set_error (bfd_error_invalid_operation);
8074       return FALSE;
8075     }
8076 }
8077
8078 static void
8079 put_value (bfd_vma size,
8080            unsigned long chunksz,
8081            bfd *input_bfd,
8082            bfd_vma x,
8083            bfd_byte *location)
8084 {
8085   location += (size - chunksz);
8086
8087   for (; size; size -= chunksz, location -= chunksz)
8088     {
8089       switch (chunksz)
8090         {
8091         case 1:
8092           bfd_put_8 (input_bfd, x, location);
8093           x >>= 8;
8094           break;
8095         case 2:
8096           bfd_put_16 (input_bfd, x, location);
8097           x >>= 16;
8098           break;
8099         case 4:
8100           bfd_put_32 (input_bfd, x, location);
8101           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8102           x >>= 16;
8103           x >>= 16;
8104           break;
8105 #ifdef BFD64
8106         case 8:
8107           bfd_put_64 (input_bfd, x, location);
8108           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8109           x >>= 32;
8110           x >>= 32;
8111           break;
8112 #endif
8113         default:
8114           abort ();
8115           break;
8116         }
8117     }
8118 }
8119
8120 static bfd_vma
8121 get_value (bfd_vma size,
8122            unsigned long chunksz,
8123            bfd *input_bfd,
8124            bfd_byte *location)
8125 {
8126   int shift;
8127   bfd_vma x = 0;
8128
8129   /* Sanity checks.  */
8130   BFD_ASSERT (chunksz <= sizeof (x)
8131               && size >= chunksz
8132               && chunksz != 0
8133               && (size % chunksz) == 0
8134               && input_bfd != NULL
8135               && location != NULL);
8136
8137   if (chunksz == sizeof (x))
8138     {
8139       BFD_ASSERT (size == chunksz);
8140
8141       /* Make sure that we do not perform an undefined shift operation.
8142          We know that size == chunksz so there will only be one iteration
8143          of the loop below.  */
8144       shift = 0;
8145     }
8146   else
8147     shift = 8 * chunksz;
8148
8149   for (; size; size -= chunksz, location += chunksz)
8150     {
8151       switch (chunksz)
8152         {
8153         case 1:
8154           x = (x << shift) | bfd_get_8 (input_bfd, location);
8155           break;
8156         case 2:
8157           x = (x << shift) | bfd_get_16 (input_bfd, location);
8158           break;
8159         case 4:
8160           x = (x << shift) | bfd_get_32 (input_bfd, location);
8161           break;
8162 #ifdef BFD64
8163         case 8:
8164           x = (x << shift) | bfd_get_64 (input_bfd, location);
8165           break;
8166 #endif
8167         default:
8168           abort ();
8169         }
8170     }
8171   return x;
8172 }
8173
8174 static void
8175 decode_complex_addend (unsigned long *start,   /* in bits */
8176                        unsigned long *oplen,   /* in bits */
8177                        unsigned long *len,     /* in bits */
8178                        unsigned long *wordsz,  /* in bytes */
8179                        unsigned long *chunksz, /* in bytes */
8180                        unsigned long *lsb0_p,
8181                        unsigned long *signed_p,
8182                        unsigned long *trunc_p,
8183                        unsigned long encoded)
8184 {
8185   * start     =  encoded        & 0x3F;
8186   * len       = (encoded >>  6) & 0x3F;
8187   * oplen     = (encoded >> 12) & 0x3F;
8188   * wordsz    = (encoded >> 18) & 0xF;
8189   * chunksz   = (encoded >> 22) & 0xF;
8190   * lsb0_p    = (encoded >> 27) & 1;
8191   * signed_p  = (encoded >> 28) & 1;
8192   * trunc_p   = (encoded >> 29) & 1;
8193 }
8194
8195 bfd_reloc_status_type
8196 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8197                                     asection *input_section ATTRIBUTE_UNUSED,
8198                                     bfd_byte *contents,
8199                                     Elf_Internal_Rela *rel,
8200                                     bfd_vma relocation)
8201 {
8202   bfd_vma shift, x, mask;
8203   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8204   bfd_reloc_status_type r;
8205
8206   /*  Perform this reloc, since it is complex.
8207       (this is not to say that it necessarily refers to a complex
8208       symbol; merely that it is a self-describing CGEN based reloc.
8209       i.e. the addend has the complete reloc information (bit start, end,
8210       word size, etc) encoded within it.).  */
8211
8212   decode_complex_addend (&start, &oplen, &len, &wordsz,
8213                          &chunksz, &lsb0_p, &signed_p,
8214                          &trunc_p, rel->r_addend);
8215
8216   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8217
8218   if (lsb0_p)
8219     shift = (start + 1) - len;
8220   else
8221     shift = (8 * wordsz) - (start + len);
8222
8223   x = get_value (wordsz, chunksz, input_bfd,
8224                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8225
8226 #ifdef DEBUG
8227   printf ("Doing complex reloc: "
8228           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8229           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8230           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8231           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8232           oplen, (unsigned long) x, (unsigned long) mask,
8233           (unsigned long) relocation);
8234 #endif
8235
8236   r = bfd_reloc_ok;
8237   if (! trunc_p)
8238     /* Now do an overflow check.  */
8239     r = bfd_check_overflow ((signed_p
8240                              ? complain_overflow_signed
8241                              : complain_overflow_unsigned),
8242                             len, 0, (8 * wordsz),
8243                             relocation);
8244
8245   /* Do the deed.  */
8246   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8247
8248 #ifdef DEBUG
8249   printf ("           relocation: %8.8lx\n"
8250           "         shifted mask: %8.8lx\n"
8251           " shifted/masked reloc: %8.8lx\n"
8252           "               result: %8.8lx\n",
8253           (unsigned long) relocation, (unsigned long) (mask << shift),
8254           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8255 #endif
8256   put_value (wordsz, chunksz, input_bfd, x,
8257              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8258   return r;
8259 }
8260
8261 /* Functions to read r_offset from external (target order) reloc
8262    entry.  Faster than bfd_getl32 et al, because we let the compiler
8263    know the value is aligned.  */
8264
8265 static bfd_vma
8266 ext32l_r_offset (const void *p)
8267 {
8268   union aligned32
8269   {
8270     uint32_t v;
8271     unsigned char c[4];
8272   };
8273   const union aligned32 *a
8274     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8275
8276   uint32_t aval = (  (uint32_t) a->c[0]
8277                    | (uint32_t) a->c[1] << 8
8278                    | (uint32_t) a->c[2] << 16
8279                    | (uint32_t) a->c[3] << 24);
8280   return aval;
8281 }
8282
8283 static bfd_vma
8284 ext32b_r_offset (const void *p)
8285 {
8286   union aligned32
8287   {
8288     uint32_t v;
8289     unsigned char c[4];
8290   };
8291   const union aligned32 *a
8292     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8293
8294   uint32_t aval = (  (uint32_t) a->c[0] << 24
8295                    | (uint32_t) a->c[1] << 16
8296                    | (uint32_t) a->c[2] << 8
8297                    | (uint32_t) a->c[3]);
8298   return aval;
8299 }
8300
8301 #ifdef BFD_HOST_64_BIT
8302 static bfd_vma
8303 ext64l_r_offset (const void *p)
8304 {
8305   union aligned64
8306   {
8307     uint64_t v;
8308     unsigned char c[8];
8309   };
8310   const union aligned64 *a
8311     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8312
8313   uint64_t aval = (  (uint64_t) a->c[0]
8314                    | (uint64_t) a->c[1] << 8
8315                    | (uint64_t) a->c[2] << 16
8316                    | (uint64_t) a->c[3] << 24
8317                    | (uint64_t) a->c[4] << 32
8318                    | (uint64_t) a->c[5] << 40
8319                    | (uint64_t) a->c[6] << 48
8320                    | (uint64_t) a->c[7] << 56);
8321   return aval;
8322 }
8323
8324 static bfd_vma
8325 ext64b_r_offset (const void *p)
8326 {
8327   union aligned64
8328   {
8329     uint64_t v;
8330     unsigned char c[8];
8331   };
8332   const union aligned64 *a
8333     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8334
8335   uint64_t aval = (  (uint64_t) a->c[0] << 56
8336                    | (uint64_t) a->c[1] << 48
8337                    | (uint64_t) a->c[2] << 40
8338                    | (uint64_t) a->c[3] << 32
8339                    | (uint64_t) a->c[4] << 24
8340                    | (uint64_t) a->c[5] << 16
8341                    | (uint64_t) a->c[6] << 8
8342                    | (uint64_t) a->c[7]);
8343   return aval;
8344 }
8345 #endif
8346
8347 /* When performing a relocatable link, the input relocations are
8348    preserved.  But, if they reference global symbols, the indices
8349    referenced must be updated.  Update all the relocations found in
8350    RELDATA.  */
8351
8352 static bfd_boolean
8353 elf_link_adjust_relocs (bfd *abfd,
8354                         asection *sec,
8355                         struct bfd_elf_section_reloc_data *reldata,
8356                         bfd_boolean sort)
8357 {
8358   unsigned int i;
8359   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8360   bfd_byte *erela;
8361   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8362   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8363   bfd_vma r_type_mask;
8364   int r_sym_shift;
8365   unsigned int count = reldata->count;
8366   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8367
8368   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8369     {
8370       swap_in = bed->s->swap_reloc_in;
8371       swap_out = bed->s->swap_reloc_out;
8372     }
8373   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8374     {
8375       swap_in = bed->s->swap_reloca_in;
8376       swap_out = bed->s->swap_reloca_out;
8377     }
8378   else
8379     abort ();
8380
8381   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8382     abort ();
8383
8384   if (bed->s->arch_size == 32)
8385     {
8386       r_type_mask = 0xff;
8387       r_sym_shift = 8;
8388     }
8389   else
8390     {
8391       r_type_mask = 0xffffffff;
8392       r_sym_shift = 32;
8393     }
8394
8395   erela = reldata->hdr->contents;
8396   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8397     {
8398       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8399       unsigned int j;
8400
8401       if (*rel_hash == NULL)
8402         continue;
8403
8404       BFD_ASSERT ((*rel_hash)->indx >= 0);
8405
8406       (*swap_in) (abfd, erela, irela);
8407       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8408         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8409                            | (irela[j].r_info & r_type_mask));
8410       (*swap_out) (abfd, irela, erela);
8411     }
8412
8413   if (bed->elf_backend_update_relocs)
8414     (*bed->elf_backend_update_relocs) (sec, reldata);
8415
8416   if (sort && count != 0)
8417     {
8418       bfd_vma (*ext_r_off) (const void *);
8419       bfd_vma r_off;
8420       size_t elt_size;
8421       bfd_byte *base, *end, *p, *loc;
8422       bfd_byte *buf = NULL;
8423
8424       if (bed->s->arch_size == 32)
8425         {
8426           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8427             ext_r_off = ext32l_r_offset;
8428           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8429             ext_r_off = ext32b_r_offset;
8430           else
8431             abort ();
8432         }
8433       else
8434         {
8435 #ifdef BFD_HOST_64_BIT
8436           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8437             ext_r_off = ext64l_r_offset;
8438           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8439             ext_r_off = ext64b_r_offset;
8440           else
8441 #endif
8442             abort ();
8443         }
8444
8445       /*  Must use a stable sort here.  A modified insertion sort,
8446           since the relocs are mostly sorted already.  */
8447       elt_size = reldata->hdr->sh_entsize;
8448       base = reldata->hdr->contents;
8449       end = base + count * elt_size;
8450       if (elt_size > sizeof (Elf64_External_Rela))
8451         abort ();
8452
8453       /* Ensure the first element is lowest.  This acts as a sentinel,
8454          speeding the main loop below.  */
8455       r_off = (*ext_r_off) (base);
8456       for (p = loc = base; (p += elt_size) < end; )
8457         {
8458           bfd_vma r_off2 = (*ext_r_off) (p);
8459           if (r_off > r_off2)
8460             {
8461               r_off = r_off2;
8462               loc = p;
8463             }
8464         }
8465       if (loc != base)
8466         {
8467           /* Don't just swap *base and *loc as that changes the order
8468              of the original base[0] and base[1] if they happen to
8469              have the same r_offset.  */
8470           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8471           memcpy (onebuf, loc, elt_size);
8472           memmove (base + elt_size, base, loc - base);
8473           memcpy (base, onebuf, elt_size);
8474         }
8475
8476       for (p = base + elt_size; (p += elt_size) < end; )
8477         {
8478           /* base to p is sorted, *p is next to insert.  */
8479           r_off = (*ext_r_off) (p);
8480           /* Search the sorted region for location to insert.  */
8481           loc = p - elt_size;
8482           while (r_off < (*ext_r_off) (loc))
8483             loc -= elt_size;
8484           loc += elt_size;
8485           if (loc != p)
8486             {
8487               /* Chances are there is a run of relocs to insert here,
8488                  from one of more input files.  Files are not always
8489                  linked in order due to the way elf_link_input_bfd is
8490                  called.  See pr17666.  */
8491               size_t sortlen = p - loc;
8492               bfd_vma r_off2 = (*ext_r_off) (loc);
8493               size_t runlen = elt_size;
8494               size_t buf_size = 96 * 1024;
8495               while (p + runlen < end
8496                      && (sortlen <= buf_size
8497                          || runlen + elt_size <= buf_size)
8498                      && r_off2 > (*ext_r_off) (p + runlen))
8499                 runlen += elt_size;
8500               if (buf == NULL)
8501                 {
8502                   buf = bfd_malloc (buf_size);
8503                   if (buf == NULL)
8504                     return FALSE;
8505                 }
8506               if (runlen < sortlen)
8507                 {
8508                   memcpy (buf, p, runlen);
8509                   memmove (loc + runlen, loc, sortlen);
8510                   memcpy (loc, buf, runlen);
8511                 }
8512               else
8513                 {
8514                   memcpy (buf, loc, sortlen);
8515                   memmove (loc, p, runlen);
8516                   memcpy (loc + runlen, buf, sortlen);
8517                 }
8518               p += runlen - elt_size;
8519             }
8520         }
8521       /* Hashes are no longer valid.  */
8522       free (reldata->hashes);
8523       reldata->hashes = NULL;
8524       free (buf);
8525     }
8526   return TRUE;
8527 }
8528
8529 struct elf_link_sort_rela
8530 {
8531   union {
8532     bfd_vma offset;
8533     bfd_vma sym_mask;
8534   } u;
8535   enum elf_reloc_type_class type;
8536   /* We use this as an array of size int_rels_per_ext_rel.  */
8537   Elf_Internal_Rela rela[1];
8538 };
8539
8540 static int
8541 elf_link_sort_cmp1 (const void *A, const void *B)
8542 {
8543   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8544   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8545   int relativea, relativeb;
8546
8547   relativea = a->type == reloc_class_relative;
8548   relativeb = b->type == reloc_class_relative;
8549
8550   if (relativea < relativeb)
8551     return 1;
8552   if (relativea > relativeb)
8553     return -1;
8554   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8555     return -1;
8556   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8557     return 1;
8558   if (a->rela->r_offset < b->rela->r_offset)
8559     return -1;
8560   if (a->rela->r_offset > b->rela->r_offset)
8561     return 1;
8562   return 0;
8563 }
8564
8565 static int
8566 elf_link_sort_cmp2 (const void *A, const void *B)
8567 {
8568   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8569   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8570
8571   if (a->type < b->type)
8572     return -1;
8573   if (a->type > b->type)
8574     return 1;
8575   if (a->u.offset < b->u.offset)
8576     return -1;
8577   if (a->u.offset > b->u.offset)
8578     return 1;
8579   if (a->rela->r_offset < b->rela->r_offset)
8580     return -1;
8581   if (a->rela->r_offset > b->rela->r_offset)
8582     return 1;
8583   return 0;
8584 }
8585
8586 static size_t
8587 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8588 {
8589   asection *dynamic_relocs;
8590   asection *rela_dyn;
8591   asection *rel_dyn;
8592   bfd_size_type count, size;
8593   size_t i, ret, sort_elt, ext_size;
8594   bfd_byte *sort, *s_non_relative, *p;
8595   struct elf_link_sort_rela *sq;
8596   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8597   int i2e = bed->s->int_rels_per_ext_rel;
8598   unsigned int opb = bfd_octets_per_byte (abfd);
8599   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8600   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8601   struct bfd_link_order *lo;
8602   bfd_vma r_sym_mask;
8603   bfd_boolean use_rela;
8604
8605   /* Find a dynamic reloc section.  */
8606   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8607   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8608   if (rela_dyn != NULL && rela_dyn->size > 0
8609       && rel_dyn != NULL && rel_dyn->size > 0)
8610     {
8611       bfd_boolean use_rela_initialised = FALSE;
8612
8613       /* This is just here to stop gcc from complaining.
8614          Its initialization checking code is not perfect.  */
8615       use_rela = TRUE;
8616
8617       /* Both sections are present.  Examine the sizes
8618          of the indirect sections to help us choose.  */
8619       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8620         if (lo->type == bfd_indirect_link_order)
8621           {
8622             asection *o = lo->u.indirect.section;
8623
8624             if ((o->size % bed->s->sizeof_rela) == 0)
8625               {
8626                 if ((o->size % bed->s->sizeof_rel) == 0)
8627                   /* Section size is divisible by both rel and rela sizes.
8628                      It is of no help to us.  */
8629                   ;
8630                 else
8631                   {
8632                     /* Section size is only divisible by rela.  */
8633                     if (use_rela_initialised && (use_rela == FALSE))
8634                       {
8635                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8636                                               "they are in more than one size"),
8637                                             abfd);
8638                         bfd_set_error (bfd_error_invalid_operation);
8639                         return 0;
8640                       }
8641                     else
8642                       {
8643                         use_rela = TRUE;
8644                         use_rela_initialised = TRUE;
8645                       }
8646                   }
8647               }
8648             else if ((o->size % bed->s->sizeof_rel) == 0)
8649               {
8650                 /* Section size is only divisible by rel.  */
8651                 if (use_rela_initialised && (use_rela == TRUE))
8652                   {
8653                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8654                                           "they are in more than one size"),
8655                                         abfd);
8656                     bfd_set_error (bfd_error_invalid_operation);
8657                     return 0;
8658                   }
8659                 else
8660                   {
8661                     use_rela = FALSE;
8662                     use_rela_initialised = TRUE;
8663                   }
8664               }
8665             else
8666               {
8667                 /* The section size is not divisible by either -
8668                    something is wrong.  */
8669                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8670                                       "they are of an unknown size"), abfd);
8671                 bfd_set_error (bfd_error_invalid_operation);
8672                 return 0;
8673               }
8674           }
8675
8676       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8677         if (lo->type == bfd_indirect_link_order)
8678           {
8679             asection *o = lo->u.indirect.section;
8680
8681             if ((o->size % bed->s->sizeof_rela) == 0)
8682               {
8683                 if ((o->size % bed->s->sizeof_rel) == 0)
8684                   /* Section size is divisible by both rel and rela sizes.
8685                      It is of no help to us.  */
8686                   ;
8687                 else
8688                   {
8689                     /* Section size is only divisible by rela.  */
8690                     if (use_rela_initialised && (use_rela == FALSE))
8691                       {
8692                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8693                                               "they are in more than one size"),
8694                                             abfd);
8695                         bfd_set_error (bfd_error_invalid_operation);
8696                         return 0;
8697                       }
8698                     else
8699                       {
8700                         use_rela = TRUE;
8701                         use_rela_initialised = TRUE;
8702                       }
8703                   }
8704               }
8705             else if ((o->size % bed->s->sizeof_rel) == 0)
8706               {
8707                 /* Section size is only divisible by rel.  */
8708                 if (use_rela_initialised && (use_rela == TRUE))
8709                   {
8710                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8711                                           "they are in more than one size"),
8712                                         abfd);
8713                     bfd_set_error (bfd_error_invalid_operation);
8714                     return 0;
8715                   }
8716                 else
8717                   {
8718                     use_rela = FALSE;
8719                     use_rela_initialised = TRUE;
8720                   }
8721               }
8722             else
8723               {
8724                 /* The section size is not divisible by either -
8725                    something is wrong.  */
8726                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8727                                       "they are of an unknown size"), abfd);
8728                 bfd_set_error (bfd_error_invalid_operation);
8729                 return 0;
8730               }
8731           }
8732
8733       if (! use_rela_initialised)
8734         /* Make a guess.  */
8735         use_rela = TRUE;
8736     }
8737   else if (rela_dyn != NULL && rela_dyn->size > 0)
8738     use_rela = TRUE;
8739   else if (rel_dyn != NULL && rel_dyn->size > 0)
8740     use_rela = FALSE;
8741   else
8742     return 0;
8743
8744   if (use_rela)
8745     {
8746       dynamic_relocs = rela_dyn;
8747       ext_size = bed->s->sizeof_rela;
8748       swap_in = bed->s->swap_reloca_in;
8749       swap_out = bed->s->swap_reloca_out;
8750     }
8751   else
8752     {
8753       dynamic_relocs = rel_dyn;
8754       ext_size = bed->s->sizeof_rel;
8755       swap_in = bed->s->swap_reloc_in;
8756       swap_out = bed->s->swap_reloc_out;
8757     }
8758
8759   size = 0;
8760   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8761     if (lo->type == bfd_indirect_link_order)
8762       size += lo->u.indirect.section->size;
8763
8764   if (size != dynamic_relocs->size)
8765     return 0;
8766
8767   sort_elt = (sizeof (struct elf_link_sort_rela)
8768               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8769
8770   count = dynamic_relocs->size / ext_size;
8771   if (count == 0)
8772     return 0;
8773   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8774
8775   if (sort == NULL)
8776     {
8777       (*info->callbacks->warning)
8778         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8779       return 0;
8780     }
8781
8782   if (bed->s->arch_size == 32)
8783     r_sym_mask = ~(bfd_vma) 0xff;
8784   else
8785     r_sym_mask = ~(bfd_vma) 0xffffffff;
8786
8787   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8788     if (lo->type == bfd_indirect_link_order)
8789       {
8790         bfd_byte *erel, *erelend;
8791         asection *o = lo->u.indirect.section;
8792
8793         if (o->contents == NULL && o->size != 0)
8794           {
8795             /* This is a reloc section that is being handled as a normal
8796                section.  See bfd_section_from_shdr.  We can't combine
8797                relocs in this case.  */
8798             free (sort);
8799             return 0;
8800           }
8801         erel = o->contents;
8802         erelend = o->contents + o->size;
8803         p = sort + o->output_offset * opb / ext_size * sort_elt;
8804
8805         while (erel < erelend)
8806           {
8807             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8808
8809             (*swap_in) (abfd, erel, s->rela);
8810             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8811             s->u.sym_mask = r_sym_mask;
8812             p += sort_elt;
8813             erel += ext_size;
8814           }
8815       }
8816
8817   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8818
8819   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8820     {
8821       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8822       if (s->type != reloc_class_relative)
8823         break;
8824     }
8825   ret = i;
8826   s_non_relative = p;
8827
8828   sq = (struct elf_link_sort_rela *) s_non_relative;
8829   for (; i < count; i++, p += sort_elt)
8830     {
8831       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8832       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8833         sq = sp;
8834       sp->u.offset = sq->rela->r_offset;
8835     }
8836
8837   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8838
8839   struct elf_link_hash_table *htab = elf_hash_table (info);
8840   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
8841     {
8842       /* We have plt relocs in .rela.dyn.  */
8843       sq = (struct elf_link_sort_rela *) sort;
8844       for (i = 0; i < count; i++)
8845         if (sq[count - i - 1].type != reloc_class_plt)
8846           break;
8847       if (i != 0 && htab->srelplt->size == i * ext_size)
8848         {
8849           struct bfd_link_order **plo;
8850           /* Put srelplt link_order last.  This is so the output_offset
8851              set in the next loop is correct for DT_JMPREL.  */
8852           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
8853             if ((*plo)->type == bfd_indirect_link_order
8854                 && (*plo)->u.indirect.section == htab->srelplt)
8855               {
8856                 lo = *plo;
8857                 *plo = lo->next;
8858               }
8859             else
8860               plo = &(*plo)->next;
8861           *plo = lo;
8862           lo->next = NULL;
8863           dynamic_relocs->map_tail.link_order = lo;
8864         }
8865     }
8866
8867   p = sort;
8868   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8869     if (lo->type == bfd_indirect_link_order)
8870       {
8871         bfd_byte *erel, *erelend;
8872         asection *o = lo->u.indirect.section;
8873
8874         erel = o->contents;
8875         erelend = o->contents + o->size;
8876         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
8877         while (erel < erelend)
8878           {
8879             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8880             (*swap_out) (abfd, s->rela, erel);
8881             p += sort_elt;
8882             erel += ext_size;
8883           }
8884       }
8885
8886   free (sort);
8887   *psec = dynamic_relocs;
8888   return ret;
8889 }
8890
8891 /* Add a symbol to the output symbol string table.  */
8892
8893 static int
8894 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8895                            const char *name,
8896                            Elf_Internal_Sym *elfsym,
8897                            asection *input_sec,
8898                            struct elf_link_hash_entry *h)
8899 {
8900   int (*output_symbol_hook)
8901     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8902      struct elf_link_hash_entry *);
8903   struct elf_link_hash_table *hash_table;
8904   const struct elf_backend_data *bed;
8905   bfd_size_type strtabsize;
8906
8907   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8908
8909   bed = get_elf_backend_data (flinfo->output_bfd);
8910   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8911   if (output_symbol_hook != NULL)
8912     {
8913       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8914       if (ret != 1)
8915         return ret;
8916     }
8917
8918   if (name == NULL
8919       || *name == '\0'
8920       || (input_sec->flags & SEC_EXCLUDE))
8921     elfsym->st_name = (unsigned long) -1;
8922   else
8923     {
8924       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8925          to get the final offset for st_name.  */
8926       elfsym->st_name
8927         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8928                                                name, FALSE);
8929       if (elfsym->st_name == (unsigned long) -1)
8930         return 0;
8931     }
8932
8933   hash_table = elf_hash_table (flinfo->info);
8934   strtabsize = hash_table->strtabsize;
8935   if (strtabsize <= hash_table->strtabcount)
8936     {
8937       strtabsize += strtabsize;
8938       hash_table->strtabsize = strtabsize;
8939       strtabsize *= sizeof (*hash_table->strtab);
8940       hash_table->strtab
8941         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8942                                                  strtabsize);
8943       if (hash_table->strtab == NULL)
8944         return 0;
8945     }
8946   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8947   hash_table->strtab[hash_table->strtabcount].dest_index
8948     = hash_table->strtabcount;
8949   hash_table->strtab[hash_table->strtabcount].destshndx_index
8950     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8951
8952   bfd_get_symcount (flinfo->output_bfd) += 1;
8953   hash_table->strtabcount += 1;
8954
8955   return 1;
8956 }
8957
8958 /* Swap symbols out to the symbol table and flush the output symbols to
8959    the file.  */
8960
8961 static bfd_boolean
8962 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8963 {
8964   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8965   bfd_size_type amt;
8966   size_t i;
8967   const struct elf_backend_data *bed;
8968   bfd_byte *symbuf;
8969   Elf_Internal_Shdr *hdr;
8970   file_ptr pos;
8971   bfd_boolean ret;
8972
8973   if (!hash_table->strtabcount)
8974     return TRUE;
8975
8976   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8977
8978   bed = get_elf_backend_data (flinfo->output_bfd);
8979
8980   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8981   symbuf = (bfd_byte *) bfd_malloc (amt);
8982   if (symbuf == NULL)
8983     return FALSE;
8984
8985   if (flinfo->symshndxbuf)
8986     {
8987       amt = sizeof (Elf_External_Sym_Shndx);
8988       amt *= bfd_get_symcount (flinfo->output_bfd);
8989       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8990       if (flinfo->symshndxbuf == NULL)
8991         {
8992           free (symbuf);
8993           return FALSE;
8994         }
8995     }
8996
8997   for (i = 0; i < hash_table->strtabcount; i++)
8998     {
8999       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9000       if (elfsym->sym.st_name == (unsigned long) -1)
9001         elfsym->sym.st_name = 0;
9002       else
9003         elfsym->sym.st_name
9004           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9005                                                     elfsym->sym.st_name);
9006       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9007                                ((bfd_byte *) symbuf
9008                                 + (elfsym->dest_index
9009                                    * bed->s->sizeof_sym)),
9010                                (flinfo->symshndxbuf
9011                                 + elfsym->destshndx_index));
9012     }
9013
9014   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9015   pos = hdr->sh_offset + hdr->sh_size;
9016   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9017   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9018       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9019     {
9020       hdr->sh_size += amt;
9021       ret = TRUE;
9022     }
9023   else
9024     ret = FALSE;
9025
9026   free (symbuf);
9027
9028   free (hash_table->strtab);
9029   hash_table->strtab = NULL;
9030
9031   return ret;
9032 }
9033
9034 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9035
9036 static bfd_boolean
9037 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9038 {
9039   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9040       && sym->st_shndx < SHN_LORESERVE)
9041     {
9042       /* The gABI doesn't support dynamic symbols in output sections
9043          beyond 64k.  */
9044       _bfd_error_handler
9045         /* xgettext:c-format */
9046         (_("%B: Too many sections: %d (>= %d)"),
9047          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9048       bfd_set_error (bfd_error_nonrepresentable_section);
9049       return FALSE;
9050     }
9051   return TRUE;
9052 }
9053
9054 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9055    allowing an unsatisfied unversioned symbol in the DSO to match a
9056    versioned symbol that would normally require an explicit version.
9057    We also handle the case that a DSO references a hidden symbol
9058    which may be satisfied by a versioned symbol in another DSO.  */
9059
9060 static bfd_boolean
9061 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9062                                  const struct elf_backend_data *bed,
9063                                  struct elf_link_hash_entry *h)
9064 {
9065   bfd *abfd;
9066   struct elf_link_loaded_list *loaded;
9067
9068   if (!is_elf_hash_table (info->hash))
9069     return FALSE;
9070
9071   /* Check indirect symbol.  */
9072   while (h->root.type == bfd_link_hash_indirect)
9073     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9074
9075   switch (h->root.type)
9076     {
9077     default:
9078       abfd = NULL;
9079       break;
9080
9081     case bfd_link_hash_undefined:
9082     case bfd_link_hash_undefweak:
9083       abfd = h->root.u.undef.abfd;
9084       if (abfd == NULL
9085           || (abfd->flags & DYNAMIC) == 0
9086           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9087         return FALSE;
9088       break;
9089
9090     case bfd_link_hash_defined:
9091     case bfd_link_hash_defweak:
9092       abfd = h->root.u.def.section->owner;
9093       break;
9094
9095     case bfd_link_hash_common:
9096       abfd = h->root.u.c.p->section->owner;
9097       break;
9098     }
9099   BFD_ASSERT (abfd != NULL);
9100
9101   for (loaded = elf_hash_table (info)->loaded;
9102        loaded != NULL;
9103        loaded = loaded->next)
9104     {
9105       bfd *input;
9106       Elf_Internal_Shdr *hdr;
9107       size_t symcount;
9108       size_t extsymcount;
9109       size_t extsymoff;
9110       Elf_Internal_Shdr *versymhdr;
9111       Elf_Internal_Sym *isym;
9112       Elf_Internal_Sym *isymend;
9113       Elf_Internal_Sym *isymbuf;
9114       Elf_External_Versym *ever;
9115       Elf_External_Versym *extversym;
9116
9117       input = loaded->abfd;
9118
9119       /* We check each DSO for a possible hidden versioned definition.  */
9120       if (input == abfd
9121           || (input->flags & DYNAMIC) == 0
9122           || elf_dynversym (input) == 0)
9123         continue;
9124
9125       hdr = &elf_tdata (input)->dynsymtab_hdr;
9126
9127       symcount = hdr->sh_size / bed->s->sizeof_sym;
9128       if (elf_bad_symtab (input))
9129         {
9130           extsymcount = symcount;
9131           extsymoff = 0;
9132         }
9133       else
9134         {
9135           extsymcount = symcount - hdr->sh_info;
9136           extsymoff = hdr->sh_info;
9137         }
9138
9139       if (extsymcount == 0)
9140         continue;
9141
9142       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9143                                       NULL, NULL, NULL);
9144       if (isymbuf == NULL)
9145         return FALSE;
9146
9147       /* Read in any version definitions.  */
9148       versymhdr = &elf_tdata (input)->dynversym_hdr;
9149       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9150       if (extversym == NULL)
9151         goto error_ret;
9152
9153       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9154           || (bfd_bread (extversym, versymhdr->sh_size, input)
9155               != versymhdr->sh_size))
9156         {
9157           free (extversym);
9158         error_ret:
9159           free (isymbuf);
9160           return FALSE;
9161         }
9162
9163       ever = extversym + extsymoff;
9164       isymend = isymbuf + extsymcount;
9165       for (isym = isymbuf; isym < isymend; isym++, ever++)
9166         {
9167           const char *name;
9168           Elf_Internal_Versym iver;
9169           unsigned short version_index;
9170
9171           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9172               || isym->st_shndx == SHN_UNDEF)
9173             continue;
9174
9175           name = bfd_elf_string_from_elf_section (input,
9176                                                   hdr->sh_link,
9177                                                   isym->st_name);
9178           if (strcmp (name, h->root.root.string) != 0)
9179             continue;
9180
9181           _bfd_elf_swap_versym_in (input, ever, &iver);
9182
9183           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9184               && !(h->def_regular
9185                    && h->forced_local))
9186             {
9187               /* If we have a non-hidden versioned sym, then it should
9188                  have provided a definition for the undefined sym unless
9189                  it is defined in a non-shared object and forced local.
9190                */
9191               abort ();
9192             }
9193
9194           version_index = iver.vs_vers & VERSYM_VERSION;
9195           if (version_index == 1 || version_index == 2)
9196             {
9197               /* This is the base or first version.  We can use it.  */
9198               free (extversym);
9199               free (isymbuf);
9200               return TRUE;
9201             }
9202         }
9203
9204       free (extversym);
9205       free (isymbuf);
9206     }
9207
9208   return FALSE;
9209 }
9210
9211 /* Convert ELF common symbol TYPE.  */
9212
9213 static int
9214 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9215 {
9216   /* Commom symbol can only appear in relocatable link.  */
9217   if (!bfd_link_relocatable (info))
9218     abort ();
9219   switch (info->elf_stt_common)
9220     {
9221     case unchanged:
9222       break;
9223     case elf_stt_common:
9224       type = STT_COMMON;
9225       break;
9226     case no_elf_stt_common:
9227       type = STT_OBJECT;
9228       break;
9229     }
9230   return type;
9231 }
9232
9233 /* Add an external symbol to the symbol table.  This is called from
9234    the hash table traversal routine.  When generating a shared object,
9235    we go through the symbol table twice.  The first time we output
9236    anything that might have been forced to local scope in a version
9237    script.  The second time we output the symbols that are still
9238    global symbols.  */
9239
9240 static bfd_boolean
9241 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9242 {
9243   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9244   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9245   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9246   bfd_boolean strip;
9247   Elf_Internal_Sym sym;
9248   asection *input_sec;
9249   const struct elf_backend_data *bed;
9250   long indx;
9251   int ret;
9252   unsigned int type;
9253   /* A symbol is bound locally if it is forced local or it is locally
9254      defined, hidden versioned, not referenced by shared library and
9255      not exported when linking executable.  */
9256   bfd_boolean local_bind = (h->forced_local
9257                             || (bfd_link_executable (flinfo->info)
9258                                 && !flinfo->info->export_dynamic
9259                                 && !h->dynamic
9260                                 && !h->ref_dynamic
9261                                 && h->def_regular
9262                                 && h->versioned == versioned_hidden));
9263
9264   if (h->root.type == bfd_link_hash_warning)
9265     {
9266       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9267       if (h->root.type == bfd_link_hash_new)
9268         return TRUE;
9269     }
9270
9271   /* Decide whether to output this symbol in this pass.  */
9272   if (eoinfo->localsyms)
9273     {
9274       if (!local_bind)
9275         return TRUE;
9276     }
9277   else
9278     {
9279       if (local_bind)
9280         return TRUE;
9281     }
9282
9283   bed = get_elf_backend_data (flinfo->output_bfd);
9284
9285   if (h->root.type == bfd_link_hash_undefined)
9286     {
9287       /* If we have an undefined symbol reference here then it must have
9288          come from a shared library that is being linked in.  (Undefined
9289          references in regular files have already been handled unless
9290          they are in unreferenced sections which are removed by garbage
9291          collection).  */
9292       bfd_boolean ignore_undef = FALSE;
9293
9294       /* Some symbols may be special in that the fact that they're
9295          undefined can be safely ignored - let backend determine that.  */
9296       if (bed->elf_backend_ignore_undef_symbol)
9297         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9298
9299       /* If we are reporting errors for this situation then do so now.  */
9300       if (!ignore_undef
9301           && h->ref_dynamic
9302           && (!h->ref_regular || flinfo->info->gc_sections)
9303           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9304           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9305         (*flinfo->info->callbacks->undefined_symbol)
9306           (flinfo->info, h->root.root.string,
9307            h->ref_regular ? NULL : h->root.u.undef.abfd,
9308            NULL, 0,
9309            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9310
9311       /* Strip a global symbol defined in a discarded section.  */
9312       if (h->indx == -3)
9313         return TRUE;
9314     }
9315
9316   /* We should also warn if a forced local symbol is referenced from
9317      shared libraries.  */
9318   if (bfd_link_executable (flinfo->info)
9319       && h->forced_local
9320       && h->ref_dynamic
9321       && h->def_regular
9322       && !h->dynamic_def
9323       && h->ref_dynamic_nonweak
9324       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9325     {
9326       bfd *def_bfd;
9327       const char *msg;
9328       struct elf_link_hash_entry *hi = h;
9329
9330       /* Check indirect symbol.  */
9331       while (hi->root.type == bfd_link_hash_indirect)
9332         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9333
9334       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9335         /* xgettext:c-format */
9336         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9337       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9338         /* xgettext:c-format */
9339         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9340       else
9341         /* xgettext:c-format */
9342         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9343       def_bfd = flinfo->output_bfd;
9344       if (hi->root.u.def.section != bfd_abs_section_ptr)
9345         def_bfd = hi->root.u.def.section->owner;
9346       _bfd_error_handler (msg, flinfo->output_bfd, def_bfd,
9347                           h->root.root.string);
9348       bfd_set_error (bfd_error_bad_value);
9349       eoinfo->failed = TRUE;
9350       return FALSE;
9351     }
9352
9353   /* We don't want to output symbols that have never been mentioned by
9354      a regular file, or that we have been told to strip.  However, if
9355      h->indx is set to -2, the symbol is used by a reloc and we must
9356      output it.  */
9357   strip = FALSE;
9358   if (h->indx == -2)
9359     ;
9360   else if ((h->def_dynamic
9361             || h->ref_dynamic
9362             || h->root.type == bfd_link_hash_new)
9363            && !h->def_regular
9364            && !h->ref_regular)
9365     strip = TRUE;
9366   else if (flinfo->info->strip == strip_all)
9367     strip = TRUE;
9368   else if (flinfo->info->strip == strip_some
9369            && bfd_hash_lookup (flinfo->info->keep_hash,
9370                                h->root.root.string, FALSE, FALSE) == NULL)
9371     strip = TRUE;
9372   else if ((h->root.type == bfd_link_hash_defined
9373             || h->root.type == bfd_link_hash_defweak)
9374            && ((flinfo->info->strip_discarded
9375                 && discarded_section (h->root.u.def.section))
9376                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9377                    && h->root.u.def.section->owner != NULL
9378                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9379     strip = TRUE;
9380   else if ((h->root.type == bfd_link_hash_undefined
9381             || h->root.type == bfd_link_hash_undefweak)
9382            && h->root.u.undef.abfd != NULL
9383            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9384     strip = TRUE;
9385
9386   type = h->type;
9387
9388   /* If we're stripping it, and it's not a dynamic symbol, there's
9389      nothing else to do.   However, if it is a forced local symbol or
9390      an ifunc symbol we need to give the backend finish_dynamic_symbol
9391      function a chance to make it dynamic.  */
9392   if (strip
9393       && h->dynindx == -1
9394       && type != STT_GNU_IFUNC
9395       && !h->forced_local)
9396     return TRUE;
9397
9398   sym.st_value = 0;
9399   sym.st_size = h->size;
9400   sym.st_other = h->other;
9401   switch (h->root.type)
9402     {
9403     default:
9404     case bfd_link_hash_new:
9405     case bfd_link_hash_warning:
9406       abort ();
9407       return FALSE;
9408
9409     case bfd_link_hash_undefined:
9410     case bfd_link_hash_undefweak:
9411       input_sec = bfd_und_section_ptr;
9412       sym.st_shndx = SHN_UNDEF;
9413       break;
9414
9415     case bfd_link_hash_defined:
9416     case bfd_link_hash_defweak:
9417       {
9418         input_sec = h->root.u.def.section;
9419         if (input_sec->output_section != NULL)
9420           {
9421             sym.st_shndx =
9422               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9423                                                  input_sec->output_section);
9424             if (sym.st_shndx == SHN_BAD)
9425               {
9426                 _bfd_error_handler
9427                   /* xgettext:c-format */
9428                   (_("%B: could not find output section %A for input section %A"),
9429                    flinfo->output_bfd, input_sec->output_section, input_sec);
9430                 bfd_set_error (bfd_error_nonrepresentable_section);
9431                 eoinfo->failed = TRUE;
9432                 return FALSE;
9433               }
9434
9435             /* ELF symbols in relocatable files are section relative,
9436                but in nonrelocatable files they are virtual
9437                addresses.  */
9438             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9439             if (!bfd_link_relocatable (flinfo->info))
9440               {
9441                 sym.st_value += input_sec->output_section->vma;
9442                 if (h->type == STT_TLS)
9443                   {
9444                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9445                     if (tls_sec != NULL)
9446                       sym.st_value -= tls_sec->vma;
9447                   }
9448               }
9449           }
9450         else
9451           {
9452             BFD_ASSERT (input_sec->owner == NULL
9453                         || (input_sec->owner->flags & DYNAMIC) != 0);
9454             sym.st_shndx = SHN_UNDEF;
9455             input_sec = bfd_und_section_ptr;
9456           }
9457       }
9458       break;
9459
9460     case bfd_link_hash_common:
9461       input_sec = h->root.u.c.p->section;
9462       sym.st_shndx = bed->common_section_index (input_sec);
9463       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9464       break;
9465
9466     case bfd_link_hash_indirect:
9467       /* These symbols are created by symbol versioning.  They point
9468          to the decorated version of the name.  For example, if the
9469          symbol foo@@GNU_1.2 is the default, which should be used when
9470          foo is used with no version, then we add an indirect symbol
9471          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9472          since the indirected symbol is already in the hash table.  */
9473       return TRUE;
9474     }
9475
9476   if (type == STT_COMMON || type == STT_OBJECT)
9477     switch (h->root.type)
9478       {
9479       case bfd_link_hash_common:
9480         type = elf_link_convert_common_type (flinfo->info, type);
9481         break;
9482       case bfd_link_hash_defined:
9483       case bfd_link_hash_defweak:
9484         if (bed->common_definition (&sym))
9485           type = elf_link_convert_common_type (flinfo->info, type);
9486         else
9487           type = STT_OBJECT;
9488         break;
9489       case bfd_link_hash_undefined:
9490       case bfd_link_hash_undefweak:
9491         break;
9492       default:
9493         abort ();
9494       }
9495
9496   if (local_bind)
9497     {
9498       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9499       /* Turn off visibility on local symbol.  */
9500       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9501     }
9502   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9503   else if (h->unique_global && h->def_regular)
9504     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9505   else if (h->root.type == bfd_link_hash_undefweak
9506            || h->root.type == bfd_link_hash_defweak)
9507     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9508   else
9509     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9510   sym.st_target_internal = h->target_internal;
9511
9512   /* Give the processor backend a chance to tweak the symbol value,
9513      and also to finish up anything that needs to be done for this
9514      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9515      forced local syms when non-shared is due to a historical quirk.
9516      STT_GNU_IFUNC symbol must go through PLT.  */
9517   if ((h->type == STT_GNU_IFUNC
9518        && h->def_regular
9519        && !bfd_link_relocatable (flinfo->info))
9520       || ((h->dynindx != -1
9521            || h->forced_local)
9522           && ((bfd_link_pic (flinfo->info)
9523                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9524                    || h->root.type != bfd_link_hash_undefweak))
9525               || !h->forced_local)
9526           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9527     {
9528       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9529              (flinfo->output_bfd, flinfo->info, h, &sym)))
9530         {
9531           eoinfo->failed = TRUE;
9532           return FALSE;
9533         }
9534     }
9535
9536   /* If we are marking the symbol as undefined, and there are no
9537      non-weak references to this symbol from a regular object, then
9538      mark the symbol as weak undefined; if there are non-weak
9539      references, mark the symbol as strong.  We can't do this earlier,
9540      because it might not be marked as undefined until the
9541      finish_dynamic_symbol routine gets through with it.  */
9542   if (sym.st_shndx == SHN_UNDEF
9543       && h->ref_regular
9544       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9545           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9546     {
9547       int bindtype;
9548       type = ELF_ST_TYPE (sym.st_info);
9549
9550       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9551       if (type == STT_GNU_IFUNC)
9552         type = STT_FUNC;
9553
9554       if (h->ref_regular_nonweak)
9555         bindtype = STB_GLOBAL;
9556       else
9557         bindtype = STB_WEAK;
9558       sym.st_info = ELF_ST_INFO (bindtype, type);
9559     }
9560
9561   /* If this is a symbol defined in a dynamic library, don't use the
9562      symbol size from the dynamic library.  Relinking an executable
9563      against a new library may introduce gratuitous changes in the
9564      executable's symbols if we keep the size.  */
9565   if (sym.st_shndx == SHN_UNDEF
9566       && !h->def_regular
9567       && h->def_dynamic)
9568     sym.st_size = 0;
9569
9570   /* If a non-weak symbol with non-default visibility is not defined
9571      locally, it is a fatal error.  */
9572   if (!bfd_link_relocatable (flinfo->info)
9573       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9574       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9575       && h->root.type == bfd_link_hash_undefined
9576       && !h->def_regular)
9577     {
9578       const char *msg;
9579
9580       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9581         /* xgettext:c-format */
9582         msg = _("%B: protected symbol `%s' isn't defined");
9583       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9584         /* xgettext:c-format */
9585         msg = _("%B: internal symbol `%s' isn't defined");
9586       else
9587         /* xgettext:c-format */
9588         msg = _("%B: hidden symbol `%s' isn't defined");
9589       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9590       bfd_set_error (bfd_error_bad_value);
9591       eoinfo->failed = TRUE;
9592       return FALSE;
9593     }
9594
9595   /* If this symbol should be put in the .dynsym section, then put it
9596      there now.  We already know the symbol index.  We also fill in
9597      the entry in the .hash section.  */
9598   if (elf_hash_table (flinfo->info)->dynsym != NULL
9599       && h->dynindx != -1
9600       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9601     {
9602       bfd_byte *esym;
9603
9604       /* Since there is no version information in the dynamic string,
9605          if there is no version info in symbol version section, we will
9606          have a run-time problem if not linking executable, referenced
9607          by shared library, not locally defined, or not bound locally.
9608       */
9609       if (h->verinfo.verdef == NULL
9610           && !local_bind
9611           && (!bfd_link_executable (flinfo->info)
9612               || h->ref_dynamic
9613               || !h->def_regular))
9614         {
9615           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9616
9617           if (p && p [1] != '\0')
9618             {
9619               _bfd_error_handler
9620                 /* xgettext:c-format */
9621                 (_("%B: No symbol version section for versioned symbol `%s'"),
9622                  flinfo->output_bfd, h->root.root.string);
9623               eoinfo->failed = TRUE;
9624               return FALSE;
9625             }
9626         }
9627
9628       sym.st_name = h->dynstr_index;
9629       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9630               + h->dynindx * bed->s->sizeof_sym);
9631       if (!check_dynsym (flinfo->output_bfd, &sym))
9632         {
9633           eoinfo->failed = TRUE;
9634           return FALSE;
9635         }
9636       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9637
9638       if (flinfo->hash_sec != NULL)
9639         {
9640           size_t hash_entry_size;
9641           bfd_byte *bucketpos;
9642           bfd_vma chain;
9643           size_t bucketcount;
9644           size_t bucket;
9645
9646           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9647           bucket = h->u.elf_hash_value % bucketcount;
9648
9649           hash_entry_size
9650             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9651           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9652                        + (bucket + 2) * hash_entry_size);
9653           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9654           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9655                    bucketpos);
9656           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9657                    ((bfd_byte *) flinfo->hash_sec->contents
9658                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9659         }
9660
9661       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9662         {
9663           Elf_Internal_Versym iversym;
9664           Elf_External_Versym *eversym;
9665
9666           if (!h->def_regular)
9667             {
9668               if (h->verinfo.verdef == NULL
9669                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9670                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9671                 iversym.vs_vers = 0;
9672               else
9673                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9674             }
9675           else
9676             {
9677               if (h->verinfo.vertree == NULL)
9678                 iversym.vs_vers = 1;
9679               else
9680                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9681               if (flinfo->info->create_default_symver)
9682                 iversym.vs_vers++;
9683             }
9684
9685           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9686              defined locally.  */
9687           if (h->versioned == versioned_hidden && h->def_regular)
9688             iversym.vs_vers |= VERSYM_HIDDEN;
9689
9690           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9691           eversym += h->dynindx;
9692           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9693         }
9694     }
9695
9696   /* If the symbol is undefined, and we didn't output it to .dynsym,
9697      strip it from .symtab too.  Obviously we can't do this for
9698      relocatable output or when needed for --emit-relocs.  */
9699   else if (input_sec == bfd_und_section_ptr
9700            && h->indx != -2
9701            && !bfd_link_relocatable (flinfo->info))
9702     return TRUE;
9703   /* Also strip others that we couldn't earlier due to dynamic symbol
9704      processing.  */
9705   if (strip)
9706     return TRUE;
9707   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9708     return TRUE;
9709
9710   /* Output a FILE symbol so that following locals are not associated
9711      with the wrong input file.  We need one for forced local symbols
9712      if we've seen more than one FILE symbol or when we have exactly
9713      one FILE symbol but global symbols are present in a file other
9714      than the one with the FILE symbol.  We also need one if linker
9715      defined symbols are present.  In practice these conditions are
9716      always met, so just emit the FILE symbol unconditionally.  */
9717   if (eoinfo->localsyms
9718       && !eoinfo->file_sym_done
9719       && eoinfo->flinfo->filesym_count != 0)
9720     {
9721       Elf_Internal_Sym fsym;
9722
9723       memset (&fsym, 0, sizeof (fsym));
9724       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9725       fsym.st_shndx = SHN_ABS;
9726       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9727                                       bfd_und_section_ptr, NULL))
9728         return FALSE;
9729
9730       eoinfo->file_sym_done = TRUE;
9731     }
9732
9733   indx = bfd_get_symcount (flinfo->output_bfd);
9734   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9735                                    input_sec, h);
9736   if (ret == 0)
9737     {
9738       eoinfo->failed = TRUE;
9739       return FALSE;
9740     }
9741   else if (ret == 1)
9742     h->indx = indx;
9743   else if (h->indx == -2)
9744     abort();
9745
9746   return TRUE;
9747 }
9748
9749 /* Return TRUE if special handling is done for relocs in SEC against
9750    symbols defined in discarded sections.  */
9751
9752 static bfd_boolean
9753 elf_section_ignore_discarded_relocs (asection *sec)
9754 {
9755   const struct elf_backend_data *bed;
9756
9757   switch (sec->sec_info_type)
9758     {
9759     case SEC_INFO_TYPE_STABS:
9760     case SEC_INFO_TYPE_EH_FRAME:
9761     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9762       return TRUE;
9763     default:
9764       break;
9765     }
9766
9767   bed = get_elf_backend_data (sec->owner);
9768   if (bed->elf_backend_ignore_discarded_relocs != NULL
9769       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9770     return TRUE;
9771
9772   return FALSE;
9773 }
9774
9775 /* Return a mask saying how ld should treat relocations in SEC against
9776    symbols defined in discarded sections.  If this function returns
9777    COMPLAIN set, ld will issue a warning message.  If this function
9778    returns PRETEND set, and the discarded section was link-once and the
9779    same size as the kept link-once section, ld will pretend that the
9780    symbol was actually defined in the kept section.  Otherwise ld will
9781    zero the reloc (at least that is the intent, but some cooperation by
9782    the target dependent code is needed, particularly for REL targets).  */
9783
9784 unsigned int
9785 _bfd_elf_default_action_discarded (asection *sec)
9786 {
9787   if (sec->flags & SEC_DEBUGGING)
9788     return PRETEND;
9789
9790   if (strcmp (".eh_frame", sec->name) == 0)
9791     return 0;
9792
9793   if (strcmp (".gcc_except_table", sec->name) == 0)
9794     return 0;
9795
9796   return COMPLAIN | PRETEND;
9797 }
9798
9799 /* Find a match between a section and a member of a section group.  */
9800
9801 static asection *
9802 match_group_member (asection *sec, asection *group,
9803                     struct bfd_link_info *info)
9804 {
9805   asection *first = elf_next_in_group (group);
9806   asection *s = first;
9807
9808   while (s != NULL)
9809     {
9810       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9811         return s;
9812
9813       s = elf_next_in_group (s);
9814       if (s == first)
9815         break;
9816     }
9817
9818   return NULL;
9819 }
9820
9821 /* Check if the kept section of a discarded section SEC can be used
9822    to replace it.  Return the replacement if it is OK.  Otherwise return
9823    NULL.  */
9824
9825 asection *
9826 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9827 {
9828   asection *kept;
9829
9830   kept = sec->kept_section;
9831   if (kept != NULL)
9832     {
9833       if ((kept->flags & SEC_GROUP) != 0)
9834         kept = match_group_member (sec, kept, info);
9835       if (kept != NULL
9836           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9837               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9838         kept = NULL;
9839       sec->kept_section = kept;
9840     }
9841   return kept;
9842 }
9843
9844 /* Link an input file into the linker output file.  This function
9845    handles all the sections and relocations of the input file at once.
9846    This is so that we only have to read the local symbols once, and
9847    don't have to keep them in memory.  */
9848
9849 static bfd_boolean
9850 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9851 {
9852   int (*relocate_section)
9853     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9854      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9855   bfd *output_bfd;
9856   Elf_Internal_Shdr *symtab_hdr;
9857   size_t locsymcount;
9858   size_t extsymoff;
9859   Elf_Internal_Sym *isymbuf;
9860   Elf_Internal_Sym *isym;
9861   Elf_Internal_Sym *isymend;
9862   long *pindex;
9863   asection **ppsection;
9864   asection *o;
9865   const struct elf_backend_data *bed;
9866   struct elf_link_hash_entry **sym_hashes;
9867   bfd_size_type address_size;
9868   bfd_vma r_type_mask;
9869   int r_sym_shift;
9870   bfd_boolean have_file_sym = FALSE;
9871
9872   output_bfd = flinfo->output_bfd;
9873   bed = get_elf_backend_data (output_bfd);
9874   relocate_section = bed->elf_backend_relocate_section;
9875
9876   /* If this is a dynamic object, we don't want to do anything here:
9877      we don't want the local symbols, and we don't want the section
9878      contents.  */
9879   if ((input_bfd->flags & DYNAMIC) != 0)
9880     return TRUE;
9881
9882   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9883   if (elf_bad_symtab (input_bfd))
9884     {
9885       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9886       extsymoff = 0;
9887     }
9888   else
9889     {
9890       locsymcount = symtab_hdr->sh_info;
9891       extsymoff = symtab_hdr->sh_info;
9892     }
9893
9894   /* Read the local symbols.  */
9895   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9896   if (isymbuf == NULL && locsymcount != 0)
9897     {
9898       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9899                                       flinfo->internal_syms,
9900                                       flinfo->external_syms,
9901                                       flinfo->locsym_shndx);
9902       if (isymbuf == NULL)
9903         return FALSE;
9904     }
9905
9906   /* Find local symbol sections and adjust values of symbols in
9907      SEC_MERGE sections.  Write out those local symbols we know are
9908      going into the output file.  */
9909   isymend = isymbuf + locsymcount;
9910   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9911        isym < isymend;
9912        isym++, pindex++, ppsection++)
9913     {
9914       asection *isec;
9915       const char *name;
9916       Elf_Internal_Sym osym;
9917       long indx;
9918       int ret;
9919
9920       *pindex = -1;
9921
9922       if (elf_bad_symtab (input_bfd))
9923         {
9924           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9925             {
9926               *ppsection = NULL;
9927               continue;
9928             }
9929         }
9930
9931       if (isym->st_shndx == SHN_UNDEF)
9932         isec = bfd_und_section_ptr;
9933       else if (isym->st_shndx == SHN_ABS)
9934         isec = bfd_abs_section_ptr;
9935       else if (isym->st_shndx == SHN_COMMON)
9936         isec = bfd_com_section_ptr;
9937       else
9938         {
9939           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9940           if (isec == NULL)
9941             {
9942               /* Don't attempt to output symbols with st_shnx in the
9943                  reserved range other than SHN_ABS and SHN_COMMON.  */
9944               *ppsection = NULL;
9945               continue;
9946             }
9947           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9948                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9949             isym->st_value =
9950               _bfd_merged_section_offset (output_bfd, &isec,
9951                                           elf_section_data (isec)->sec_info,
9952                                           isym->st_value);
9953         }
9954
9955       *ppsection = isec;
9956
9957       /* Don't output the first, undefined, symbol.  In fact, don't
9958          output any undefined local symbol.  */
9959       if (isec == bfd_und_section_ptr)
9960         continue;
9961
9962       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9963         {
9964           /* We never output section symbols.  Instead, we use the
9965              section symbol of the corresponding section in the output
9966              file.  */
9967           continue;
9968         }
9969
9970       /* If we are stripping all symbols, we don't want to output this
9971          one.  */
9972       if (flinfo->info->strip == strip_all)
9973         continue;
9974
9975       /* If we are discarding all local symbols, we don't want to
9976          output this one.  If we are generating a relocatable output
9977          file, then some of the local symbols may be required by
9978          relocs; we output them below as we discover that they are
9979          needed.  */
9980       if (flinfo->info->discard == discard_all)
9981         continue;
9982
9983       /* If this symbol is defined in a section which we are
9984          discarding, we don't need to keep it.  */
9985       if (isym->st_shndx != SHN_UNDEF
9986           && isym->st_shndx < SHN_LORESERVE
9987           && bfd_section_removed_from_list (output_bfd,
9988                                             isec->output_section))
9989         continue;
9990
9991       /* Get the name of the symbol.  */
9992       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9993                                               isym->st_name);
9994       if (name == NULL)
9995         return FALSE;
9996
9997       /* See if we are discarding symbols with this name.  */
9998       if ((flinfo->info->strip == strip_some
9999            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10000                == NULL))
10001           || (((flinfo->info->discard == discard_sec_merge
10002                 && (isec->flags & SEC_MERGE)
10003                 && !bfd_link_relocatable (flinfo->info))
10004                || flinfo->info->discard == discard_l)
10005               && bfd_is_local_label_name (input_bfd, name)))
10006         continue;
10007
10008       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10009         {
10010           if (input_bfd->lto_output)
10011             /* -flto puts a temp file name here.  This means builds
10012                are not reproducible.  Discard the symbol.  */
10013             continue;
10014           have_file_sym = TRUE;
10015           flinfo->filesym_count += 1;
10016         }
10017       if (!have_file_sym)
10018         {
10019           /* In the absence of debug info, bfd_find_nearest_line uses
10020              FILE symbols to determine the source file for local
10021              function symbols.  Provide a FILE symbol here if input
10022              files lack such, so that their symbols won't be
10023              associated with a previous input file.  It's not the
10024              source file, but the best we can do.  */
10025           have_file_sym = TRUE;
10026           flinfo->filesym_count += 1;
10027           memset (&osym, 0, sizeof (osym));
10028           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10029           osym.st_shndx = SHN_ABS;
10030           if (!elf_link_output_symstrtab (flinfo,
10031                                           (input_bfd->lto_output ? NULL
10032                                            : input_bfd->filename),
10033                                           &osym, bfd_abs_section_ptr,
10034                                           NULL))
10035             return FALSE;
10036         }
10037
10038       osym = *isym;
10039
10040       /* Adjust the section index for the output file.  */
10041       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10042                                                          isec->output_section);
10043       if (osym.st_shndx == SHN_BAD)
10044         return FALSE;
10045
10046       /* ELF symbols in relocatable files are section relative, but
10047          in executable files they are virtual addresses.  Note that
10048          this code assumes that all ELF sections have an associated
10049          BFD section with a reasonable value for output_offset; below
10050          we assume that they also have a reasonable value for
10051          output_section.  Any special sections must be set up to meet
10052          these requirements.  */
10053       osym.st_value += isec->output_offset;
10054       if (!bfd_link_relocatable (flinfo->info))
10055         {
10056           osym.st_value += isec->output_section->vma;
10057           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10058             {
10059               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10060               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10061               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10062             }
10063         }
10064
10065       indx = bfd_get_symcount (output_bfd);
10066       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10067       if (ret == 0)
10068         return FALSE;
10069       else if (ret == 1)
10070         *pindex = indx;
10071     }
10072
10073   if (bed->s->arch_size == 32)
10074     {
10075       r_type_mask = 0xff;
10076       r_sym_shift = 8;
10077       address_size = 4;
10078     }
10079   else
10080     {
10081       r_type_mask = 0xffffffff;
10082       r_sym_shift = 32;
10083       address_size = 8;
10084     }
10085
10086   /* Relocate the contents of each section.  */
10087   sym_hashes = elf_sym_hashes (input_bfd);
10088   for (o = input_bfd->sections; o != NULL; o = o->next)
10089     {
10090       bfd_byte *contents;
10091
10092       if (! o->linker_mark)
10093         {
10094           /* This section was omitted from the link.  */
10095           continue;
10096         }
10097
10098       if (bfd_link_relocatable (flinfo->info)
10099           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10100         {
10101           /* Deal with the group signature symbol.  */
10102           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10103           unsigned long symndx = sec_data->this_hdr.sh_info;
10104           asection *osec = o->output_section;
10105
10106           if (symndx >= locsymcount
10107               || (elf_bad_symtab (input_bfd)
10108                   && flinfo->sections[symndx] == NULL))
10109             {
10110               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10111               while (h->root.type == bfd_link_hash_indirect
10112                      || h->root.type == bfd_link_hash_warning)
10113                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10114               /* Arrange for symbol to be output.  */
10115               h->indx = -2;
10116               elf_section_data (osec)->this_hdr.sh_info = -2;
10117             }
10118           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10119             {
10120               /* We'll use the output section target_index.  */
10121               asection *sec = flinfo->sections[symndx]->output_section;
10122               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10123             }
10124           else
10125             {
10126               if (flinfo->indices[symndx] == -1)
10127                 {
10128                   /* Otherwise output the local symbol now.  */
10129                   Elf_Internal_Sym sym = isymbuf[symndx];
10130                   asection *sec = flinfo->sections[symndx]->output_section;
10131                   const char *name;
10132                   long indx;
10133                   int ret;
10134
10135                   name = bfd_elf_string_from_elf_section (input_bfd,
10136                                                           symtab_hdr->sh_link,
10137                                                           sym.st_name);
10138                   if (name == NULL)
10139                     return FALSE;
10140
10141                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10142                                                                     sec);
10143                   if (sym.st_shndx == SHN_BAD)
10144                     return FALSE;
10145
10146                   sym.st_value += o->output_offset;
10147
10148                   indx = bfd_get_symcount (output_bfd);
10149                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10150                                                    NULL);
10151                   if (ret == 0)
10152                     return FALSE;
10153                   else if (ret == 1)
10154                     flinfo->indices[symndx] = indx;
10155                   else
10156                     abort ();
10157                 }
10158               elf_section_data (osec)->this_hdr.sh_info
10159                 = flinfo->indices[symndx];
10160             }
10161         }
10162
10163       if ((o->flags & SEC_HAS_CONTENTS) == 0
10164           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10165         continue;
10166
10167       if ((o->flags & SEC_LINKER_CREATED) != 0)
10168         {
10169           /* Section was created by _bfd_elf_link_create_dynamic_sections
10170              or somesuch.  */
10171           continue;
10172         }
10173
10174       /* Get the contents of the section.  They have been cached by a
10175          relaxation routine.  Note that o is a section in an input
10176          file, so the contents field will not have been set by any of
10177          the routines which work on output files.  */
10178       if (elf_section_data (o)->this_hdr.contents != NULL)
10179         {
10180           contents = elf_section_data (o)->this_hdr.contents;
10181           if (bed->caches_rawsize
10182               && o->rawsize != 0
10183               && o->rawsize < o->size)
10184             {
10185               memcpy (flinfo->contents, contents, o->rawsize);
10186               contents = flinfo->contents;
10187             }
10188         }
10189       else
10190         {
10191           contents = flinfo->contents;
10192           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10193             return FALSE;
10194         }
10195
10196       if ((o->flags & SEC_RELOC) != 0)
10197         {
10198           Elf_Internal_Rela *internal_relocs;
10199           Elf_Internal_Rela *rel, *relend;
10200           int action_discarded;
10201           int ret;
10202
10203           /* Get the swapped relocs.  */
10204           internal_relocs
10205             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10206                                          flinfo->internal_relocs, FALSE);
10207           if (internal_relocs == NULL
10208               && o->reloc_count > 0)
10209             return FALSE;
10210
10211           /* We need to reverse-copy input .ctors/.dtors sections if
10212              they are placed in .init_array/.finit_array for output.  */
10213           if (o->size > address_size
10214               && ((strncmp (o->name, ".ctors", 6) == 0
10215                    && strcmp (o->output_section->name,
10216                               ".init_array") == 0)
10217                   || (strncmp (o->name, ".dtors", 6) == 0
10218                       && strcmp (o->output_section->name,
10219                                  ".fini_array") == 0))
10220               && (o->name[6] == 0 || o->name[6] == '.'))
10221             {
10222               if (o->size != o->reloc_count * address_size)
10223                 {
10224                   _bfd_error_handler
10225                     /* xgettext:c-format */
10226                     (_("error: %B: size of section %A is not "
10227                        "multiple of address size"),
10228                      input_bfd, o);
10229                   bfd_set_error (bfd_error_on_input);
10230                   return FALSE;
10231                 }
10232               o->flags |= SEC_ELF_REVERSE_COPY;
10233             }
10234
10235           action_discarded = -1;
10236           if (!elf_section_ignore_discarded_relocs (o))
10237             action_discarded = (*bed->action_discarded) (o);
10238
10239           /* Run through the relocs evaluating complex reloc symbols and
10240              looking for relocs against symbols from discarded sections
10241              or section symbols from removed link-once sections.
10242              Complain about relocs against discarded sections.  Zero
10243              relocs against removed link-once sections.  */
10244
10245           rel = internal_relocs;
10246           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10247           for ( ; rel < relend; rel++)
10248             {
10249               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10250               unsigned int s_type;
10251               asection **ps, *sec;
10252               struct elf_link_hash_entry *h = NULL;
10253               const char *sym_name;
10254
10255               if (r_symndx == STN_UNDEF)
10256                 continue;
10257
10258               if (r_symndx >= locsymcount
10259                   || (elf_bad_symtab (input_bfd)
10260                       && flinfo->sections[r_symndx] == NULL))
10261                 {
10262                   h = sym_hashes[r_symndx - extsymoff];
10263
10264                   /* Badly formatted input files can contain relocs that
10265                      reference non-existant symbols.  Check here so that
10266                      we do not seg fault.  */
10267                   if (h == NULL)
10268                     {
10269                       char buffer [32];
10270
10271                       sprintf_vma (buffer, rel->r_info);
10272                       _bfd_error_handler
10273                         /* xgettext:c-format */
10274                         (_("error: %B contains a reloc (0x%s) for section %A "
10275                            "that references a non-existent global symbol"),
10276                          input_bfd, o, buffer);
10277                       bfd_set_error (bfd_error_bad_value);
10278                       return FALSE;
10279                     }
10280
10281                   while (h->root.type == bfd_link_hash_indirect
10282                          || h->root.type == bfd_link_hash_warning)
10283                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10284
10285                   s_type = h->type;
10286
10287                   /* If a plugin symbol is referenced from a non-IR file,
10288                      mark the symbol as undefined.  Note that the
10289                      linker may attach linker created dynamic sections
10290                      to the plugin bfd.  Symbols defined in linker
10291                      created sections are not plugin symbols.  */
10292                   if (h->root.non_ir_ref
10293                       && (h->root.type == bfd_link_hash_defined
10294                           || h->root.type == bfd_link_hash_defweak)
10295                       && (h->root.u.def.section->flags
10296                           & SEC_LINKER_CREATED) == 0
10297                       && h->root.u.def.section->owner != NULL
10298                       && (h->root.u.def.section->owner->flags
10299                           & BFD_PLUGIN) != 0)
10300                     {
10301                       h->root.type = bfd_link_hash_undefined;
10302                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10303                     }
10304
10305                   ps = NULL;
10306                   if (h->root.type == bfd_link_hash_defined
10307                       || h->root.type == bfd_link_hash_defweak)
10308                     ps = &h->root.u.def.section;
10309
10310                   sym_name = h->root.root.string;
10311                 }
10312               else
10313                 {
10314                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10315
10316                   s_type = ELF_ST_TYPE (sym->st_info);
10317                   ps = &flinfo->sections[r_symndx];
10318                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10319                                                sym, *ps);
10320                 }
10321
10322               if ((s_type == STT_RELC || s_type == STT_SRELC)
10323                   && !bfd_link_relocatable (flinfo->info))
10324                 {
10325                   bfd_vma val;
10326                   bfd_vma dot = (rel->r_offset
10327                                  + o->output_offset + o->output_section->vma);
10328 #ifdef DEBUG
10329                   printf ("Encountered a complex symbol!");
10330                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10331                           input_bfd->filename, o->name,
10332                           (long) (rel - internal_relocs));
10333                   printf (" symbol: idx  %8.8lx, name %s\n",
10334                           r_symndx, sym_name);
10335                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10336                           (unsigned long) rel->r_info,
10337                           (unsigned long) rel->r_offset);
10338 #endif
10339                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10340                                     isymbuf, locsymcount, s_type == STT_SRELC))
10341                     return FALSE;
10342
10343                   /* Symbol evaluated OK.  Update to absolute value.  */
10344                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10345                                     r_symndx, val);
10346                   continue;
10347                 }
10348
10349               if (action_discarded != -1 && ps != NULL)
10350                 {
10351                   /* Complain if the definition comes from a
10352                      discarded section.  */
10353                   if ((sec = *ps) != NULL && discarded_section (sec))
10354                     {
10355                       BFD_ASSERT (r_symndx != STN_UNDEF);
10356                       if (action_discarded & COMPLAIN)
10357                         (*flinfo->info->callbacks->einfo)
10358                           /* xgettext:c-format */
10359                           (_("%X`%s' referenced in section `%A' of %B: "
10360                              "defined in discarded section `%A' of %B\n"),
10361                            sym_name, o, input_bfd, sec, sec->owner);
10362
10363                       /* Try to do the best we can to support buggy old
10364                          versions of gcc.  Pretend that the symbol is
10365                          really defined in the kept linkonce section.
10366                          FIXME: This is quite broken.  Modifying the
10367                          symbol here means we will be changing all later
10368                          uses of the symbol, not just in this section.  */
10369                       if (action_discarded & PRETEND)
10370                         {
10371                           asection *kept;
10372
10373                           kept = _bfd_elf_check_kept_section (sec,
10374                                                               flinfo->info);
10375                           if (kept != NULL)
10376                             {
10377                               *ps = kept;
10378                               continue;
10379                             }
10380                         }
10381                     }
10382                 }
10383             }
10384
10385           /* Relocate the section by invoking a back end routine.
10386
10387              The back end routine is responsible for adjusting the
10388              section contents as necessary, and (if using Rela relocs
10389              and generating a relocatable output file) adjusting the
10390              reloc addend as necessary.
10391
10392              The back end routine does not have to worry about setting
10393              the reloc address or the reloc symbol index.
10394
10395              The back end routine is given a pointer to the swapped in
10396              internal symbols, and can access the hash table entries
10397              for the external symbols via elf_sym_hashes (input_bfd).
10398
10399              When generating relocatable output, the back end routine
10400              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10401              output symbol is going to be a section symbol
10402              corresponding to the output section, which will require
10403              the addend to be adjusted.  */
10404
10405           ret = (*relocate_section) (output_bfd, flinfo->info,
10406                                      input_bfd, o, contents,
10407                                      internal_relocs,
10408                                      isymbuf,
10409                                      flinfo->sections);
10410           if (!ret)
10411             return FALSE;
10412
10413           if (ret == 2
10414               || bfd_link_relocatable (flinfo->info)
10415               || flinfo->info->emitrelocations)
10416             {
10417               Elf_Internal_Rela *irela;
10418               Elf_Internal_Rela *irelaend, *irelamid;
10419               bfd_vma last_offset;
10420               struct elf_link_hash_entry **rel_hash;
10421               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10422               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10423               unsigned int next_erel;
10424               bfd_boolean rela_normal;
10425               struct bfd_elf_section_data *esdi, *esdo;
10426
10427               esdi = elf_section_data (o);
10428               esdo = elf_section_data (o->output_section);
10429               rela_normal = FALSE;
10430
10431               /* Adjust the reloc addresses and symbol indices.  */
10432
10433               irela = internal_relocs;
10434               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10435               rel_hash = esdo->rel.hashes + esdo->rel.count;
10436               /* We start processing the REL relocs, if any.  When we reach
10437                  IRELAMID in the loop, we switch to the RELA relocs.  */
10438               irelamid = irela;
10439               if (esdi->rel.hdr != NULL)
10440                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10441                              * bed->s->int_rels_per_ext_rel);
10442               rel_hash_list = rel_hash;
10443               rela_hash_list = NULL;
10444               last_offset = o->output_offset;
10445               if (!bfd_link_relocatable (flinfo->info))
10446                 last_offset += o->output_section->vma;
10447               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10448                 {
10449                   unsigned long r_symndx;
10450                   asection *sec;
10451                   Elf_Internal_Sym sym;
10452
10453                   if (next_erel == bed->s->int_rels_per_ext_rel)
10454                     {
10455                       rel_hash++;
10456                       next_erel = 0;
10457                     }
10458
10459                   if (irela == irelamid)
10460                     {
10461                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10462                       rela_hash_list = rel_hash;
10463                       rela_normal = bed->rela_normal;
10464                     }
10465
10466                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10467                                                              flinfo->info, o,
10468                                                              irela->r_offset);
10469                   if (irela->r_offset >= (bfd_vma) -2)
10470                     {
10471                       /* This is a reloc for a deleted entry or somesuch.
10472                          Turn it into an R_*_NONE reloc, at the same
10473                          offset as the last reloc.  elf_eh_frame.c and
10474                          bfd_elf_discard_info rely on reloc offsets
10475                          being ordered.  */
10476                       irela->r_offset = last_offset;
10477                       irela->r_info = 0;
10478                       irela->r_addend = 0;
10479                       continue;
10480                     }
10481
10482                   irela->r_offset += o->output_offset;
10483
10484                   /* Relocs in an executable have to be virtual addresses.  */
10485                   if (!bfd_link_relocatable (flinfo->info))
10486                     irela->r_offset += o->output_section->vma;
10487
10488                   last_offset = irela->r_offset;
10489
10490                   r_symndx = irela->r_info >> r_sym_shift;
10491                   if (r_symndx == STN_UNDEF)
10492                     continue;
10493
10494                   if (r_symndx >= locsymcount
10495                       || (elf_bad_symtab (input_bfd)
10496                           && flinfo->sections[r_symndx] == NULL))
10497                     {
10498                       struct elf_link_hash_entry *rh;
10499                       unsigned long indx;
10500
10501                       /* This is a reloc against a global symbol.  We
10502                          have not yet output all the local symbols, so
10503                          we do not know the symbol index of any global
10504                          symbol.  We set the rel_hash entry for this
10505                          reloc to point to the global hash table entry
10506                          for this symbol.  The symbol index is then
10507                          set at the end of bfd_elf_final_link.  */
10508                       indx = r_symndx - extsymoff;
10509                       rh = elf_sym_hashes (input_bfd)[indx];
10510                       while (rh->root.type == bfd_link_hash_indirect
10511                              || rh->root.type == bfd_link_hash_warning)
10512                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10513
10514                       /* Setting the index to -2 tells
10515                          elf_link_output_extsym that this symbol is
10516                          used by a reloc.  */
10517                       BFD_ASSERT (rh->indx < 0);
10518                       rh->indx = -2;
10519
10520                       *rel_hash = rh;
10521
10522                       continue;
10523                     }
10524
10525                   /* This is a reloc against a local symbol.  */
10526
10527                   *rel_hash = NULL;
10528                   sym = isymbuf[r_symndx];
10529                   sec = flinfo->sections[r_symndx];
10530                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10531                     {
10532                       /* I suppose the backend ought to fill in the
10533                          section of any STT_SECTION symbol against a
10534                          processor specific section.  */
10535                       r_symndx = STN_UNDEF;
10536                       if (bfd_is_abs_section (sec))
10537                         ;
10538                       else if (sec == NULL || sec->owner == NULL)
10539                         {
10540                           bfd_set_error (bfd_error_bad_value);
10541                           return FALSE;
10542                         }
10543                       else
10544                         {
10545                           asection *osec = sec->output_section;
10546
10547                           /* If we have discarded a section, the output
10548                              section will be the absolute section.  In
10549                              case of discarded SEC_MERGE sections, use
10550                              the kept section.  relocate_section should
10551                              have already handled discarded linkonce
10552                              sections.  */
10553                           if (bfd_is_abs_section (osec)
10554                               && sec->kept_section != NULL
10555                               && sec->kept_section->output_section != NULL)
10556                             {
10557                               osec = sec->kept_section->output_section;
10558                               irela->r_addend -= osec->vma;
10559                             }
10560
10561                           if (!bfd_is_abs_section (osec))
10562                             {
10563                               r_symndx = osec->target_index;
10564                               if (r_symndx == STN_UNDEF)
10565                                 {
10566                                   irela->r_addend += osec->vma;
10567                                   osec = _bfd_nearby_section (output_bfd, osec,
10568                                                               osec->vma);
10569                                   irela->r_addend -= osec->vma;
10570                                   r_symndx = osec->target_index;
10571                                 }
10572                             }
10573                         }
10574
10575                       /* Adjust the addend according to where the
10576                          section winds up in the output section.  */
10577                       if (rela_normal)
10578                         irela->r_addend += sec->output_offset;
10579                     }
10580                   else
10581                     {
10582                       if (flinfo->indices[r_symndx] == -1)
10583                         {
10584                           unsigned long shlink;
10585                           const char *name;
10586                           asection *osec;
10587                           long indx;
10588
10589                           if (flinfo->info->strip == strip_all)
10590                             {
10591                               /* You can't do ld -r -s.  */
10592                               bfd_set_error (bfd_error_invalid_operation);
10593                               return FALSE;
10594                             }
10595
10596                           /* This symbol was skipped earlier, but
10597                              since it is needed by a reloc, we
10598                              must output it now.  */
10599                           shlink = symtab_hdr->sh_link;
10600                           name = (bfd_elf_string_from_elf_section
10601                                   (input_bfd, shlink, sym.st_name));
10602                           if (name == NULL)
10603                             return FALSE;
10604
10605                           osec = sec->output_section;
10606                           sym.st_shndx =
10607                             _bfd_elf_section_from_bfd_section (output_bfd,
10608                                                                osec);
10609                           if (sym.st_shndx == SHN_BAD)
10610                             return FALSE;
10611
10612                           sym.st_value += sec->output_offset;
10613                           if (!bfd_link_relocatable (flinfo->info))
10614                             {
10615                               sym.st_value += osec->vma;
10616                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10617                                 {
10618                                   /* STT_TLS symbols are relative to PT_TLS
10619                                      segment base.  */
10620                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10621                                               ->tls_sec != NULL);
10622                                   sym.st_value -= (elf_hash_table (flinfo->info)
10623                                                    ->tls_sec->vma);
10624                                 }
10625                             }
10626
10627                           indx = bfd_get_symcount (output_bfd);
10628                           ret = elf_link_output_symstrtab (flinfo, name,
10629                                                            &sym, sec,
10630                                                            NULL);
10631                           if (ret == 0)
10632                             return FALSE;
10633                           else if (ret == 1)
10634                             flinfo->indices[r_symndx] = indx;
10635                           else
10636                             abort ();
10637                         }
10638
10639                       r_symndx = flinfo->indices[r_symndx];
10640                     }
10641
10642                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10643                                    | (irela->r_info & r_type_mask));
10644                 }
10645
10646               /* Swap out the relocs.  */
10647               input_rel_hdr = esdi->rel.hdr;
10648               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10649                 {
10650                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10651                                                      input_rel_hdr,
10652                                                      internal_relocs,
10653                                                      rel_hash_list))
10654                     return FALSE;
10655                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10656                                       * bed->s->int_rels_per_ext_rel);
10657                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10658                 }
10659
10660               input_rela_hdr = esdi->rela.hdr;
10661               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10662                 {
10663                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10664                                                      input_rela_hdr,
10665                                                      internal_relocs,
10666                                                      rela_hash_list))
10667                     return FALSE;
10668                 }
10669             }
10670         }
10671
10672       /* Write out the modified section contents.  */
10673       if (bed->elf_backend_write_section
10674           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10675                                                 contents))
10676         {
10677           /* Section written out.  */
10678         }
10679       else switch (o->sec_info_type)
10680         {
10681         case SEC_INFO_TYPE_STABS:
10682           if (! (_bfd_write_section_stabs
10683                  (output_bfd,
10684                   &elf_hash_table (flinfo->info)->stab_info,
10685                   o, &elf_section_data (o)->sec_info, contents)))
10686             return FALSE;
10687           break;
10688         case SEC_INFO_TYPE_MERGE:
10689           if (! _bfd_write_merged_section (output_bfd, o,
10690                                            elf_section_data (o)->sec_info))
10691             return FALSE;
10692           break;
10693         case SEC_INFO_TYPE_EH_FRAME:
10694           {
10695             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10696                                                    o, contents))
10697               return FALSE;
10698           }
10699           break;
10700         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10701           {
10702             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10703                                                          flinfo->info,
10704                                                          o, contents))
10705               return FALSE;
10706           }
10707           break;
10708         default:
10709           {
10710             if (! (o->flags & SEC_EXCLUDE))
10711               {
10712                 file_ptr offset = (file_ptr) o->output_offset;
10713                 bfd_size_type todo = o->size;
10714
10715                 offset *= bfd_octets_per_byte (output_bfd);
10716
10717                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10718                   {
10719                     /* Reverse-copy input section to output.  */
10720                     do
10721                       {
10722                         todo -= address_size;
10723                         if (! bfd_set_section_contents (output_bfd,
10724                                                         o->output_section,
10725                                                         contents + todo,
10726                                                         offset,
10727                                                         address_size))
10728                           return FALSE;
10729                         if (todo == 0)
10730                           break;
10731                         offset += address_size;
10732                       }
10733                     while (1);
10734                   }
10735                 else if (! bfd_set_section_contents (output_bfd,
10736                                                      o->output_section,
10737                                                      contents,
10738                                                      offset, todo))
10739                   return FALSE;
10740               }
10741           }
10742           break;
10743         }
10744     }
10745
10746   return TRUE;
10747 }
10748
10749 /* Generate a reloc when linking an ELF file.  This is a reloc
10750    requested by the linker, and does not come from any input file.  This
10751    is used to build constructor and destructor tables when linking
10752    with -Ur.  */
10753
10754 static bfd_boolean
10755 elf_reloc_link_order (bfd *output_bfd,
10756                       struct bfd_link_info *info,
10757                       asection *output_section,
10758                       struct bfd_link_order *link_order)
10759 {
10760   reloc_howto_type *howto;
10761   long indx;
10762   bfd_vma offset;
10763   bfd_vma addend;
10764   struct bfd_elf_section_reloc_data *reldata;
10765   struct elf_link_hash_entry **rel_hash_ptr;
10766   Elf_Internal_Shdr *rel_hdr;
10767   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10768   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10769   bfd_byte *erel;
10770   unsigned int i;
10771   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10772
10773   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10774   if (howto == NULL)
10775     {
10776       bfd_set_error (bfd_error_bad_value);
10777       return FALSE;
10778     }
10779
10780   addend = link_order->u.reloc.p->addend;
10781
10782   if (esdo->rel.hdr)
10783     reldata = &esdo->rel;
10784   else if (esdo->rela.hdr)
10785     reldata = &esdo->rela;
10786   else
10787     {
10788       reldata = NULL;
10789       BFD_ASSERT (0);
10790     }
10791
10792   /* Figure out the symbol index.  */
10793   rel_hash_ptr = reldata->hashes + reldata->count;
10794   if (link_order->type == bfd_section_reloc_link_order)
10795     {
10796       indx = link_order->u.reloc.p->u.section->target_index;
10797       BFD_ASSERT (indx != 0);
10798       *rel_hash_ptr = NULL;
10799     }
10800   else
10801     {
10802       struct elf_link_hash_entry *h;
10803
10804       /* Treat a reloc against a defined symbol as though it were
10805          actually against the section.  */
10806       h = ((struct elf_link_hash_entry *)
10807            bfd_wrapped_link_hash_lookup (output_bfd, info,
10808                                          link_order->u.reloc.p->u.name,
10809                                          FALSE, FALSE, TRUE));
10810       if (h != NULL
10811           && (h->root.type == bfd_link_hash_defined
10812               || h->root.type == bfd_link_hash_defweak))
10813         {
10814           asection *section;
10815
10816           section = h->root.u.def.section;
10817           indx = section->output_section->target_index;
10818           *rel_hash_ptr = NULL;
10819           /* It seems that we ought to add the symbol value to the
10820              addend here, but in practice it has already been added
10821              because it was passed to constructor_callback.  */
10822           addend += section->output_section->vma + section->output_offset;
10823         }
10824       else if (h != NULL)
10825         {
10826           /* Setting the index to -2 tells elf_link_output_extsym that
10827              this symbol is used by a reloc.  */
10828           h->indx = -2;
10829           *rel_hash_ptr = h;
10830           indx = 0;
10831         }
10832       else
10833         {
10834           (*info->callbacks->unattached_reloc)
10835             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
10836           indx = 0;
10837         }
10838     }
10839
10840   /* If this is an inplace reloc, we must write the addend into the
10841      object file.  */
10842   if (howto->partial_inplace && addend != 0)
10843     {
10844       bfd_size_type size;
10845       bfd_reloc_status_type rstat;
10846       bfd_byte *buf;
10847       bfd_boolean ok;
10848       const char *sym_name;
10849
10850       size = (bfd_size_type) bfd_get_reloc_size (howto);
10851       buf = (bfd_byte *) bfd_zmalloc (size);
10852       if (buf == NULL && size != 0)
10853         return FALSE;
10854       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10855       switch (rstat)
10856         {
10857         case bfd_reloc_ok:
10858           break;
10859
10860         default:
10861         case bfd_reloc_outofrange:
10862           abort ();
10863
10864         case bfd_reloc_overflow:
10865           if (link_order->type == bfd_section_reloc_link_order)
10866             sym_name = bfd_section_name (output_bfd,
10867                                          link_order->u.reloc.p->u.section);
10868           else
10869             sym_name = link_order->u.reloc.p->u.name;
10870           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
10871                                               howto->name, addend, NULL, NULL,
10872                                               (bfd_vma) 0);
10873           break;
10874         }
10875
10876       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10877                                      link_order->offset
10878                                      * bfd_octets_per_byte (output_bfd),
10879                                      size);
10880       free (buf);
10881       if (! ok)
10882         return FALSE;
10883     }
10884
10885   /* The address of a reloc is relative to the section in a
10886      relocatable file, and is a virtual address in an executable
10887      file.  */
10888   offset = link_order->offset;
10889   if (! bfd_link_relocatable (info))
10890     offset += output_section->vma;
10891
10892   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10893     {
10894       irel[i].r_offset = offset;
10895       irel[i].r_info = 0;
10896       irel[i].r_addend = 0;
10897     }
10898   if (bed->s->arch_size == 32)
10899     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10900   else
10901     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10902
10903   rel_hdr = reldata->hdr;
10904   erel = rel_hdr->contents;
10905   if (rel_hdr->sh_type == SHT_REL)
10906     {
10907       erel += reldata->count * bed->s->sizeof_rel;
10908       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10909     }
10910   else
10911     {
10912       irel[0].r_addend = addend;
10913       erel += reldata->count * bed->s->sizeof_rela;
10914       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10915     }
10916
10917   ++reldata->count;
10918
10919   return TRUE;
10920 }
10921
10922
10923 /* Get the output vma of the section pointed to by the sh_link field.  */
10924
10925 static bfd_vma
10926 elf_get_linked_section_vma (struct bfd_link_order *p)
10927 {
10928   Elf_Internal_Shdr **elf_shdrp;
10929   asection *s;
10930   int elfsec;
10931
10932   s = p->u.indirect.section;
10933   elf_shdrp = elf_elfsections (s->owner);
10934   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10935   elfsec = elf_shdrp[elfsec]->sh_link;
10936   /* PR 290:
10937      The Intel C compiler generates SHT_IA_64_UNWIND with
10938      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10939      sh_info fields.  Hence we could get the situation
10940      where elfsec is 0.  */
10941   if (elfsec == 0)
10942     {
10943       const struct elf_backend_data *bed
10944         = get_elf_backend_data (s->owner);
10945       if (bed->link_order_error_handler)
10946         bed->link_order_error_handler
10947           /* xgettext:c-format */
10948           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10949       return 0;
10950     }
10951   else
10952     {
10953       s = elf_shdrp[elfsec]->bfd_section;
10954       return s->output_section->vma + s->output_offset;
10955     }
10956 }
10957
10958
10959 /* Compare two sections based on the locations of the sections they are
10960    linked to.  Used by elf_fixup_link_order.  */
10961
10962 static int
10963 compare_link_order (const void * a, const void * b)
10964 {
10965   bfd_vma apos;
10966   bfd_vma bpos;
10967
10968   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10969   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10970   if (apos < bpos)
10971     return -1;
10972   return apos > bpos;
10973 }
10974
10975
10976 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10977    order as their linked sections.  Returns false if this could not be done
10978    because an output section includes both ordered and unordered
10979    sections.  Ideally we'd do this in the linker proper.  */
10980
10981 static bfd_boolean
10982 elf_fixup_link_order (bfd *abfd, asection *o)
10983 {
10984   int seen_linkorder;
10985   int seen_other;
10986   int n;
10987   struct bfd_link_order *p;
10988   bfd *sub;
10989   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10990   unsigned elfsec;
10991   struct bfd_link_order **sections;
10992   asection *s, *other_sec, *linkorder_sec;
10993   bfd_vma offset;
10994
10995   other_sec = NULL;
10996   linkorder_sec = NULL;
10997   seen_other = 0;
10998   seen_linkorder = 0;
10999   for (p = o->map_head.link_order; p != NULL; p = p->next)
11000     {
11001       if (p->type == bfd_indirect_link_order)
11002         {
11003           s = p->u.indirect.section;
11004           sub = s->owner;
11005           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11006               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11007               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11008               && elfsec < elf_numsections (sub)
11009               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11010               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11011             {
11012               seen_linkorder++;
11013               linkorder_sec = s;
11014             }
11015           else
11016             {
11017               seen_other++;
11018               other_sec = s;
11019             }
11020         }
11021       else
11022         seen_other++;
11023
11024       if (seen_other && seen_linkorder)
11025         {
11026           if (other_sec && linkorder_sec)
11027             _bfd_error_handler
11028               /* xgettext:c-format */
11029               (_("%A has both ordered [`%A' in %B] "
11030                  "and unordered [`%A' in %B] sections"),
11031                o, linkorder_sec,
11032                linkorder_sec->owner, other_sec,
11033                other_sec->owner);
11034           else
11035             _bfd_error_handler
11036               (_("%A has both ordered and unordered sections"), o);
11037           bfd_set_error (bfd_error_bad_value);
11038           return FALSE;
11039         }
11040     }
11041
11042   if (!seen_linkorder)
11043     return TRUE;
11044
11045   sections = (struct bfd_link_order **)
11046     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11047   if (sections == NULL)
11048     return FALSE;
11049   seen_linkorder = 0;
11050
11051   for (p = o->map_head.link_order; p != NULL; p = p->next)
11052     {
11053       sections[seen_linkorder++] = p;
11054     }
11055   /* Sort the input sections in the order of their linked section.  */
11056   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11057          compare_link_order);
11058
11059   /* Change the offsets of the sections.  */
11060   offset = 0;
11061   for (n = 0; n < seen_linkorder; n++)
11062     {
11063       s = sections[n]->u.indirect.section;
11064       offset &= ~(bfd_vma) 0 << s->alignment_power;
11065       s->output_offset = offset / bfd_octets_per_byte (abfd);
11066       sections[n]->offset = offset;
11067       offset += sections[n]->size;
11068     }
11069
11070   free (sections);
11071   return TRUE;
11072 }
11073
11074 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11075    Returns TRUE upon success, FALSE otherwise.  */
11076
11077 static bfd_boolean
11078 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11079 {
11080   bfd_boolean ret = FALSE;
11081   bfd *implib_bfd;
11082   const struct elf_backend_data *bed;
11083   flagword flags;
11084   enum bfd_architecture arch;
11085   unsigned int mach;
11086   asymbol **sympp = NULL;
11087   long symsize;
11088   long symcount;
11089   long src_count;
11090   elf_symbol_type *osymbuf;
11091
11092   implib_bfd = info->out_implib_bfd;
11093   bed = get_elf_backend_data (abfd);
11094
11095   if (!bfd_set_format (implib_bfd, bfd_object))
11096     return FALSE;
11097
11098   flags = bfd_get_file_flags (abfd);
11099   flags &= ~HAS_RELOC;
11100   if (!bfd_set_start_address (implib_bfd, 0)
11101       || !bfd_set_file_flags (implib_bfd, flags))
11102     return FALSE;
11103
11104   /* Copy architecture of output file to import library file.  */
11105   arch = bfd_get_arch (abfd);
11106   mach = bfd_get_mach (abfd);
11107   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11108       && (abfd->target_defaulted
11109           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11110     return FALSE;
11111
11112   /* Get symbol table size.  */
11113   symsize = bfd_get_symtab_upper_bound (abfd);
11114   if (symsize < 0)
11115     return FALSE;
11116
11117   /* Read in the symbol table.  */
11118   sympp = (asymbol **) xmalloc (symsize);
11119   symcount = bfd_canonicalize_symtab (abfd, sympp);
11120   if (symcount < 0)
11121     goto free_sym_buf;
11122
11123   /* Allow the BFD backend to copy any private header data it
11124      understands from the output BFD to the import library BFD.  */
11125   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11126     goto free_sym_buf;
11127
11128   /* Filter symbols to appear in the import library.  */
11129   if (bed->elf_backend_filter_implib_symbols)
11130     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11131                                                        symcount);
11132   else
11133     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11134   if (symcount == 0)
11135     {
11136       bfd_set_error (bfd_error_no_symbols);
11137       _bfd_error_handler (_("%B: no symbol found for import library"),
11138                           implib_bfd);
11139       goto free_sym_buf;
11140     }
11141
11142
11143   /* Make symbols absolute.  */
11144   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11145                                             sizeof (*osymbuf));
11146   for (src_count = 0; src_count < symcount; src_count++)
11147     {
11148       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11149               sizeof (*osymbuf));
11150       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11151       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11152       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11153       osymbuf[src_count].internal_elf_sym.st_value =
11154         osymbuf[src_count].symbol.value;
11155       sympp[src_count] = &osymbuf[src_count].symbol;
11156     }
11157
11158   bfd_set_symtab (implib_bfd, sympp, symcount);
11159
11160   /* Allow the BFD backend to copy any private data it understands
11161      from the output BFD to the import library BFD.  This is done last
11162      to permit the routine to look at the filtered symbol table.  */
11163   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11164     goto free_sym_buf;
11165
11166   if (!bfd_close (implib_bfd))
11167     goto free_sym_buf;
11168
11169   ret = TRUE;
11170
11171 free_sym_buf:
11172   free (sympp);
11173   return ret;
11174 }
11175
11176 static void
11177 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11178 {
11179   asection *o;
11180
11181   if (flinfo->symstrtab != NULL)
11182     _bfd_elf_strtab_free (flinfo->symstrtab);
11183   if (flinfo->contents != NULL)
11184     free (flinfo->contents);
11185   if (flinfo->external_relocs != NULL)
11186     free (flinfo->external_relocs);
11187   if (flinfo->internal_relocs != NULL)
11188     free (flinfo->internal_relocs);
11189   if (flinfo->external_syms != NULL)
11190     free (flinfo->external_syms);
11191   if (flinfo->locsym_shndx != NULL)
11192     free (flinfo->locsym_shndx);
11193   if (flinfo->internal_syms != NULL)
11194     free (flinfo->internal_syms);
11195   if (flinfo->indices != NULL)
11196     free (flinfo->indices);
11197   if (flinfo->sections != NULL)
11198     free (flinfo->sections);
11199   if (flinfo->symshndxbuf != NULL)
11200     free (flinfo->symshndxbuf);
11201   for (o = obfd->sections; o != NULL; o = o->next)
11202     {
11203       struct bfd_elf_section_data *esdo = elf_section_data (o);
11204       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11205         free (esdo->rel.hashes);
11206       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11207         free (esdo->rela.hashes);
11208     }
11209 }
11210
11211 /* Do the final step of an ELF link.  */
11212
11213 bfd_boolean
11214 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11215 {
11216   bfd_boolean dynamic;
11217   bfd_boolean emit_relocs;
11218   bfd *dynobj;
11219   struct elf_final_link_info flinfo;
11220   asection *o;
11221   struct bfd_link_order *p;
11222   bfd *sub;
11223   bfd_size_type max_contents_size;
11224   bfd_size_type max_external_reloc_size;
11225   bfd_size_type max_internal_reloc_count;
11226   bfd_size_type max_sym_count;
11227   bfd_size_type max_sym_shndx_count;
11228   Elf_Internal_Sym elfsym;
11229   unsigned int i;
11230   Elf_Internal_Shdr *symtab_hdr;
11231   Elf_Internal_Shdr *symtab_shndx_hdr;
11232   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11233   struct elf_outext_info eoinfo;
11234   bfd_boolean merged;
11235   size_t relativecount = 0;
11236   asection *reldyn = 0;
11237   bfd_size_type amt;
11238   asection *attr_section = NULL;
11239   bfd_vma attr_size = 0;
11240   const char *std_attrs_section;
11241
11242   if (! is_elf_hash_table (info->hash))
11243     return FALSE;
11244
11245   if (bfd_link_pic (info))
11246     abfd->flags |= DYNAMIC;
11247
11248   dynamic = elf_hash_table (info)->dynamic_sections_created;
11249   dynobj = elf_hash_table (info)->dynobj;
11250
11251   emit_relocs = (bfd_link_relocatable (info)
11252                  || info->emitrelocations);
11253
11254   flinfo.info = info;
11255   flinfo.output_bfd = abfd;
11256   flinfo.symstrtab = _bfd_elf_strtab_init ();
11257   if (flinfo.symstrtab == NULL)
11258     return FALSE;
11259
11260   if (! dynamic)
11261     {
11262       flinfo.hash_sec = NULL;
11263       flinfo.symver_sec = NULL;
11264     }
11265   else
11266     {
11267       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11268       /* Note that dynsym_sec can be NULL (on VMS).  */
11269       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11270       /* Note that it is OK if symver_sec is NULL.  */
11271     }
11272
11273   flinfo.contents = NULL;
11274   flinfo.external_relocs = NULL;
11275   flinfo.internal_relocs = NULL;
11276   flinfo.external_syms = NULL;
11277   flinfo.locsym_shndx = NULL;
11278   flinfo.internal_syms = NULL;
11279   flinfo.indices = NULL;
11280   flinfo.sections = NULL;
11281   flinfo.symshndxbuf = NULL;
11282   flinfo.filesym_count = 0;
11283
11284   /* The object attributes have been merged.  Remove the input
11285      sections from the link, and set the contents of the output
11286      secton.  */
11287   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11288   for (o = abfd->sections; o != NULL; o = o->next)
11289     {
11290       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11291           || strcmp (o->name, ".gnu.attributes") == 0)
11292         {
11293           for (p = o->map_head.link_order; p != NULL; p = p->next)
11294             {
11295               asection *input_section;
11296
11297               if (p->type != bfd_indirect_link_order)
11298                 continue;
11299               input_section = p->u.indirect.section;
11300               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11301                  elf_link_input_bfd ignores this section.  */
11302               input_section->flags &= ~SEC_HAS_CONTENTS;
11303             }
11304
11305           attr_size = bfd_elf_obj_attr_size (abfd);
11306           if (attr_size)
11307             {
11308               bfd_set_section_size (abfd, o, attr_size);
11309               attr_section = o;
11310               /* Skip this section later on.  */
11311               o->map_head.link_order = NULL;
11312             }
11313           else
11314             o->flags |= SEC_EXCLUDE;
11315         }
11316     }
11317
11318   /* Count up the number of relocations we will output for each output
11319      section, so that we know the sizes of the reloc sections.  We
11320      also figure out some maximum sizes.  */
11321   max_contents_size = 0;
11322   max_external_reloc_size = 0;
11323   max_internal_reloc_count = 0;
11324   max_sym_count = 0;
11325   max_sym_shndx_count = 0;
11326   merged = FALSE;
11327   for (o = abfd->sections; o != NULL; o = o->next)
11328     {
11329       struct bfd_elf_section_data *esdo = elf_section_data (o);
11330       o->reloc_count = 0;
11331
11332       for (p = o->map_head.link_order; p != NULL; p = p->next)
11333         {
11334           unsigned int reloc_count = 0;
11335           unsigned int additional_reloc_count = 0;
11336           struct bfd_elf_section_data *esdi = NULL;
11337
11338           if (p->type == bfd_section_reloc_link_order
11339               || p->type == bfd_symbol_reloc_link_order)
11340             reloc_count = 1;
11341           else if (p->type == bfd_indirect_link_order)
11342             {
11343               asection *sec;
11344
11345               sec = p->u.indirect.section;
11346               esdi = elf_section_data (sec);
11347
11348               /* Mark all sections which are to be included in the
11349                  link.  This will normally be every section.  We need
11350                  to do this so that we can identify any sections which
11351                  the linker has decided to not include.  */
11352               sec->linker_mark = TRUE;
11353
11354               if (sec->flags & SEC_MERGE)
11355                 merged = TRUE;
11356
11357               if (esdo->this_hdr.sh_type == SHT_REL
11358                   || esdo->this_hdr.sh_type == SHT_RELA)
11359                 /* Some backends use reloc_count in relocation sections
11360                    to count particular types of relocs.  Of course,
11361                    reloc sections themselves can't have relocations.  */
11362                 reloc_count = 0;
11363               else if (emit_relocs)
11364                 {
11365                   reloc_count = sec->reloc_count;
11366                   if (bed->elf_backend_count_additional_relocs)
11367                     {
11368                       int c;
11369                       c = (*bed->elf_backend_count_additional_relocs) (sec);
11370                       additional_reloc_count += c;
11371                     }
11372                 }
11373               else if (bed->elf_backend_count_relocs)
11374                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11375
11376               if (sec->rawsize > max_contents_size)
11377                 max_contents_size = sec->rawsize;
11378               if (sec->size > max_contents_size)
11379                 max_contents_size = sec->size;
11380
11381               /* We are interested in just local symbols, not all
11382                  symbols.  */
11383               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11384                   && (sec->owner->flags & DYNAMIC) == 0)
11385                 {
11386                   size_t sym_count;
11387
11388                   if (elf_bad_symtab (sec->owner))
11389                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11390                                  / bed->s->sizeof_sym);
11391                   else
11392                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11393
11394                   if (sym_count > max_sym_count)
11395                     max_sym_count = sym_count;
11396
11397                   if (sym_count > max_sym_shndx_count
11398                       && elf_symtab_shndx_list (sec->owner) != NULL)
11399                     max_sym_shndx_count = sym_count;
11400
11401                   if ((sec->flags & SEC_RELOC) != 0)
11402                     {
11403                       size_t ext_size = 0;
11404
11405                       if (esdi->rel.hdr != NULL)
11406                         ext_size = esdi->rel.hdr->sh_size;
11407                       if (esdi->rela.hdr != NULL)
11408                         ext_size += esdi->rela.hdr->sh_size;
11409
11410                       if (ext_size > max_external_reloc_size)
11411                         max_external_reloc_size = ext_size;
11412                       if (sec->reloc_count > max_internal_reloc_count)
11413                         max_internal_reloc_count = sec->reloc_count;
11414                     }
11415                 }
11416             }
11417
11418           if (reloc_count == 0)
11419             continue;
11420
11421           reloc_count += additional_reloc_count;
11422           o->reloc_count += reloc_count;
11423
11424           if (p->type == bfd_indirect_link_order && emit_relocs)
11425             {
11426               if (esdi->rel.hdr)
11427                 {
11428                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11429                   esdo->rel.count += additional_reloc_count;
11430                 }
11431               if (esdi->rela.hdr)
11432                 {
11433                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11434                   esdo->rela.count += additional_reloc_count;
11435                 }
11436             }
11437           else
11438             {
11439               if (o->use_rela_p)
11440                 esdo->rela.count += reloc_count;
11441               else
11442                 esdo->rel.count += reloc_count;
11443             }
11444         }
11445
11446       if (o->reloc_count > 0)
11447         o->flags |= SEC_RELOC;
11448       else
11449         {
11450           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11451              set it (this is probably a bug) and if it is set
11452              assign_section_numbers will create a reloc section.  */
11453           o->flags &=~ SEC_RELOC;
11454         }
11455
11456       /* If the SEC_ALLOC flag is not set, force the section VMA to
11457          zero.  This is done in elf_fake_sections as well, but forcing
11458          the VMA to 0 here will ensure that relocs against these
11459          sections are handled correctly.  */
11460       if ((o->flags & SEC_ALLOC) == 0
11461           && ! o->user_set_vma)
11462         o->vma = 0;
11463     }
11464
11465   if (! bfd_link_relocatable (info) && merged)
11466     elf_link_hash_traverse (elf_hash_table (info),
11467                             _bfd_elf_link_sec_merge_syms, abfd);
11468
11469   /* Figure out the file positions for everything but the symbol table
11470      and the relocs.  We set symcount to force assign_section_numbers
11471      to create a symbol table.  */
11472   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11473   BFD_ASSERT (! abfd->output_has_begun);
11474   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11475     goto error_return;
11476
11477   /* Set sizes, and assign file positions for reloc sections.  */
11478   for (o = abfd->sections; o != NULL; o = o->next)
11479     {
11480       struct bfd_elf_section_data *esdo = elf_section_data (o);
11481       if ((o->flags & SEC_RELOC) != 0)
11482         {
11483           if (esdo->rel.hdr
11484               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11485             goto error_return;
11486
11487           if (esdo->rela.hdr
11488               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11489             goto error_return;
11490         }
11491
11492       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11493          to count upwards while actually outputting the relocations.  */
11494       esdo->rel.count = 0;
11495       esdo->rela.count = 0;
11496
11497       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11498         {
11499           /* Cache the section contents so that they can be compressed
11500              later.  Use bfd_malloc since it will be freed by
11501              bfd_compress_section_contents.  */
11502           unsigned char *contents = esdo->this_hdr.contents;
11503           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11504             abort ();
11505           contents
11506             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11507           if (contents == NULL)
11508             goto error_return;
11509           esdo->this_hdr.contents = contents;
11510         }
11511     }
11512
11513   /* We have now assigned file positions for all the sections except
11514      .symtab, .strtab, and non-loaded reloc sections.  We start the
11515      .symtab section at the current file position, and write directly
11516      to it.  We build the .strtab section in memory.  */
11517   bfd_get_symcount (abfd) = 0;
11518   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11519   /* sh_name is set in prep_headers.  */
11520   symtab_hdr->sh_type = SHT_SYMTAB;
11521   /* sh_flags, sh_addr and sh_size all start off zero.  */
11522   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11523   /* sh_link is set in assign_section_numbers.  */
11524   /* sh_info is set below.  */
11525   /* sh_offset is set just below.  */
11526   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11527
11528   if (max_sym_count < 20)
11529     max_sym_count = 20;
11530   elf_hash_table (info)->strtabsize = max_sym_count;
11531   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11532   elf_hash_table (info)->strtab
11533     = (struct elf_sym_strtab *) bfd_malloc (amt);
11534   if (elf_hash_table (info)->strtab == NULL)
11535     goto error_return;
11536   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11537   flinfo.symshndxbuf
11538     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11539        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11540
11541   if (info->strip != strip_all || emit_relocs)
11542     {
11543       file_ptr off = elf_next_file_pos (abfd);
11544
11545       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11546
11547       /* Note that at this point elf_next_file_pos (abfd) is
11548          incorrect.  We do not yet know the size of the .symtab section.
11549          We correct next_file_pos below, after we do know the size.  */
11550
11551       /* Start writing out the symbol table.  The first symbol is always a
11552          dummy symbol.  */
11553       elfsym.st_value = 0;
11554       elfsym.st_size = 0;
11555       elfsym.st_info = 0;
11556       elfsym.st_other = 0;
11557       elfsym.st_shndx = SHN_UNDEF;
11558       elfsym.st_target_internal = 0;
11559       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11560                                      bfd_und_section_ptr, NULL) != 1)
11561         goto error_return;
11562
11563       /* Output a symbol for each section.  We output these even if we are
11564          discarding local symbols, since they are used for relocs.  These
11565          symbols have no names.  We store the index of each one in the
11566          index field of the section, so that we can find it again when
11567          outputting relocs.  */
11568
11569       elfsym.st_size = 0;
11570       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11571       elfsym.st_other = 0;
11572       elfsym.st_value = 0;
11573       elfsym.st_target_internal = 0;
11574       for (i = 1; i < elf_numsections (abfd); i++)
11575         {
11576           o = bfd_section_from_elf_index (abfd, i);
11577           if (o != NULL)
11578             {
11579               o->target_index = bfd_get_symcount (abfd);
11580               elfsym.st_shndx = i;
11581               if (!bfd_link_relocatable (info))
11582                 elfsym.st_value = o->vma;
11583               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11584                                              NULL) != 1)
11585                 goto error_return;
11586             }
11587         }
11588     }
11589
11590   /* Allocate some memory to hold information read in from the input
11591      files.  */
11592   if (max_contents_size != 0)
11593     {
11594       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11595       if (flinfo.contents == NULL)
11596         goto error_return;
11597     }
11598
11599   if (max_external_reloc_size != 0)
11600     {
11601       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11602       if (flinfo.external_relocs == NULL)
11603         goto error_return;
11604     }
11605
11606   if (max_internal_reloc_count != 0)
11607     {
11608       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11609       amt *= sizeof (Elf_Internal_Rela);
11610       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11611       if (flinfo.internal_relocs == NULL)
11612         goto error_return;
11613     }
11614
11615   if (max_sym_count != 0)
11616     {
11617       amt = max_sym_count * bed->s->sizeof_sym;
11618       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11619       if (flinfo.external_syms == NULL)
11620         goto error_return;
11621
11622       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11623       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11624       if (flinfo.internal_syms == NULL)
11625         goto error_return;
11626
11627       amt = max_sym_count * sizeof (long);
11628       flinfo.indices = (long int *) bfd_malloc (amt);
11629       if (flinfo.indices == NULL)
11630         goto error_return;
11631
11632       amt = max_sym_count * sizeof (asection *);
11633       flinfo.sections = (asection **) bfd_malloc (amt);
11634       if (flinfo.sections == NULL)
11635         goto error_return;
11636     }
11637
11638   if (max_sym_shndx_count != 0)
11639     {
11640       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11641       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11642       if (flinfo.locsym_shndx == NULL)
11643         goto error_return;
11644     }
11645
11646   if (elf_hash_table (info)->tls_sec)
11647     {
11648       bfd_vma base, end = 0;
11649       asection *sec;
11650
11651       for (sec = elf_hash_table (info)->tls_sec;
11652            sec && (sec->flags & SEC_THREAD_LOCAL);
11653            sec = sec->next)
11654         {
11655           bfd_size_type size = sec->size;
11656
11657           if (size == 0
11658               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11659             {
11660               struct bfd_link_order *ord = sec->map_tail.link_order;
11661
11662               if (ord != NULL)
11663                 size = ord->offset + ord->size;
11664             }
11665           end = sec->vma + size;
11666         }
11667       base = elf_hash_table (info)->tls_sec->vma;
11668       /* Only align end of TLS section if static TLS doesn't have special
11669          alignment requirements.  */
11670       if (bed->static_tls_alignment == 1)
11671         end = align_power (end,
11672                            elf_hash_table (info)->tls_sec->alignment_power);
11673       elf_hash_table (info)->tls_size = end - base;
11674     }
11675
11676   /* Reorder SHF_LINK_ORDER sections.  */
11677   for (o = abfd->sections; o != NULL; o = o->next)
11678     {
11679       if (!elf_fixup_link_order (abfd, o))
11680         return FALSE;
11681     }
11682
11683   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11684     return FALSE;
11685
11686   /* Since ELF permits relocations to be against local symbols, we
11687      must have the local symbols available when we do the relocations.
11688      Since we would rather only read the local symbols once, and we
11689      would rather not keep them in memory, we handle all the
11690      relocations for a single input file at the same time.
11691
11692      Unfortunately, there is no way to know the total number of local
11693      symbols until we have seen all of them, and the local symbol
11694      indices precede the global symbol indices.  This means that when
11695      we are generating relocatable output, and we see a reloc against
11696      a global symbol, we can not know the symbol index until we have
11697      finished examining all the local symbols to see which ones we are
11698      going to output.  To deal with this, we keep the relocations in
11699      memory, and don't output them until the end of the link.  This is
11700      an unfortunate waste of memory, but I don't see a good way around
11701      it.  Fortunately, it only happens when performing a relocatable
11702      link, which is not the common case.  FIXME: If keep_memory is set
11703      we could write the relocs out and then read them again; I don't
11704      know how bad the memory loss will be.  */
11705
11706   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11707     sub->output_has_begun = FALSE;
11708   for (o = abfd->sections; o != NULL; o = o->next)
11709     {
11710       for (p = o->map_head.link_order; p != NULL; p = p->next)
11711         {
11712           if (p->type == bfd_indirect_link_order
11713               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11714                   == bfd_target_elf_flavour)
11715               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11716             {
11717               if (! sub->output_has_begun)
11718                 {
11719                   if (! elf_link_input_bfd (&flinfo, sub))
11720                     goto error_return;
11721                   sub->output_has_begun = TRUE;
11722                 }
11723             }
11724           else if (p->type == bfd_section_reloc_link_order
11725                    || p->type == bfd_symbol_reloc_link_order)
11726             {
11727               if (! elf_reloc_link_order (abfd, info, o, p))
11728                 goto error_return;
11729             }
11730           else
11731             {
11732               if (! _bfd_default_link_order (abfd, info, o, p))
11733                 {
11734                   if (p->type == bfd_indirect_link_order
11735                       && (bfd_get_flavour (sub)
11736                           == bfd_target_elf_flavour)
11737                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11738                           != bed->s->elfclass))
11739                     {
11740                       const char *iclass, *oclass;
11741
11742                       switch (bed->s->elfclass)
11743                         {
11744                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11745                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11746                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11747                         default: abort ();
11748                         }
11749
11750                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11751                         {
11752                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11753                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11754                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11755                         default: abort ();
11756                         }
11757
11758                       bfd_set_error (bfd_error_wrong_format);
11759                       _bfd_error_handler
11760                         /* xgettext:c-format */
11761                         (_("%B: file class %s incompatible with %s"),
11762                          sub, iclass, oclass);
11763                     }
11764
11765                   goto error_return;
11766                 }
11767             }
11768         }
11769     }
11770
11771   /* Free symbol buffer if needed.  */
11772   if (!info->reduce_memory_overheads)
11773     {
11774       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11775         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11776             && elf_tdata (sub)->symbuf)
11777           {
11778             free (elf_tdata (sub)->symbuf);
11779             elf_tdata (sub)->symbuf = NULL;
11780           }
11781     }
11782
11783   /* Output any global symbols that got converted to local in a
11784      version script or due to symbol visibility.  We do this in a
11785      separate step since ELF requires all local symbols to appear
11786      prior to any global symbols.  FIXME: We should only do this if
11787      some global symbols were, in fact, converted to become local.
11788      FIXME: Will this work correctly with the Irix 5 linker?  */
11789   eoinfo.failed = FALSE;
11790   eoinfo.flinfo = &flinfo;
11791   eoinfo.localsyms = TRUE;
11792   eoinfo.file_sym_done = FALSE;
11793   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11794   if (eoinfo.failed)
11795     return FALSE;
11796
11797   /* If backend needs to output some local symbols not present in the hash
11798      table, do it now.  */
11799   if (bed->elf_backend_output_arch_local_syms
11800       && (info->strip != strip_all || emit_relocs))
11801     {
11802       typedef int (*out_sym_func)
11803         (void *, const char *, Elf_Internal_Sym *, asection *,
11804          struct elf_link_hash_entry *);
11805
11806       if (! ((*bed->elf_backend_output_arch_local_syms)
11807              (abfd, info, &flinfo,
11808               (out_sym_func) elf_link_output_symstrtab)))
11809         return FALSE;
11810     }
11811
11812   /* That wrote out all the local symbols.  Finish up the symbol table
11813      with the global symbols. Even if we want to strip everything we
11814      can, we still need to deal with those global symbols that got
11815      converted to local in a version script.  */
11816
11817   /* The sh_info field records the index of the first non local symbol.  */
11818   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11819
11820   if (dynamic
11821       && elf_hash_table (info)->dynsym != NULL
11822       && (elf_hash_table (info)->dynsym->output_section
11823           != bfd_abs_section_ptr))
11824     {
11825       Elf_Internal_Sym sym;
11826       bfd_byte *dynsym = elf_hash_table (info)->dynsym->contents;
11827
11828       o = elf_hash_table (info)->dynsym->output_section;
11829       elf_section_data (o)->this_hdr.sh_info
11830         = elf_hash_table (info)->local_dynsymcount + 1;
11831
11832       /* Write out the section symbols for the output sections.  */
11833       if (bfd_link_pic (info)
11834           || elf_hash_table (info)->is_relocatable_executable)
11835         {
11836           asection *s;
11837
11838           sym.st_size = 0;
11839           sym.st_name = 0;
11840           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11841           sym.st_other = 0;
11842           sym.st_target_internal = 0;
11843
11844           for (s = abfd->sections; s != NULL; s = s->next)
11845             {
11846               int indx;
11847               bfd_byte *dest;
11848               long dynindx;
11849
11850               dynindx = elf_section_data (s)->dynindx;
11851               if (dynindx <= 0)
11852                 continue;
11853               indx = elf_section_data (s)->this_idx;
11854               BFD_ASSERT (indx > 0);
11855               sym.st_shndx = indx;
11856               if (! check_dynsym (abfd, &sym))
11857                 return FALSE;
11858               sym.st_value = s->vma;
11859               dest = dynsym + dynindx * bed->s->sizeof_sym;
11860               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11861             }
11862         }
11863
11864       /* Write out the local dynsyms.  */
11865       if (elf_hash_table (info)->dynlocal)
11866         {
11867           struct elf_link_local_dynamic_entry *e;
11868           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11869             {
11870               asection *s;
11871               bfd_byte *dest;
11872
11873               /* Copy the internal symbol and turn off visibility.
11874                  Note that we saved a word of storage and overwrote
11875                  the original st_name with the dynstr_index.  */
11876               sym = e->isym;
11877               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11878
11879               s = bfd_section_from_elf_index (e->input_bfd,
11880                                               e->isym.st_shndx);
11881               if (s != NULL)
11882                 {
11883                   sym.st_shndx =
11884                     elf_section_data (s->output_section)->this_idx;
11885                   if (! check_dynsym (abfd, &sym))
11886                     return FALSE;
11887                   sym.st_value = (s->output_section->vma
11888                                   + s->output_offset
11889                                   + e->isym.st_value);
11890                 }
11891
11892               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11893               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11894             }
11895         }
11896     }
11897
11898   /* We get the global symbols from the hash table.  */
11899   eoinfo.failed = FALSE;
11900   eoinfo.localsyms = FALSE;
11901   eoinfo.flinfo = &flinfo;
11902   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11903   if (eoinfo.failed)
11904     return FALSE;
11905
11906   /* If backend needs to output some symbols not present in the hash
11907      table, do it now.  */
11908   if (bed->elf_backend_output_arch_syms
11909       && (info->strip != strip_all || emit_relocs))
11910     {
11911       typedef int (*out_sym_func)
11912         (void *, const char *, Elf_Internal_Sym *, asection *,
11913          struct elf_link_hash_entry *);
11914
11915       if (! ((*bed->elf_backend_output_arch_syms)
11916              (abfd, info, &flinfo,
11917               (out_sym_func) elf_link_output_symstrtab)))
11918         return FALSE;
11919     }
11920
11921   /* Finalize the .strtab section.  */
11922   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11923
11924   /* Swap out the .strtab section. */
11925   if (!elf_link_swap_symbols_out (&flinfo))
11926     return FALSE;
11927
11928   /* Now we know the size of the symtab section.  */
11929   if (bfd_get_symcount (abfd) > 0)
11930     {
11931       /* Finish up and write out the symbol string table (.strtab)
11932          section.  */
11933       Elf_Internal_Shdr *symstrtab_hdr;
11934       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11935
11936       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
11937       if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
11938         {
11939           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11940           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11941           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11942           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11943           symtab_shndx_hdr->sh_size = amt;
11944
11945           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11946                                                            off, TRUE);
11947
11948           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11949               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11950             return FALSE;
11951         }
11952
11953       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11954       /* sh_name was set in prep_headers.  */
11955       symstrtab_hdr->sh_type = SHT_STRTAB;
11956       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
11957       symstrtab_hdr->sh_addr = 0;
11958       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11959       symstrtab_hdr->sh_entsize = 0;
11960       symstrtab_hdr->sh_link = 0;
11961       symstrtab_hdr->sh_info = 0;
11962       /* sh_offset is set just below.  */
11963       symstrtab_hdr->sh_addralign = 1;
11964
11965       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11966                                                        off, TRUE);
11967       elf_next_file_pos (abfd) = off;
11968
11969       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11970           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11971         return FALSE;
11972     }
11973
11974   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
11975     {
11976       _bfd_error_handler (_("%B: failed to generate import library"),
11977                           info->out_implib_bfd);
11978       return FALSE;
11979     }
11980
11981   /* Adjust the relocs to have the correct symbol indices.  */
11982   for (o = abfd->sections; o != NULL; o = o->next)
11983     {
11984       struct bfd_elf_section_data *esdo = elf_section_data (o);
11985       bfd_boolean sort;
11986       if ((o->flags & SEC_RELOC) == 0)
11987         continue;
11988
11989       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11990       if (esdo->rel.hdr != NULL
11991           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort))
11992         return FALSE;
11993       if (esdo->rela.hdr != NULL
11994           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort))
11995         return FALSE;
11996
11997       /* Set the reloc_count field to 0 to prevent write_relocs from
11998          trying to swap the relocs out itself.  */
11999       o->reloc_count = 0;
12000     }
12001
12002   if (dynamic && info->combreloc && dynobj != NULL)
12003     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12004
12005   /* If we are linking against a dynamic object, or generating a
12006      shared library, finish up the dynamic linking information.  */
12007   if (dynamic)
12008     {
12009       bfd_byte *dyncon, *dynconend;
12010
12011       /* Fix up .dynamic entries.  */
12012       o = bfd_get_linker_section (dynobj, ".dynamic");
12013       BFD_ASSERT (o != NULL);
12014
12015       dyncon = o->contents;
12016       dynconend = o->contents + o->size;
12017       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12018         {
12019           Elf_Internal_Dyn dyn;
12020           const char *name;
12021           unsigned int type;
12022
12023           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12024
12025           switch (dyn.d_tag)
12026             {
12027             default:
12028               continue;
12029             case DT_NULL:
12030               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12031                 {
12032                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12033                     {
12034                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12035                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12036                     default: continue;
12037                     }
12038                   dyn.d_un.d_val = relativecount;
12039                   relativecount = 0;
12040                   break;
12041                 }
12042               continue;
12043
12044             case DT_INIT:
12045               name = info->init_function;
12046               goto get_sym;
12047             case DT_FINI:
12048               name = info->fini_function;
12049             get_sym:
12050               {
12051                 struct elf_link_hash_entry *h;
12052
12053                 h = elf_link_hash_lookup (elf_hash_table (info), name,
12054                                           FALSE, FALSE, TRUE);
12055                 if (h != NULL
12056                     && (h->root.type == bfd_link_hash_defined
12057                         || h->root.type == bfd_link_hash_defweak))
12058                   {
12059                     dyn.d_un.d_ptr = h->root.u.def.value;
12060                     o = h->root.u.def.section;
12061                     if (o->output_section != NULL)
12062                       dyn.d_un.d_ptr += (o->output_section->vma
12063                                          + o->output_offset);
12064                     else
12065                       {
12066                         /* The symbol is imported from another shared
12067                            library and does not apply to this one.  */
12068                         dyn.d_un.d_ptr = 0;
12069                       }
12070                     break;
12071                   }
12072               }
12073               continue;
12074
12075             case DT_PREINIT_ARRAYSZ:
12076               name = ".preinit_array";
12077               goto get_out_size;
12078             case DT_INIT_ARRAYSZ:
12079               name = ".init_array";
12080               goto get_out_size;
12081             case DT_FINI_ARRAYSZ:
12082               name = ".fini_array";
12083             get_out_size:
12084               o = bfd_get_section_by_name (abfd, name);
12085               if (o == NULL)
12086                 {
12087                   _bfd_error_handler
12088                     (_("could not find section %s"), name);
12089                   goto error_return;
12090                 }
12091               if (o->size == 0)
12092                 _bfd_error_handler
12093                   (_("warning: %s section has zero size"), name);
12094               dyn.d_un.d_val = o->size;
12095               break;
12096
12097             case DT_PREINIT_ARRAY:
12098               name = ".preinit_array";
12099               goto get_out_vma;
12100             case DT_INIT_ARRAY:
12101               name = ".init_array";
12102               goto get_out_vma;
12103             case DT_FINI_ARRAY:
12104               name = ".fini_array";
12105             get_out_vma:
12106               o = bfd_get_section_by_name (abfd, name);
12107               goto do_vma;
12108
12109             case DT_HASH:
12110               name = ".hash";
12111               goto get_vma;
12112             case DT_GNU_HASH:
12113               name = ".gnu.hash";
12114               goto get_vma;
12115             case DT_STRTAB:
12116               name = ".dynstr";
12117               goto get_vma;
12118             case DT_SYMTAB:
12119               name = ".dynsym";
12120               goto get_vma;
12121             case DT_VERDEF:
12122               name = ".gnu.version_d";
12123               goto get_vma;
12124             case DT_VERNEED:
12125               name = ".gnu.version_r";
12126               goto get_vma;
12127             case DT_VERSYM:
12128               name = ".gnu.version";
12129             get_vma:
12130               o = bfd_get_linker_section (dynobj, name);
12131             do_vma:
12132               if (o == NULL)
12133                 {
12134                   _bfd_error_handler
12135                     (_("could not find section %s"), name);
12136                   goto error_return;
12137                 }
12138               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12139                 {
12140                   _bfd_error_handler
12141                     (_("warning: section '%s' is being made into a note"), name);
12142                   bfd_set_error (bfd_error_nonrepresentable_section);
12143                   goto error_return;
12144                 }
12145               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12146               break;
12147
12148             case DT_REL:
12149             case DT_RELA:
12150             case DT_RELSZ:
12151             case DT_RELASZ:
12152               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12153                 type = SHT_REL;
12154               else
12155                 type = SHT_RELA;
12156               dyn.d_un.d_val = 0;
12157               dyn.d_un.d_ptr = 0;
12158               for (i = 1; i < elf_numsections (abfd); i++)
12159                 {
12160                   Elf_Internal_Shdr *hdr;
12161
12162                   hdr = elf_elfsections (abfd)[i];
12163                   if (hdr->sh_type == type
12164                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12165                     {
12166                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12167                         dyn.d_un.d_val += hdr->sh_size;
12168                       else
12169                         {
12170                           if (dyn.d_un.d_ptr == 0
12171                               || hdr->sh_addr < dyn.d_un.d_ptr)
12172                             dyn.d_un.d_ptr = hdr->sh_addr;
12173                         }
12174                     }
12175                 }
12176               break;
12177             }
12178           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12179         }
12180     }
12181
12182   /* If we have created any dynamic sections, then output them.  */
12183   if (dynobj != NULL)
12184     {
12185       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12186         goto error_return;
12187
12188       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12189       if (((info->warn_shared_textrel && bfd_link_pic (info))
12190            || info->error_textrel)
12191           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12192         {
12193           bfd_byte *dyncon, *dynconend;
12194
12195           dyncon = o->contents;
12196           dynconend = o->contents + o->size;
12197           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12198             {
12199               Elf_Internal_Dyn dyn;
12200
12201               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12202
12203               if (dyn.d_tag == DT_TEXTREL)
12204                 {
12205                   if (info->error_textrel)
12206                     info->callbacks->einfo
12207                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12208                   else
12209                     info->callbacks->einfo
12210                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12211                   break;
12212                 }
12213             }
12214         }
12215
12216       for (o = dynobj->sections; o != NULL; o = o->next)
12217         {
12218           if ((o->flags & SEC_HAS_CONTENTS) == 0
12219               || o->size == 0
12220               || o->output_section == bfd_abs_section_ptr)
12221             continue;
12222           if ((o->flags & SEC_LINKER_CREATED) == 0)
12223             {
12224               /* At this point, we are only interested in sections
12225                  created by _bfd_elf_link_create_dynamic_sections.  */
12226               continue;
12227             }
12228           if (elf_hash_table (info)->stab_info.stabstr == o)
12229             continue;
12230           if (elf_hash_table (info)->eh_info.hdr_sec == o)
12231             continue;
12232           if (strcmp (o->name, ".dynstr") != 0)
12233             {
12234               if (! bfd_set_section_contents (abfd, o->output_section,
12235                                               o->contents,
12236                                               (file_ptr) o->output_offset
12237                                               * bfd_octets_per_byte (abfd),
12238                                               o->size))
12239                 goto error_return;
12240             }
12241           else
12242             {
12243               /* The contents of the .dynstr section are actually in a
12244                  stringtab.  */
12245               file_ptr off;
12246
12247               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12248               if (bfd_seek (abfd, off, SEEK_SET) != 0
12249                   || ! _bfd_elf_strtab_emit (abfd,
12250                                              elf_hash_table (info)->dynstr))
12251                 goto error_return;
12252             }
12253         }
12254     }
12255
12256   if (bfd_link_relocatable (info))
12257     {
12258       bfd_boolean failed = FALSE;
12259
12260       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12261       if (failed)
12262         goto error_return;
12263     }
12264
12265   /* If we have optimized stabs strings, output them.  */
12266   if (elf_hash_table (info)->stab_info.stabstr != NULL)
12267     {
12268       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
12269         goto error_return;
12270     }
12271
12272   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12273     goto error_return;
12274
12275   elf_final_link_free (abfd, &flinfo);
12276
12277   elf_linker (abfd) = TRUE;
12278
12279   if (attr_section)
12280     {
12281       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12282       if (contents == NULL)
12283         return FALSE;   /* Bail out and fail.  */
12284       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12285       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12286       free (contents);
12287     }
12288
12289   return TRUE;
12290
12291  error_return:
12292   elf_final_link_free (abfd, &flinfo);
12293   return FALSE;
12294 }
12295 \f
12296 /* Initialize COOKIE for input bfd ABFD.  */
12297
12298 static bfd_boolean
12299 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12300                    struct bfd_link_info *info, bfd *abfd)
12301 {
12302   Elf_Internal_Shdr *symtab_hdr;
12303   const struct elf_backend_data *bed;
12304
12305   bed = get_elf_backend_data (abfd);
12306   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12307
12308   cookie->abfd = abfd;
12309   cookie->sym_hashes = elf_sym_hashes (abfd);
12310   cookie->bad_symtab = elf_bad_symtab (abfd);
12311   if (cookie->bad_symtab)
12312     {
12313       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12314       cookie->extsymoff = 0;
12315     }
12316   else
12317     {
12318       cookie->locsymcount = symtab_hdr->sh_info;
12319       cookie->extsymoff = symtab_hdr->sh_info;
12320     }
12321
12322   if (bed->s->arch_size == 32)
12323     cookie->r_sym_shift = 8;
12324   else
12325     cookie->r_sym_shift = 32;
12326
12327   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12328   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12329     {
12330       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12331                                               cookie->locsymcount, 0,
12332                                               NULL, NULL, NULL);
12333       if (cookie->locsyms == NULL)
12334         {
12335           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12336           return FALSE;
12337         }
12338       if (info->keep_memory)
12339         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12340     }
12341   return TRUE;
12342 }
12343
12344 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12345
12346 static void
12347 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12348 {
12349   Elf_Internal_Shdr *symtab_hdr;
12350
12351   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12352   if (cookie->locsyms != NULL
12353       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12354     free (cookie->locsyms);
12355 }
12356
12357 /* Initialize the relocation information in COOKIE for input section SEC
12358    of input bfd ABFD.  */
12359
12360 static bfd_boolean
12361 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12362                         struct bfd_link_info *info, bfd *abfd,
12363                         asection *sec)
12364 {
12365   const struct elf_backend_data *bed;
12366
12367   if (sec->reloc_count == 0)
12368     {
12369       cookie->rels = NULL;
12370       cookie->relend = NULL;
12371     }
12372   else
12373     {
12374       bed = get_elf_backend_data (abfd);
12375
12376       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12377                                                 info->keep_memory);
12378       if (cookie->rels == NULL)
12379         return FALSE;
12380       cookie->rel = cookie->rels;
12381       cookie->relend = (cookie->rels
12382                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12383     }
12384   cookie->rel = cookie->rels;
12385   return TRUE;
12386 }
12387
12388 /* Free the memory allocated by init_reloc_cookie_rels,
12389    if appropriate.  */
12390
12391 static void
12392 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12393                         asection *sec)
12394 {
12395   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12396     free (cookie->rels);
12397 }
12398
12399 /* Initialize the whole of COOKIE for input section SEC.  */
12400
12401 static bfd_boolean
12402 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12403                                struct bfd_link_info *info,
12404                                asection *sec)
12405 {
12406   if (!init_reloc_cookie (cookie, info, sec->owner))
12407     goto error1;
12408   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12409     goto error2;
12410   return TRUE;
12411
12412  error2:
12413   fini_reloc_cookie (cookie, sec->owner);
12414  error1:
12415   return FALSE;
12416 }
12417
12418 /* Free the memory allocated by init_reloc_cookie_for_section,
12419    if appropriate.  */
12420
12421 static void
12422 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12423                                asection *sec)
12424 {
12425   fini_reloc_cookie_rels (cookie, sec);
12426   fini_reloc_cookie (cookie, sec->owner);
12427 }
12428 \f
12429 /* Garbage collect unused sections.  */
12430
12431 /* Default gc_mark_hook.  */
12432
12433 asection *
12434 _bfd_elf_gc_mark_hook (asection *sec,
12435                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12436                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12437                        struct elf_link_hash_entry *h,
12438                        Elf_Internal_Sym *sym)
12439 {
12440   if (h != NULL)
12441     {
12442       switch (h->root.type)
12443         {
12444         case bfd_link_hash_defined:
12445         case bfd_link_hash_defweak:
12446           return h->root.u.def.section;
12447
12448         case bfd_link_hash_common:
12449           return h->root.u.c.p->section;
12450
12451         default:
12452           break;
12453         }
12454     }
12455   else
12456     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12457
12458   return NULL;
12459 }
12460
12461 /* For undefined __start_<name> and __stop_<name> symbols, return the
12462    first input section matching <name>.  Return NULL otherwise.  */
12463
12464 asection *
12465 _bfd_elf_is_start_stop (const struct bfd_link_info *info,
12466                         struct elf_link_hash_entry *h)
12467 {
12468   asection *s;
12469   const char *sec_name;
12470
12471   if (h->root.type != bfd_link_hash_undefined
12472       && h->root.type != bfd_link_hash_undefweak)
12473     return NULL;
12474
12475   s = h->root.u.undef.section;
12476   if (s != NULL)
12477     {
12478       if (s == (asection *) 0 - 1)
12479         return NULL;
12480       return s;
12481     }
12482
12483   sec_name = NULL;
12484   if (strncmp (h->root.root.string, "__start_", 8) == 0)
12485     sec_name = h->root.root.string + 8;
12486   else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12487     sec_name = h->root.root.string + 7;
12488
12489   if (sec_name != NULL && *sec_name != '\0')
12490     {
12491       bfd *i;
12492
12493       for (i = info->input_bfds; i != NULL; i = i->link.next)
12494         {
12495           s = bfd_get_section_by_name (i, sec_name);
12496           if (s != NULL)
12497             {
12498               h->root.u.undef.section = s;
12499               break;
12500             }
12501         }
12502     }
12503
12504   if (s == NULL)
12505     h->root.u.undef.section = (asection *) 0 - 1;
12506
12507   return s;
12508 }
12509
12510 /* COOKIE->rel describes a relocation against section SEC, which is
12511    a section we've decided to keep.  Return the section that contains
12512    the relocation symbol, or NULL if no section contains it.  */
12513
12514 asection *
12515 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12516                        elf_gc_mark_hook_fn gc_mark_hook,
12517                        struct elf_reloc_cookie *cookie,
12518                        bfd_boolean *start_stop)
12519 {
12520   unsigned long r_symndx;
12521   struct elf_link_hash_entry *h;
12522
12523   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12524   if (r_symndx == STN_UNDEF)
12525     return NULL;
12526
12527   if (r_symndx >= cookie->locsymcount
12528       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12529     {
12530       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12531       if (h == NULL)
12532         {
12533           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12534                                   sec->owner);
12535           return NULL;
12536         }
12537       while (h->root.type == bfd_link_hash_indirect
12538              || h->root.type == bfd_link_hash_warning)
12539         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12540       h->mark = 1;
12541       /* If this symbol is weak and there is a non-weak definition, we
12542          keep the non-weak definition because many backends put
12543          dynamic reloc info on the non-weak definition for code
12544          handling copy relocs.  */
12545       if (h->u.weakdef != NULL)
12546         h->u.weakdef->mark = 1;
12547
12548       if (start_stop != NULL)
12549         {
12550           /* To work around a glibc bug, mark all XXX input sections
12551              when there is an as yet undefined reference to __start_XXX
12552              or __stop_XXX symbols.  The linker will later define such
12553              symbols for orphan input sections that have a name
12554              representable as a C identifier.  */
12555           asection *s = _bfd_elf_is_start_stop (info, h);
12556
12557           if (s != NULL)
12558             {
12559               *start_stop = !s->gc_mark;
12560               return s;
12561             }
12562         }
12563
12564       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12565     }
12566
12567   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12568                           &cookie->locsyms[r_symndx]);
12569 }
12570
12571 /* COOKIE->rel describes a relocation against section SEC, which is
12572    a section we've decided to keep.  Mark the section that contains
12573    the relocation symbol.  */
12574
12575 bfd_boolean
12576 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12577                         asection *sec,
12578                         elf_gc_mark_hook_fn gc_mark_hook,
12579                         struct elf_reloc_cookie *cookie)
12580 {
12581   asection *rsec;
12582   bfd_boolean start_stop = FALSE;
12583
12584   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12585   while (rsec != NULL)
12586     {
12587       if (!rsec->gc_mark)
12588         {
12589           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12590               || (rsec->owner->flags & DYNAMIC) != 0)
12591             rsec->gc_mark = 1;
12592           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12593             return FALSE;
12594         }
12595       if (!start_stop)
12596         break;
12597       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12598     }
12599   return TRUE;
12600 }
12601
12602 /* The mark phase of garbage collection.  For a given section, mark
12603    it and any sections in this section's group, and all the sections
12604    which define symbols to which it refers.  */
12605
12606 bfd_boolean
12607 _bfd_elf_gc_mark (struct bfd_link_info *info,
12608                   asection *sec,
12609                   elf_gc_mark_hook_fn gc_mark_hook)
12610 {
12611   bfd_boolean ret;
12612   asection *group_sec, *eh_frame;
12613
12614   sec->gc_mark = 1;
12615
12616   /* Mark all the sections in the group.  */
12617   group_sec = elf_section_data (sec)->next_in_group;
12618   if (group_sec && !group_sec->gc_mark)
12619     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12620       return FALSE;
12621
12622   /* Look through the section relocs.  */
12623   ret = TRUE;
12624   eh_frame = elf_eh_frame_section (sec->owner);
12625   if ((sec->flags & SEC_RELOC) != 0
12626       && sec->reloc_count > 0
12627       && sec != eh_frame)
12628     {
12629       struct elf_reloc_cookie cookie;
12630
12631       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12632         ret = FALSE;
12633       else
12634         {
12635           for (; cookie.rel < cookie.relend; cookie.rel++)
12636             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12637               {
12638                 ret = FALSE;
12639                 break;
12640               }
12641           fini_reloc_cookie_for_section (&cookie, sec);
12642         }
12643     }
12644
12645   if (ret && eh_frame && elf_fde_list (sec))
12646     {
12647       struct elf_reloc_cookie cookie;
12648
12649       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12650         ret = FALSE;
12651       else
12652         {
12653           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12654                                       gc_mark_hook, &cookie))
12655             ret = FALSE;
12656           fini_reloc_cookie_for_section (&cookie, eh_frame);
12657         }
12658     }
12659
12660   eh_frame = elf_section_eh_frame_entry (sec);
12661   if (ret && eh_frame && !eh_frame->gc_mark)
12662     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12663       ret = FALSE;
12664
12665   return ret;
12666 }
12667
12668 /* Scan and mark sections in a special or debug section group.  */
12669
12670 static void
12671 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12672 {
12673   /* Point to first section of section group.  */
12674   asection *ssec;
12675   /* Used to iterate the section group.  */
12676   asection *msec;
12677
12678   bfd_boolean is_special_grp = TRUE;
12679   bfd_boolean is_debug_grp = TRUE;
12680
12681   /* First scan to see if group contains any section other than debug
12682      and special section.  */
12683   ssec = msec = elf_next_in_group (grp);
12684   do
12685     {
12686       if ((msec->flags & SEC_DEBUGGING) == 0)
12687         is_debug_grp = FALSE;
12688
12689       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12690         is_special_grp = FALSE;
12691
12692       msec = elf_next_in_group (msec);
12693     }
12694   while (msec != ssec);
12695
12696   /* If this is a pure debug section group or pure special section group,
12697      keep all sections in this group.  */
12698   if (is_debug_grp || is_special_grp)
12699     {
12700       do
12701         {
12702           msec->gc_mark = 1;
12703           msec = elf_next_in_group (msec);
12704         }
12705       while (msec != ssec);
12706     }
12707 }
12708
12709 /* Keep debug and special sections.  */
12710
12711 bfd_boolean
12712 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12713                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12714 {
12715   bfd *ibfd;
12716
12717   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12718     {
12719       asection *isec;
12720       bfd_boolean some_kept;
12721       bfd_boolean debug_frag_seen;
12722
12723       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12724         continue;
12725
12726       /* Ensure all linker created sections are kept,
12727          see if any other section is already marked,
12728          and note if we have any fragmented debug sections.  */
12729       debug_frag_seen = some_kept = FALSE;
12730       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12731         {
12732           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12733             isec->gc_mark = 1;
12734           else if (isec->gc_mark)
12735             some_kept = TRUE;
12736
12737           if (debug_frag_seen == FALSE
12738               && (isec->flags & SEC_DEBUGGING)
12739               && CONST_STRNEQ (isec->name, ".debug_line."))
12740             debug_frag_seen = TRUE;
12741         }
12742
12743       /* If no section in this file will be kept, then we can
12744          toss out the debug and special sections.  */
12745       if (!some_kept)
12746         continue;
12747
12748       /* Keep debug and special sections like .comment when they are
12749          not part of a group.  Also keep section groups that contain
12750          just debug sections or special sections.  */
12751       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12752         {
12753           if ((isec->flags & SEC_GROUP) != 0)
12754             _bfd_elf_gc_mark_debug_special_section_group (isec);
12755           else if (((isec->flags & SEC_DEBUGGING) != 0
12756                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12757                    && elf_next_in_group (isec) == NULL)
12758             isec->gc_mark = 1;
12759         }
12760
12761       if (! debug_frag_seen)
12762         continue;
12763
12764       /* Look for CODE sections which are going to be discarded,
12765          and find and discard any fragmented debug sections which
12766          are associated with that code section.  */
12767       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12768         if ((isec->flags & SEC_CODE) != 0
12769             && isec->gc_mark == 0)
12770           {
12771             unsigned int ilen;
12772             asection *dsec;
12773
12774             ilen = strlen (isec->name);
12775
12776             /* Association is determined by the name of the debug section
12777                containing the name of the code section as a suffix.  For
12778                example .debug_line.text.foo is a debug section associated
12779                with .text.foo.  */
12780             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12781               {
12782                 unsigned int dlen;
12783
12784                 if (dsec->gc_mark == 0
12785                     || (dsec->flags & SEC_DEBUGGING) == 0)
12786                   continue;
12787
12788                 dlen = strlen (dsec->name);
12789
12790                 if (dlen > ilen
12791                     && strncmp (dsec->name + (dlen - ilen),
12792                                 isec->name, ilen) == 0)
12793                   {
12794                     dsec->gc_mark = 0;
12795                   }
12796               }
12797           }
12798     }
12799   return TRUE;
12800 }
12801
12802 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12803
12804 struct elf_gc_sweep_symbol_info
12805 {
12806   struct bfd_link_info *info;
12807   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12808                        bfd_boolean);
12809 };
12810
12811 static bfd_boolean
12812 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12813 {
12814   if (!h->mark
12815       && (((h->root.type == bfd_link_hash_defined
12816             || h->root.type == bfd_link_hash_defweak)
12817            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12818                 && h->root.u.def.section->gc_mark))
12819           || h->root.type == bfd_link_hash_undefined
12820           || h->root.type == bfd_link_hash_undefweak))
12821     {
12822       struct elf_gc_sweep_symbol_info *inf;
12823
12824       inf = (struct elf_gc_sweep_symbol_info *) data;
12825       (*inf->hide_symbol) (inf->info, h, TRUE);
12826       h->def_regular = 0;
12827       h->ref_regular = 0;
12828       h->ref_regular_nonweak = 0;
12829     }
12830
12831   return TRUE;
12832 }
12833
12834 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12835
12836 typedef bfd_boolean (*gc_sweep_hook_fn)
12837   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12838
12839 static bfd_boolean
12840 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12841 {
12842   bfd *sub;
12843   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12844   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12845   unsigned long section_sym_count;
12846   struct elf_gc_sweep_symbol_info sweep_info;
12847
12848   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12849     {
12850       asection *o;
12851
12852       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12853           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12854         continue;
12855
12856       for (o = sub->sections; o != NULL; o = o->next)
12857         {
12858           /* When any section in a section group is kept, we keep all
12859              sections in the section group.  If the first member of
12860              the section group is excluded, we will also exclude the
12861              group section.  */
12862           if (o->flags & SEC_GROUP)
12863             {
12864               asection *first = elf_next_in_group (o);
12865               o->gc_mark = first->gc_mark;
12866             }
12867
12868           if (o->gc_mark)
12869             continue;
12870
12871           /* Skip sweeping sections already excluded.  */
12872           if (o->flags & SEC_EXCLUDE)
12873             continue;
12874
12875           /* Since this is early in the link process, it is simple
12876              to remove a section from the output.  */
12877           o->flags |= SEC_EXCLUDE;
12878
12879           if (info->print_gc_sections && o->size != 0)
12880             /* xgettext:c-format */
12881             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12882
12883           /* But we also have to update some of the relocation
12884              info we collected before.  */
12885           if (gc_sweep_hook
12886               && (o->flags & SEC_RELOC) != 0
12887               && o->reloc_count != 0
12888               && !((info->strip == strip_all || info->strip == strip_debugger)
12889                    && (o->flags & SEC_DEBUGGING) != 0)
12890               && !bfd_is_abs_section (o->output_section))
12891             {
12892               Elf_Internal_Rela *internal_relocs;
12893               bfd_boolean r;
12894
12895               internal_relocs
12896                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12897                                              info->keep_memory);
12898               if (internal_relocs == NULL)
12899                 return FALSE;
12900
12901               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12902
12903               if (elf_section_data (o)->relocs != internal_relocs)
12904                 free (internal_relocs);
12905
12906               if (!r)
12907                 return FALSE;
12908             }
12909         }
12910     }
12911
12912   /* Remove the symbols that were in the swept sections from the dynamic
12913      symbol table.  GCFIXME: Anyone know how to get them out of the
12914      static symbol table as well?  */
12915   sweep_info.info = info;
12916   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12917   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12918                           &sweep_info);
12919
12920   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12921   return TRUE;
12922 }
12923
12924 /* Propagate collected vtable information.  This is called through
12925    elf_link_hash_traverse.  */
12926
12927 static bfd_boolean
12928 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12929 {
12930   /* Those that are not vtables.  */
12931   if (h->vtable == NULL || h->vtable->parent == NULL)
12932     return TRUE;
12933
12934   /* Those vtables that do not have parents, we cannot merge.  */
12935   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12936     return TRUE;
12937
12938   /* If we've already been done, exit.  */
12939   if (h->vtable->used && h->vtable->used[-1])
12940     return TRUE;
12941
12942   /* Make sure the parent's table is up to date.  */
12943   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12944
12945   if (h->vtable->used == NULL)
12946     {
12947       /* None of this table's entries were referenced.  Re-use the
12948          parent's table.  */
12949       h->vtable->used = h->vtable->parent->vtable->used;
12950       h->vtable->size = h->vtable->parent->vtable->size;
12951     }
12952   else
12953     {
12954       size_t n;
12955       bfd_boolean *cu, *pu;
12956
12957       /* Or the parent's entries into ours.  */
12958       cu = h->vtable->used;
12959       cu[-1] = TRUE;
12960       pu = h->vtable->parent->vtable->used;
12961       if (pu != NULL)
12962         {
12963           const struct elf_backend_data *bed;
12964           unsigned int log_file_align;
12965
12966           bed = get_elf_backend_data (h->root.u.def.section->owner);
12967           log_file_align = bed->s->log_file_align;
12968           n = h->vtable->parent->vtable->size >> log_file_align;
12969           while (n--)
12970             {
12971               if (*pu)
12972                 *cu = TRUE;
12973               pu++;
12974               cu++;
12975             }
12976         }
12977     }
12978
12979   return TRUE;
12980 }
12981
12982 static bfd_boolean
12983 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12984 {
12985   asection *sec;
12986   bfd_vma hstart, hend;
12987   Elf_Internal_Rela *relstart, *relend, *rel;
12988   const struct elf_backend_data *bed;
12989   unsigned int log_file_align;
12990
12991   /* Take care of both those symbols that do not describe vtables as
12992      well as those that are not loaded.  */
12993   if (h->vtable == NULL || h->vtable->parent == NULL)
12994     return TRUE;
12995
12996   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12997               || h->root.type == bfd_link_hash_defweak);
12998
12999   sec = h->root.u.def.section;
13000   hstart = h->root.u.def.value;
13001   hend = hstart + h->size;
13002
13003   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13004   if (!relstart)
13005     return *(bfd_boolean *) okp = FALSE;
13006   bed = get_elf_backend_data (sec->owner);
13007   log_file_align = bed->s->log_file_align;
13008
13009   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
13010
13011   for (rel = relstart; rel < relend; ++rel)
13012     if (rel->r_offset >= hstart && rel->r_offset < hend)
13013       {
13014         /* If the entry is in use, do nothing.  */
13015         if (h->vtable->used
13016             && (rel->r_offset - hstart) < h->vtable->size)
13017           {
13018             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13019             if (h->vtable->used[entry])
13020               continue;
13021           }
13022         /* Otherwise, kill it.  */
13023         rel->r_offset = rel->r_info = rel->r_addend = 0;
13024       }
13025
13026   return TRUE;
13027 }
13028
13029 /* Mark sections containing dynamically referenced symbols.  When
13030    building shared libraries, we must assume that any visible symbol is
13031    referenced.  */
13032
13033 bfd_boolean
13034 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13035 {
13036   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13037   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13038
13039   if ((h->root.type == bfd_link_hash_defined
13040        || h->root.type == bfd_link_hash_defweak)
13041       && (h->ref_dynamic
13042           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13043               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13044               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13045               && (!bfd_link_executable (info)
13046                   || info->export_dynamic
13047                   || (h->dynamic
13048                       && d != NULL
13049                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13050               && (h->versioned >= versioned
13051                   || !bfd_hide_sym_by_version (info->version_info,
13052                                                h->root.root.string)))))
13053     h->root.u.def.section->flags |= SEC_KEEP;
13054
13055   return TRUE;
13056 }
13057
13058 /* Keep all sections containing symbols undefined on the command-line,
13059    and the section containing the entry symbol.  */
13060
13061 void
13062 _bfd_elf_gc_keep (struct bfd_link_info *info)
13063 {
13064   struct bfd_sym_chain *sym;
13065
13066   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13067     {
13068       struct elf_link_hash_entry *h;
13069
13070       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13071                                 FALSE, FALSE, FALSE);
13072
13073       if (h != NULL
13074           && (h->root.type == bfd_link_hash_defined
13075               || h->root.type == bfd_link_hash_defweak)
13076           && !bfd_is_abs_section (h->root.u.def.section)
13077           && !bfd_is_und_section (h->root.u.def.section))
13078         h->root.u.def.section->flags |= SEC_KEEP;
13079     }
13080 }
13081
13082 bfd_boolean
13083 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13084                                 struct bfd_link_info *info)
13085 {
13086   bfd *ibfd = info->input_bfds;
13087
13088   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13089     {
13090       asection *sec;
13091       struct elf_reloc_cookie cookie;
13092
13093       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13094         continue;
13095
13096       if (!init_reloc_cookie (&cookie, info, ibfd))
13097         return FALSE;
13098
13099       for (sec = ibfd->sections; sec; sec = sec->next)
13100         {
13101           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13102               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13103             {
13104               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13105               fini_reloc_cookie_rels (&cookie, sec);
13106             }
13107         }
13108     }
13109   return TRUE;
13110 }
13111
13112 /* Do mark and sweep of unused sections.  */
13113
13114 bfd_boolean
13115 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13116 {
13117   bfd_boolean ok = TRUE;
13118   bfd *sub;
13119   elf_gc_mark_hook_fn gc_mark_hook;
13120   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13121   struct elf_link_hash_table *htab;
13122
13123   if (!bed->can_gc_sections
13124       || !is_elf_hash_table (info->hash))
13125     {
13126       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13127       return TRUE;
13128     }
13129
13130   bed->gc_keep (info);
13131   htab = elf_hash_table (info);
13132
13133   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13134      at the .eh_frame section if we can mark the FDEs individually.  */
13135   for (sub = info->input_bfds;
13136        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13137        sub = sub->link.next)
13138     {
13139       asection *sec;
13140       struct elf_reloc_cookie cookie;
13141
13142       sec = bfd_get_section_by_name (sub, ".eh_frame");
13143       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13144         {
13145           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13146           if (elf_section_data (sec)->sec_info
13147               && (sec->flags & SEC_LINKER_CREATED) == 0)
13148             elf_eh_frame_section (sub) = sec;
13149           fini_reloc_cookie_for_section (&cookie, sec);
13150           sec = bfd_get_next_section_by_name (NULL, sec);
13151         }
13152     }
13153
13154   /* Apply transitive closure to the vtable entry usage info.  */
13155   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13156   if (!ok)
13157     return FALSE;
13158
13159   /* Kill the vtable relocations that were not used.  */
13160   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13161   if (!ok)
13162     return FALSE;
13163
13164   /* Mark dynamically referenced symbols.  */
13165   if (htab->dynamic_sections_created)
13166     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13167
13168   /* Grovel through relocs to find out who stays ...  */
13169   gc_mark_hook = bed->gc_mark_hook;
13170   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13171     {
13172       asection *o;
13173
13174       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13175           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13176         continue;
13177
13178       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13179          Also treat note sections as a root, if the section is not part
13180          of a group.  */
13181       for (o = sub->sections; o != NULL; o = o->next)
13182         if (!o->gc_mark
13183             && (o->flags & SEC_EXCLUDE) == 0
13184             && ((o->flags & SEC_KEEP) != 0
13185                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13186                     && elf_next_in_group (o) == NULL )))
13187           {
13188             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13189               return FALSE;
13190           }
13191     }
13192
13193   /* Allow the backend to mark additional target specific sections.  */
13194   bed->gc_mark_extra_sections (info, gc_mark_hook);
13195
13196   /* ... and mark SEC_EXCLUDE for those that go.  */
13197   return elf_gc_sweep (abfd, info);
13198 }
13199 \f
13200 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13201
13202 bfd_boolean
13203 bfd_elf_gc_record_vtinherit (bfd *abfd,
13204                              asection *sec,
13205                              struct elf_link_hash_entry *h,
13206                              bfd_vma offset)
13207 {
13208   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13209   struct elf_link_hash_entry **search, *child;
13210   size_t extsymcount;
13211   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13212
13213   /* The sh_info field of the symtab header tells us where the
13214      external symbols start.  We don't care about the local symbols at
13215      this point.  */
13216   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13217   if (!elf_bad_symtab (abfd))
13218     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13219
13220   sym_hashes = elf_sym_hashes (abfd);
13221   sym_hashes_end = sym_hashes + extsymcount;
13222
13223   /* Hunt down the child symbol, which is in this section at the same
13224      offset as the relocation.  */
13225   for (search = sym_hashes; search != sym_hashes_end; ++search)
13226     {
13227       if ((child = *search) != NULL
13228           && (child->root.type == bfd_link_hash_defined
13229               || child->root.type == bfd_link_hash_defweak)
13230           && child->root.u.def.section == sec
13231           && child->root.u.def.value == offset)
13232         goto win;
13233     }
13234
13235   /* xgettext:c-format */
13236   _bfd_error_handler (_("%B: %A+%lu: No symbol found for INHERIT"),
13237                       abfd, sec, (unsigned long) offset);
13238   bfd_set_error (bfd_error_invalid_operation);
13239   return FALSE;
13240
13241  win:
13242   if (!child->vtable)
13243     {
13244       child->vtable = ((struct elf_link_virtual_table_entry *)
13245                        bfd_zalloc (abfd, sizeof (*child->vtable)));
13246       if (!child->vtable)
13247         return FALSE;
13248     }
13249   if (!h)
13250     {
13251       /* This *should* only be the absolute section.  It could potentially
13252          be that someone has defined a non-global vtable though, which
13253          would be bad.  It isn't worth paging in the local symbols to be
13254          sure though; that case should simply be handled by the assembler.  */
13255
13256       child->vtable->parent = (struct elf_link_hash_entry *) -1;
13257     }
13258   else
13259     child->vtable->parent = h;
13260
13261   return TRUE;
13262 }
13263
13264 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13265
13266 bfd_boolean
13267 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13268                            asection *sec ATTRIBUTE_UNUSED,
13269                            struct elf_link_hash_entry *h,
13270                            bfd_vma addend)
13271 {
13272   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13273   unsigned int log_file_align = bed->s->log_file_align;
13274
13275   if (!h->vtable)
13276     {
13277       h->vtable = ((struct elf_link_virtual_table_entry *)
13278                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13279       if (!h->vtable)
13280         return FALSE;
13281     }
13282
13283   if (addend >= h->vtable->size)
13284     {
13285       size_t size, bytes, file_align;
13286       bfd_boolean *ptr = h->vtable->used;
13287
13288       /* While the symbol is undefined, we have to be prepared to handle
13289          a zero size.  */
13290       file_align = 1 << log_file_align;
13291       if (h->root.type == bfd_link_hash_undefined)
13292         size = addend + file_align;
13293       else
13294         {
13295           size = h->size;
13296           if (addend >= size)
13297             {
13298               /* Oops!  We've got a reference past the defined end of
13299                  the table.  This is probably a bug -- shall we warn?  */
13300               size = addend + file_align;
13301             }
13302         }
13303       size = (size + file_align - 1) & -file_align;
13304
13305       /* Allocate one extra entry for use as a "done" flag for the
13306          consolidation pass.  */
13307       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13308
13309       if (ptr)
13310         {
13311           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13312
13313           if (ptr != NULL)
13314             {
13315               size_t oldbytes;
13316
13317               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13318                           * sizeof (bfd_boolean));
13319               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13320             }
13321         }
13322       else
13323         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13324
13325       if (ptr == NULL)
13326         return FALSE;
13327
13328       /* And arrange for that done flag to be at index -1.  */
13329       h->vtable->used = ptr + 1;
13330       h->vtable->size = size;
13331     }
13332
13333   h->vtable->used[addend >> log_file_align] = TRUE;
13334
13335   return TRUE;
13336 }
13337
13338 /* Map an ELF section header flag to its corresponding string.  */
13339 typedef struct
13340 {
13341   char *flag_name;
13342   flagword flag_value;
13343 } elf_flags_to_name_table;
13344
13345 static elf_flags_to_name_table elf_flags_to_names [] =
13346 {
13347   { "SHF_WRITE", SHF_WRITE },
13348   { "SHF_ALLOC", SHF_ALLOC },
13349   { "SHF_EXECINSTR", SHF_EXECINSTR },
13350   { "SHF_MERGE", SHF_MERGE },
13351   { "SHF_STRINGS", SHF_STRINGS },
13352   { "SHF_INFO_LINK", SHF_INFO_LINK},
13353   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13354   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13355   { "SHF_GROUP", SHF_GROUP },
13356   { "SHF_TLS", SHF_TLS },
13357   { "SHF_MASKOS", SHF_MASKOS },
13358   { "SHF_EXCLUDE", SHF_EXCLUDE },
13359 };
13360
13361 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13362 bfd_boolean
13363 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13364                               struct flag_info *flaginfo,
13365                               asection *section)
13366 {
13367   const bfd_vma sh_flags = elf_section_flags (section);
13368
13369   if (!flaginfo->flags_initialized)
13370     {
13371       bfd *obfd = info->output_bfd;
13372       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13373       struct flag_info_list *tf = flaginfo->flag_list;
13374       int with_hex = 0;
13375       int without_hex = 0;
13376
13377       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13378         {
13379           unsigned i;
13380           flagword (*lookup) (char *);
13381
13382           lookup = bed->elf_backend_lookup_section_flags_hook;
13383           if (lookup != NULL)
13384             {
13385               flagword hexval = (*lookup) ((char *) tf->name);
13386
13387               if (hexval != 0)
13388                 {
13389                   if (tf->with == with_flags)
13390                     with_hex |= hexval;
13391                   else if (tf->with == without_flags)
13392                     without_hex |= hexval;
13393                   tf->valid = TRUE;
13394                   continue;
13395                 }
13396             }
13397           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13398             {
13399               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13400                 {
13401                   if (tf->with == with_flags)
13402                     with_hex |= elf_flags_to_names[i].flag_value;
13403                   else if (tf->with == without_flags)
13404                     without_hex |= elf_flags_to_names[i].flag_value;
13405                   tf->valid = TRUE;
13406                   break;
13407                 }
13408             }
13409           if (!tf->valid)
13410             {
13411               info->callbacks->einfo
13412                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13413               return FALSE;
13414             }
13415         }
13416       flaginfo->flags_initialized = TRUE;
13417       flaginfo->only_with_flags |= with_hex;
13418       flaginfo->not_with_flags |= without_hex;
13419     }
13420
13421   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13422     return FALSE;
13423
13424   if ((flaginfo->not_with_flags & sh_flags) != 0)
13425     return FALSE;
13426
13427   return TRUE;
13428 }
13429
13430 struct alloc_got_off_arg {
13431   bfd_vma gotoff;
13432   struct bfd_link_info *info;
13433 };
13434
13435 /* We need a special top-level link routine to convert got reference counts
13436    to real got offsets.  */
13437
13438 static bfd_boolean
13439 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13440 {
13441   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13442   bfd *obfd = gofarg->info->output_bfd;
13443   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13444
13445   if (h->got.refcount > 0)
13446     {
13447       h->got.offset = gofarg->gotoff;
13448       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13449     }
13450   else
13451     h->got.offset = (bfd_vma) -1;
13452
13453   return TRUE;
13454 }
13455
13456 /* And an accompanying bit to work out final got entry offsets once
13457    we're done.  Should be called from final_link.  */
13458
13459 bfd_boolean
13460 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13461                                         struct bfd_link_info *info)
13462 {
13463   bfd *i;
13464   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13465   bfd_vma gotoff;
13466   struct alloc_got_off_arg gofarg;
13467
13468   BFD_ASSERT (abfd == info->output_bfd);
13469
13470   if (! is_elf_hash_table (info->hash))
13471     return FALSE;
13472
13473   /* The GOT offset is relative to the .got section, but the GOT header is
13474      put into the .got.plt section, if the backend uses it.  */
13475   if (bed->want_got_plt)
13476     gotoff = 0;
13477   else
13478     gotoff = bed->got_header_size;
13479
13480   /* Do the local .got entries first.  */
13481   for (i = info->input_bfds; i; i = i->link.next)
13482     {
13483       bfd_signed_vma *local_got;
13484       size_t j, locsymcount;
13485       Elf_Internal_Shdr *symtab_hdr;
13486
13487       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13488         continue;
13489
13490       local_got = elf_local_got_refcounts (i);
13491       if (!local_got)
13492         continue;
13493
13494       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13495       if (elf_bad_symtab (i))
13496         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13497       else
13498         locsymcount = symtab_hdr->sh_info;
13499
13500       for (j = 0; j < locsymcount; ++j)
13501         {
13502           if (local_got[j] > 0)
13503             {
13504               local_got[j] = gotoff;
13505               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13506             }
13507           else
13508             local_got[j] = (bfd_vma) -1;
13509         }
13510     }
13511
13512   /* Then the global .got entries.  .plt refcounts are handled by
13513      adjust_dynamic_symbol  */
13514   gofarg.gotoff = gotoff;
13515   gofarg.info = info;
13516   elf_link_hash_traverse (elf_hash_table (info),
13517                           elf_gc_allocate_got_offsets,
13518                           &gofarg);
13519   return TRUE;
13520 }
13521
13522 /* Many folk need no more in the way of final link than this, once
13523    got entry reference counting is enabled.  */
13524
13525 bfd_boolean
13526 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13527 {
13528   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13529     return FALSE;
13530
13531   /* Invoke the regular ELF backend linker to do all the work.  */
13532   return bfd_elf_final_link (abfd, info);
13533 }
13534
13535 bfd_boolean
13536 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13537 {
13538   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13539
13540   if (rcookie->bad_symtab)
13541     rcookie->rel = rcookie->rels;
13542
13543   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13544     {
13545       unsigned long r_symndx;
13546
13547       if (! rcookie->bad_symtab)
13548         if (rcookie->rel->r_offset > offset)
13549           return FALSE;
13550       if (rcookie->rel->r_offset != offset)
13551         continue;
13552
13553       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13554       if (r_symndx == STN_UNDEF)
13555         return TRUE;
13556
13557       if (r_symndx >= rcookie->locsymcount
13558           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13559         {
13560           struct elf_link_hash_entry *h;
13561
13562           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13563
13564           while (h->root.type == bfd_link_hash_indirect
13565                  || h->root.type == bfd_link_hash_warning)
13566             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13567
13568           if ((h->root.type == bfd_link_hash_defined
13569                || h->root.type == bfd_link_hash_defweak)
13570               && (h->root.u.def.section->owner != rcookie->abfd
13571                   || h->root.u.def.section->kept_section != NULL
13572                   || discarded_section (h->root.u.def.section)))
13573             return TRUE;
13574         }
13575       else
13576         {
13577           /* It's not a relocation against a global symbol,
13578              but it could be a relocation against a local
13579              symbol for a discarded section.  */
13580           asection *isec;
13581           Elf_Internal_Sym *isym;
13582
13583           /* Need to: get the symbol; get the section.  */
13584           isym = &rcookie->locsyms[r_symndx];
13585           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13586           if (isec != NULL
13587               && (isec->kept_section != NULL
13588                   || discarded_section (isec)))
13589             return TRUE;
13590         }
13591       return FALSE;
13592     }
13593   return FALSE;
13594 }
13595
13596 /* Discard unneeded references to discarded sections.
13597    Returns -1 on error, 1 if any section's size was changed, 0 if
13598    nothing changed.  This function assumes that the relocations are in
13599    sorted order, which is true for all known assemblers.  */
13600
13601 int
13602 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13603 {
13604   struct elf_reloc_cookie cookie;
13605   asection *o;
13606   bfd *abfd;
13607   int changed = 0;
13608
13609   if (info->traditional_format
13610       || !is_elf_hash_table (info->hash))
13611     return 0;
13612
13613   o = bfd_get_section_by_name (output_bfd, ".stab");
13614   if (o != NULL)
13615     {
13616       asection *i;
13617
13618       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13619         {
13620           if (i->size == 0
13621               || i->reloc_count == 0
13622               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13623             continue;
13624
13625           abfd = i->owner;
13626           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13627             continue;
13628
13629           if (!init_reloc_cookie_for_section (&cookie, info, i))
13630             return -1;
13631
13632           if (_bfd_discard_section_stabs (abfd, i,
13633                                           elf_section_data (i)->sec_info,
13634                                           bfd_elf_reloc_symbol_deleted_p,
13635                                           &cookie))
13636             changed = 1;
13637
13638           fini_reloc_cookie_for_section (&cookie, i);
13639         }
13640     }
13641
13642   o = NULL;
13643   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13644     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13645   if (o != NULL)
13646     {
13647       asection *i;
13648
13649       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13650         {
13651           if (i->size == 0)
13652             continue;
13653
13654           abfd = i->owner;
13655           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13656             continue;
13657
13658           if (!init_reloc_cookie_for_section (&cookie, info, i))
13659             return -1;
13660
13661           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13662           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13663                                                  bfd_elf_reloc_symbol_deleted_p,
13664                                                  &cookie))
13665             changed = 1;
13666
13667           fini_reloc_cookie_for_section (&cookie, i);
13668         }
13669     }
13670
13671   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13672     {
13673       const struct elf_backend_data *bed;
13674
13675       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13676         continue;
13677
13678       bed = get_elf_backend_data (abfd);
13679
13680       if (bed->elf_backend_discard_info != NULL)
13681         {
13682           if (!init_reloc_cookie (&cookie, info, abfd))
13683             return -1;
13684
13685           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13686             changed = 1;
13687
13688           fini_reloc_cookie (&cookie, abfd);
13689         }
13690     }
13691
13692   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13693     _bfd_elf_end_eh_frame_parsing (info);
13694
13695   if (info->eh_frame_hdr_type
13696       && !bfd_link_relocatable (info)
13697       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13698     changed = 1;
13699
13700   return changed;
13701 }
13702
13703 bfd_boolean
13704 _bfd_elf_section_already_linked (bfd *abfd,
13705                                  asection *sec,
13706                                  struct bfd_link_info *info)
13707 {
13708   flagword flags;
13709   const char *name, *key;
13710   struct bfd_section_already_linked *l;
13711   struct bfd_section_already_linked_hash_entry *already_linked_list;
13712
13713   if (sec->output_section == bfd_abs_section_ptr)
13714     return FALSE;
13715
13716   flags = sec->flags;
13717
13718   /* Return if it isn't a linkonce section.  A comdat group section
13719      also has SEC_LINK_ONCE set.  */
13720   if ((flags & SEC_LINK_ONCE) == 0)
13721     return FALSE;
13722
13723   /* Don't put group member sections on our list of already linked
13724      sections.  They are handled as a group via their group section.  */
13725   if (elf_sec_group (sec) != NULL)
13726     return FALSE;
13727
13728   /* For a SHT_GROUP section, use the group signature as the key.  */
13729   name = sec->name;
13730   if ((flags & SEC_GROUP) != 0
13731       && elf_next_in_group (sec) != NULL
13732       && elf_group_name (elf_next_in_group (sec)) != NULL)
13733     key = elf_group_name (elf_next_in_group (sec));
13734   else
13735     {
13736       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13737       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13738           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13739         key++;
13740       else
13741         /* Must be a user linkonce section that doesn't follow gcc's
13742            naming convention.  In this case we won't be matching
13743            single member groups.  */
13744         key = name;
13745     }
13746
13747   already_linked_list = bfd_section_already_linked_table_lookup (key);
13748
13749   for (l = already_linked_list->entry; l != NULL; l = l->next)
13750     {
13751       /* We may have 2 different types of sections on the list: group
13752          sections with a signature of <key> (<key> is some string),
13753          and linkonce sections named .gnu.linkonce.<type>.<key>.
13754          Match like sections.  LTO plugin sections are an exception.
13755          They are always named .gnu.linkonce.t.<key> and match either
13756          type of section.  */
13757       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13758            && ((flags & SEC_GROUP) != 0
13759                || strcmp (name, l->sec->name) == 0))
13760           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13761         {
13762           /* The section has already been linked.  See if we should
13763              issue a warning.  */
13764           if (!_bfd_handle_already_linked (sec, l, info))
13765             return FALSE;
13766
13767           if (flags & SEC_GROUP)
13768             {
13769               asection *first = elf_next_in_group (sec);
13770               asection *s = first;
13771
13772               while (s != NULL)
13773                 {
13774                   s->output_section = bfd_abs_section_ptr;
13775                   /* Record which group discards it.  */
13776                   s->kept_section = l->sec;
13777                   s = elf_next_in_group (s);
13778                   /* These lists are circular.  */
13779                   if (s == first)
13780                     break;
13781                 }
13782             }
13783
13784           return TRUE;
13785         }
13786     }
13787
13788   /* A single member comdat group section may be discarded by a
13789      linkonce section and vice versa.  */
13790   if ((flags & SEC_GROUP) != 0)
13791     {
13792       asection *first = elf_next_in_group (sec);
13793
13794       if (first != NULL && elf_next_in_group (first) == first)
13795         /* Check this single member group against linkonce sections.  */
13796         for (l = already_linked_list->entry; l != NULL; l = l->next)
13797           if ((l->sec->flags & SEC_GROUP) == 0
13798               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13799             {
13800               first->output_section = bfd_abs_section_ptr;
13801               first->kept_section = l->sec;
13802               sec->output_section = bfd_abs_section_ptr;
13803               break;
13804             }
13805     }
13806   else
13807     /* Check this linkonce section against single member groups.  */
13808     for (l = already_linked_list->entry; l != NULL; l = l->next)
13809       if (l->sec->flags & SEC_GROUP)
13810         {
13811           asection *first = elf_next_in_group (l->sec);
13812
13813           if (first != NULL
13814               && elf_next_in_group (first) == first
13815               && bfd_elf_match_symbols_in_sections (first, sec, info))
13816             {
13817               sec->output_section = bfd_abs_section_ptr;
13818               sec->kept_section = first;
13819               break;
13820             }
13821         }
13822
13823   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13824      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13825      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13826      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13827      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13828      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13829      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13830      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13831      The reverse order cannot happen as there is never a bfd with only the
13832      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13833      matter as here were are looking only for cross-bfd sections.  */
13834
13835   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13836     for (l = already_linked_list->entry; l != NULL; l = l->next)
13837       if ((l->sec->flags & SEC_GROUP) == 0
13838           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13839         {
13840           if (abfd != l->sec->owner)
13841             sec->output_section = bfd_abs_section_ptr;
13842           break;
13843         }
13844
13845   /* This is the first section with this name.  Record it.  */
13846   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13847     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13848   return sec->output_section == bfd_abs_section_ptr;
13849 }
13850
13851 bfd_boolean
13852 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13853 {
13854   return sym->st_shndx == SHN_COMMON;
13855 }
13856
13857 unsigned int
13858 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13859 {
13860   return SHN_COMMON;
13861 }
13862
13863 asection *
13864 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13865 {
13866   return bfd_com_section_ptr;
13867 }
13868
13869 bfd_vma
13870 _bfd_elf_default_got_elt_size (bfd *abfd,
13871                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13872                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13873                                bfd *ibfd ATTRIBUTE_UNUSED,
13874                                unsigned long symndx ATTRIBUTE_UNUSED)
13875 {
13876   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13877   return bed->s->arch_size / 8;
13878 }
13879
13880 /* Routines to support the creation of dynamic relocs.  */
13881
13882 /* Returns the name of the dynamic reloc section associated with SEC.  */
13883
13884 static const char *
13885 get_dynamic_reloc_section_name (bfd *       abfd,
13886                                 asection *  sec,
13887                                 bfd_boolean is_rela)
13888 {
13889   char *name;
13890   const char *old_name = bfd_get_section_name (NULL, sec);
13891   const char *prefix = is_rela ? ".rela" : ".rel";
13892
13893   if (old_name == NULL)
13894     return NULL;
13895
13896   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13897   sprintf (name, "%s%s", prefix, old_name);
13898
13899   return name;
13900 }
13901
13902 /* Returns the dynamic reloc section associated with SEC.
13903    If necessary compute the name of the dynamic reloc section based
13904    on SEC's name (looked up in ABFD's string table) and the setting
13905    of IS_RELA.  */
13906
13907 asection *
13908 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13909                                     asection *  sec,
13910                                     bfd_boolean is_rela)
13911 {
13912   asection * reloc_sec = elf_section_data (sec)->sreloc;
13913
13914   if (reloc_sec == NULL)
13915     {
13916       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13917
13918       if (name != NULL)
13919         {
13920           reloc_sec = bfd_get_linker_section (abfd, name);
13921
13922           if (reloc_sec != NULL)
13923             elf_section_data (sec)->sreloc = reloc_sec;
13924         }
13925     }
13926
13927   return reloc_sec;
13928 }
13929
13930 /* Returns the dynamic reloc section associated with SEC.  If the
13931    section does not exist it is created and attached to the DYNOBJ
13932    bfd and stored in the SRELOC field of SEC's elf_section_data
13933    structure.
13934
13935    ALIGNMENT is the alignment for the newly created section and
13936    IS_RELA defines whether the name should be .rela.<SEC's name>
13937    or .rel.<SEC's name>.  The section name is looked up in the
13938    string table associated with ABFD.  */
13939
13940 asection *
13941 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13942                                      bfd *dynobj,
13943                                      unsigned int alignment,
13944                                      bfd *abfd,
13945                                      bfd_boolean is_rela)
13946 {
13947   asection * reloc_sec = elf_section_data (sec)->sreloc;
13948
13949   if (reloc_sec == NULL)
13950     {
13951       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13952
13953       if (name == NULL)
13954         return NULL;
13955
13956       reloc_sec = bfd_get_linker_section (dynobj, name);
13957
13958       if (reloc_sec == NULL)
13959         {
13960           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13961                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13962           if ((sec->flags & SEC_ALLOC) != 0)
13963             flags |= SEC_ALLOC | SEC_LOAD;
13964
13965           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13966           if (reloc_sec != NULL)
13967             {
13968               /* _bfd_elf_get_sec_type_attr chooses a section type by
13969                  name.  Override as it may be wrong, eg. for a user
13970                  section named "auto" we'll get ".relauto" which is
13971                  seen to be a .rela section.  */
13972               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13973               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13974                 reloc_sec = NULL;
13975             }
13976         }
13977
13978       elf_section_data (sec)->sreloc = reloc_sec;
13979     }
13980
13981   return reloc_sec;
13982 }
13983
13984 /* Copy the ELF symbol type and other attributes for a linker script
13985    assignment from HSRC to HDEST.  Generally this should be treated as
13986    if we found a strong non-dynamic definition for HDEST (except that
13987    ld ignores multiple definition errors).  */
13988 void
13989 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13990                                      struct bfd_link_hash_entry *hdest,
13991                                      struct bfd_link_hash_entry *hsrc)
13992 {
13993   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13994   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13995   Elf_Internal_Sym isym;
13996
13997   ehdest->type = ehsrc->type;
13998   ehdest->target_internal = ehsrc->target_internal;
13999
14000   isym.st_other = ehsrc->other;
14001   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14002 }
14003
14004 /* Append a RELA relocation REL to section S in BFD.  */
14005
14006 void
14007 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14008 {
14009   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14010   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14011   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14012   bed->s->swap_reloca_out (abfd, rel, loc);
14013 }
14014
14015 /* Append a REL relocation REL to section S in BFD.  */
14016
14017 void
14018 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14019 {
14020   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14021   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14022   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14023   bed->s->swap_reloc_out (abfd, rel, loc);
14024 }